Jakir Hossain
Jakir Hossain

Reputation: 390

Drawing in MigraDoc document using XGraphics

I have generated some PDF report using MigraDoc. Initial code is as follows:-

MigraDoc.DocumentObjectModel.Document document = new MigraDoc.DocumentObjectModel.Document();

MigraDoc.DocumentObjectModel.Section section = document.AddSection();
...

Paragraph paragraph = section.Headers.Primary.AddParagraph();
....

table = section.AddTable();
...

paragraph = section.Footers.Primary.AddParagraph();
...

The PDF was rendered successfully. Now I want to add some graphics into the pages of this document. I have gone through several articles for that and found that everyone using PdfDocument class instead of MigraDoc.DocumentObjectModel.Document. Is it possible to apply graphics into pages of a document of type MigraDoc.DocumentObjectModel.Document using XGraphics? If it is not possible, what is the best way to mix PdfDocument with MigraDoc.DocumentObjectModel.Document to accomplish the same?

Upvotes: 2

Views: 4003

Answers (1)

MigraDoc uses PDFsharp and an XGraphics object to create the PDF pages.

There are several ways to add content to pages created by MigraDoc.

This MigraDoc sample shows some options:
http://pdfsharp.net/wiki/MixMigraDocAndPdfSharp-sample.ashx

You can even call MigraDoc to use "your" XGraphics object for drawing:

// Alternative rendering with progress indicator.
// Set a callback for phase 1.
pdfRenderer.DocumentRenderer.PrepareDocumentProgress += PrepareDocumentProgress;
// Now start phase 1: Preparing pages (i.e. calculate the layout).
pdfRenderer.PrepareRenderPages();

// Now phase 2: create the PDF pages.
Console.WriteLine("\r\nRendering document ...");

int pages = pdfRenderer.DocumentRenderer.FormattedDocument.PageCount;
for (int i = 1; i <= pages; ++i)
{
    var page = pdfRenderer.PdfDocument.AddPage();
    Console.Write("\rRendering page " + i + "/" + pages);

    PageInfo pageInfo = pdfRenderer.DocumentRenderer.FormattedDocument.GetPageInfo(i);
    page.Width = pageInfo.Width;
    page.Height = pageInfo.Height;
    page.Orientation = pageInfo.Orientation;

    using (XGraphics gfx = XGraphics.FromPdfPage(page))
    {
        gfx.MUH = pdfRenderer.Unicode ? PdfFontEncoding.Unicode : PdfFontEncoding.WinAnsi;
        gfx.MFEH = pdfRenderer.FontEmbedding;
        pdfRenderer.DocumentRenderer.RenderPage(gfx, i);
    }
}
Console.WriteLine("\r\nSaving document ...");

Sample code taken from this post:
http://forum.pdfsharp.net/viewtopic.php?p=9293#p9293

Upvotes: 3

Related Questions