merge pdf pages using migradoc in csharp

To merge multiple PDF pages into one document using MigraDoc in C#, you can follow these steps:

  1. Instantiate a new PdfDocument object.
main.cs
PdfDocument document = new PdfDocument();
42 chars
2 lines
  1. Create a new Section in the document.
main.cs
Section section = document.AddSection();
41 chars
2 lines
  1. Add the PDF pages to the document using the AddImage() method, which takes a PdfDocument object representing the page to be added.
main.cs
foreach (string filePath in pdfFiles) // pdfFiles is a list containing file paths of pdf pages
{
    PdfDocument mergeDocument = PdfReader.Open(filePath, PdfDocumentOpenMode.Import);

    foreach (PdfPage page in mergeDocument.Pages)
    {
        PdfPage newPage = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(newPage);

        XImage image = XImage.FromStream(() => ConvertPdfPageToStream(page));
        gfx.DrawImage(image, 0, 0);

        gfx.Dispose();
    }
}
489 chars
16 lines
  1. Save the merged document.
main.cs
document.Save(outputFilePath);
31 chars
2 lines
  1. Dispose of the PdfDocument object.
main.cs
document.Dispose();
20 chars
2 lines

Here, I've assumed that you have defined a ConvertPdfPageToStream() method which converts a PdfPage to a MemoryStream object.

main.cs
public static MemoryStream ConvertPdfPageToStream(PdfPage page)
{
    MemoryStream stream = new MemoryStream();
    PdfDocument document = new PdfDocument();
    document.Version = page.Document.Version;
    document.Info = page.Document.Info.Clone(document);
    document.Options.CompressContentStreams = false;
    document.AddPage(page);
    document.Save(stream, false);
    document.Close();
    stream.Position = 0;
    return stream;
}
443 chars
14 lines

This method adds the PdfPage to a new PdfDocument object and then saves it to a MemoryStream, which is returned.

related categories

gistlibby LogSnag