Click or drag to resize

Merge and Split Documents

The document model merges PDF documents and extracts pages from a PDF document with the static methods of the MergePdf and SplitPdf classes:

  • Merge merges PDF files into a PDF file, and the overload with streams merges PDF streams into a PDF stream.

  • ExtractPages extracts a range of pages - a start page index and a number of pages - from a PDF file or a Document, into a new file or into a new Document that can be changed further.

A document can also take the pages of other documents: AppendDocument(Document) appends all the pages of a document, and Add(PdfPage) appends one page. An appended document must stay open until the document it was appended to is saved (AutoCloseAppendedDocs closes it with that document). The appended pages keep their own layout, so the document's header, footer, left and right templates are not drawn on them; the other templates (a watermark, for example) are drawn on every page. A PDF/A document takes pages only from documents that conform to its PDF/A level; convert the others first with ConvertToPdfA(PdfStandardSubset).

For merging with more options (page ranges, images, empty pages, bookmarks for the merged documents, security) see Merge PDF, and for splitting a document into several files see Split PDF.

Code Sample

The code sample below, an ASP.NET Core controller action, merges two PDF files into a file on disk, extracts the first page of the merged document into another file, and merges the two files again into a stream returned to the browser:

public IActionResult MergeAndSplit()
{
    string workingFolderPath = Path.Combine(AppContext.BaseDirectory, "Files");

    string firstFilePath = Path.Combine(workingFolderPath, "first.pdf");
    string secondFilePath = Path.Combine(workingFolderPath, "second.pdf");
    string mergedFilePath = Path.Combine(workingFolderPath, "MergeFileResult.pdf");
    string extractedFilePath = Path.Combine(workingFolderPath,
        "SplitFileResult.pdf");

    // merge the two files into mergedFilePath on disk
    string[] filesToMerge = new string[] { firstFilePath, secondFilePath };
    MergePdf.Merge(filesToMerge, mergedFilePath);

    // extract the first page from the merged document into a PDF file
    SplitPdf.ExtractPages(mergedFilePath, 0, 1, extractedFilePath);

    // merge streams into a memory stream
    using (FileStream fs1 = new FileStream(firstFilePath, FileMode.Open,
        FileAccess.Read))
    using (FileStream fs2 = new FileStream(secondFilePath, FileMode.Open,
        FileAccess.Read))
    {
        MemoryStream merged = new MemoryStream();
        MergePdf.Merge(new Stream[] { fs1, fs2 }, merged);

        // send the merge result to the browser
        return File(merged.ToArray(), "application/pdf", "MergeStreamsResult.pdf");
    }
}
See Also