Search code examples
c#pdf-generationpdfsharpmigradoc

Add an external PDF page to PDFSharp/MigraDoc


I currently build a PDF file with MigraDoc, I then render the document which creates a PdfDocument (PDFSharp) so I can ad external pages from other PDFs (because from my understanding MigraDoc does no have the "notion" of pages and thus cannot add external pages)

My current PDF file format is:

(PDFSharp) Page 1 --- 
(PDFSharp) Page 2   | (MigraDoc) Section 1
(PDFSharp) Page 3 ---
(PDFSharp) Page 4 --- (MigraDoc) Section 2
(PDFSharp) Page 5 --- (MigraDoc) Section 2
(PDFSharp) Page 6 --- (MigraDoc) Section 3
(PDFSharp) External Page 1
(PDFSharp) External Page 2
(PDFSharp) External Page 3
(PDFSharp) External Page 4

I need to have something like:

(PDFSharp) Page 1 --- 
(PDFSharp) Page 2   | (MigraDoc) Section 1
(PDFSharp) Page 3 ---
(PDFSharp) External Page 1
(PDFSharp) External Page 2
(PDFSharp) Page 4 --- (MigraDoc) Section 2
(PDFSharp) Page 5 --- (MigraDoc) Section 2
(PDFSharp) External Page 3
(PDFSharp) External Page 4
(PDFSharp) Page 6 --- (MigraDoc) Section 3

I need to have the external pages mixed with the my own created pages, but as I create them with MigraDoc which works with sections I don't know the page number to add the external pages at and when I render them I loose the sections and have only pages that are not related in any manner, thus I do not know when a section ends to add the external page.

  • Sections can have 1 or more pages
  • The external pages cannot be in the middle of a section
  • Between section can be any number of external pages, or none

Solution

  • MigraDoc can add pages from PDF files using AddImage. You pass the desired page number (one-based) after the filename - "test.pdf#5" will take the fifth page from that PDF file.

    You can simply add a page break to a section, add the image, then add another page break. Images can be positioned at absolute positions, so they fill the whole page.

    Automatic page breaks are added when rendering a document to PDF, but you can always add manual page breaks as needed.

    If you use that approach then all pages will be created by MigraDoc and page numbers will work.