PDFsharp and MigraDoc Foundation (Fundamentals)

    Since the article, due to which I received an invite, disappeared somewhere, I want to publish it again.

    Due to the small number of free libraries for working with PDF in .Net and the insufficient coverage of them in Russian, I want to talk about working with such a wonderful library as PDFsharp and MigradDoc. Let's

    start from the very beginning - the sources can be downloaded here or here.
    Now add links to your project :
    using MigraDoc;
    using PdfSharp;
    using MigraDoc.DocumentObjectModel;
    using MigraDoc.Rendering;
    using PdfSharp.Pdf;
    

    Create a new document
    Document document = new Document();
    

    Each MigraDoc document consists of independent sections, which can have their own format.
    Section Creation:
    Section section = document.AddSection();
    after such initialization, working with section - we work with part of the document document .
    A section has functions for working with information, such as Add, AddParagraph (), AddImage (), AddTable () , etc., as well as a class for changing the format of the PageSetup section itself .
    Format change:
    section.PageSetup.PageFormat = PageFormat.А5;//стандартный размер страницы
    section.PageSetup.Orientation = Orientation.Portrait;//ориентация
    section.PageSetup.BottomMargin = 10;//нижний отступ
    section.PageSetup.TopMargin = 10;//верхний отступ

    Information is added either using Add (Param) , where Param is a paragraph (Paragraph), a picture (Image), a table (Table), a chart (Chart) or a text frame (TextFrame)
    Paragraph paragraph =new Paragraph();
    section.Add(paragraph);

    or following the example of adding a section
    Paragraph paragraph = section.AddParagraph();

    Moreover, for each paragraph it is also possible to set an individual format (class Format) and style (class Style):
    paragraph.Format.Font.Color = Color.FromCmyk(100, 30, 20, 50);

    For each paragraph, you can add information:
    Text text = new Text("text");
    paragraph.AddText("text");//текст
    paragraph.AddFormattedText("formatted text", styleName);// форматированный текст
    paragraph.Add(text);//добавление любого из перечисленых ниже
    paragraph.AddBookmark("Bookmark");//закладка
    paragraph.AddChar('c');//символ
    paragraph.AddDateField("10.10.2010");//дата
    paragraph.AddFootnote("Footnote");//нижняя подпись
    //и еще много чего

    We have collected the basis, now it remains to turn it into a full-fledged PDF document, for which PdfDocumentRenderer is used:
    pdfRenderer = new PdfDocumentRenderer(true, PdfFontEmbedding.Always);
    pdfRenderer.Document = document;
    pdfRenderer.RenderDocument();
    pdfRenderer.PdfDocument.Save(filePath);// сохраняем

    You may need to use fonts that are not installed by default in the OS, for example, DejaVuSansMono.ttf . You can do this by first placing the file of the above font in the same folder where the executable file is:
    Uri uri = new Uri(@"file://" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + @"\DejaVuSansMono.ttf");
    XPrivateFontCollection pfc = XPrivateFontCollection.Global;
    try
    {
          pfc.Add(uri, "./#DejaVu Sans Mono");
    }
    catch (Exception)
    {}
    pdfRenderer.DocumentRenderer.PrivateFonts = pfc;

    If you need to display the created document in your application, MigraDoc.Rendering.Windows.DocumentPreview , a control for outputting documents created in MigraDoc , will help us . First you need to put it on a form or WPF window, and then use the following code:
    Document doc = new Document();
    doc = oDocument.Clone();
    preview.Ddl = DdlWriter.WriteToString(doc);

    The ability to display already created PDF documents is unfortunately not available.
    I recommend that you pay attention to the Clone () function , which is important when assigning any MigraDoc objects (documents, sections, paragraphs, etc.), if you do not use it, changing the first object will change the one that was assigned to the first.
    To print MigraDoc documents, you can use MigraDocPrintDocument :
    MigraDocPrintDocument migraDocPrint = new MigraDocPrintDocument(preview.Renderer);
    migraDocPrint.Print();

    But such a problem was noticed that this method does not work when printing through a server, printing through a local printer is normal.
    Therefore, as an option, you can use Foxit Reader to print:
    pdfDocumentRenderer.PdfDocument.Save(@"temp.pdf");
    Process.Start(@"Resources\Foxit Reader.exe", @"/p temp.pdf"); 
    

    In conclusion, I want to say that having tested all the libraries from this post, I settled on this library as the most convenient and having ample opportunities.

    Also popular now: