Merging PDF Documents |
The PDF merge part of ExpertPdf Anywhere combines PDF documents and images into one PDF document. It is in the ExpertPdf.Anywhere.MergePdf namespace of the ExpertPdf.Anywhere library and runs on every platform the library supports: Windows, Linux and macOS.
The main class is PDFMerge: you append documents, images and empty pages to it in the order they must appear, then save the merged document. Merging is done in managed code and needs neither the Chromium engine nor the native PDF tool.
Merge PDF documents from files, streams and byte arrays: the whole document, the pages from a start page to the end, or a range of pages.
Merge password protected documents, opened with their user or owner password.
Add images - PNG, JPEG, GIF, BMP, WebP or TIFF, from a file or as the bytes of an image file - and empty pages, each on a new page.
Insert a document, a range of pages, an image or an empty page at any position, and change the order of the merged pages.
Add a bookmark for each merged document (titled from its file name or document title), with the bookmarks of the document nested under it; or leave the bookmarks out.
Save the merged pages as a booklet: two pages on each landscape sheet, in saddle stitch order, for single or double-sided printing.
Choose the page size and orientation of the pages the library creates, and the compression level of the merged document.
Set the document information: title, subject, author, keywords, creation date.
Protect the merged document: user and owner passwords, print, copy, edit, form fill and assemble permissions, RC4 (40 or 128 bit), AES (128 or 256 bit) or AES-256 GCM encryption.
Save the merged document as PDF/A-1b, PDF/A-2b, PDF/A-2u, PDF/A-3b, PDF/A-3u, PDF/A-4, PDF/A-4e, PDF/A-4f or PDF/X-1a.
Save to a file, a stream or a byte array.
The merge classes are part of the ExpertPdf.Anywhere package; there is no separate package to install. See Installation for the packages and Requirements for the supported platforms. An application that only merges documents does not need a native engine package.
dotnet add package ExpertPdf.Anywhere
Create a PDFMerge, append the documents and images, and save the result with SaveMergedPDFToFile(String). PDFMerge is disposable: a using statement releases the documents it holds.
using ExpertPdf.Anywhere.MergePdf; using (PDFMerge pdfMerge = new PDFMerge()) { pdfMerge.AppendPDFFile("report.pdf"); pdfMerge.AppendImageFile("chart.png"); // on a new page pdfMerge.AppendEmptyPage(); pdfMerge.AppendPDFFile("invoice.pdf"); pdfMerge.SaveMergedPDFToFile("merged.pdf"); }
The options of the merged document are given to the constructor in a PdfDocumentOptions object. The page size and orientation (A4 and portrait by default) are used for the pages the library creates - images and empty pages; the pages of the appended PDF documents keep their own size.
Each Append method has versions that take only some pages of the source document: from a zero based start index to the end, or a number of pages from the start index (a negative number of pages also means "to the end"). Documents can come from a file (AppendPDFFile(String, Int32, Int32)), a stream (AppendPDFStream(Stream, Int32, Int32)) or a byte array (AppendPDFBytes(Byte, Int32, Int32)), for example a document just created in memory by the HTML to PDF converter. A stream is read when it is appended, so it can be closed right after the call. An image can also be given as the bytes of an image file, with AppendImageObject(Byte).
PDFMerge pdfMerge = new PDFMerge(); // the first two pages of the report pdfMerge.AppendPDFFile("report.pdf", 0, 2); // a whole document from memory pdfMerge.AppendPDFBytes(File.ReadAllBytes("invoice.pdf")); // the report from its fifth page to the end pdfMerge.AppendPDFFile("report.pdf", 4); // an image given as the bytes of a PNG file pdfMerge.AppendImageObject(File.ReadAllBytes("chart.png")); Console.WriteLine("Pages: " + pdfMerge.GetCurrentPageCount()); // the merged document in memory, for example to send it in a web response byte[] mergedBytes = pdfMerge.RenderMergedPDFDocument();
GetPageCount(String) is a fast way to get the page count of a document before you merge it.
DocumentInfo sets the title, subject, author and keywords of the merged document, and SecurityOptions protects it. The user password opens the document with the permissions you set; the owner password opens it with all the rights. When only a user password is set, it is also the owner password. The encryption is AES with a 128 bit key by default; a 256 bit key gives AES-256 (ISO 32000-2), a 40 bit key RC4, and AESGCM AES-256 in Galois/Counter mode, which writes the document as PDF 2.0.
PDFMerge pdfMerge = new PDFMerge(); pdfMerge.DocumentInfo.Title = "Report with invoice"; pdfMerge.DocumentInfo.AuthorName = "Sample Company"; pdfMerge.DocumentInfo.Keywords = "report, invoice"; pdfMerge.SecurityOptions.UserPassword = "user"; pdfMerge.SecurityOptions.OwnerPassword = "owner"; pdfMerge.SecurityOptions.KeySize = EncryptionKeySize.EncryptKey256Bit; pdfMerge.SecurityOptions.CanCopyContent = false; pdfMerge.SecurityOptions.CanEditContent = false; // a protected source document is opened with its user or owner password (-1 = all // the pages) pdfMerge.AppendPDFFile("protected.pdf", "password", 0, -1); pdfMerge.AppendPDFFile("invoice.pdf"); using (FileStream output = File.Create("secured.pdf")) { pdfMerge.SaveMergedPDFToStream(output); }
The Insert methods add a document, a range of pages, an image or an empty page at a zero based position in the merged document: 0 inserts before the first page, GetCurrentPageCount at the end. They take the same arguments as the Append methods, after the position: InsertPDFFile(Int32, String), InsertPDFStream(Int32, Stream, String, Int32, Int32), InsertPDFBytes(Int32, Byte, Int32, Int32), InsertImageFile(Int32, String) and InsertEmptyPage(Int32). ReorderPages(Int32) changes the order of the pages merged so far: the new order lists, for each position, the current index of the page that goes there, and contains every page once. The bookmarks keep opening the same pages and are listed in the order of the pages.
PDFMerge pdfMerge = new PDFMerge(); pdfMerge.AppendPDFFile("report.pdf"); // 6 pages pdfMerge.InsertPDFFile(1, "invoice.pdf"); // after the first page pdfMerge.InsertEmptyPage(0); // in front // reverse the order of the 8 pages pdfMerge.ReorderPages(new int[] { 7, 6, 5, 4, 3, 2, 1, 0 }); pdfMerge.SaveMergedPDFToFile("merged.pdf");
By default the merged document keeps the bookmarks of the merged documents. With AddDocumentBookmarks set to true, each merged document - and each image appended from a file - gets a bookmark that opens its first page, and its own bookmarks are nested under it. TitleSource takes the title from the file name or from the document title (a document from a stream or memory without a title is "Document N"), and SetBookmarkTitle(String) sets the title of the document added last. KeepSourceBookmarks set to false leaves the bookmarks of the merged documents out.
PDFMerge pdfMerge = new PDFMerge(); pdfMerge.BookmarkOptions.AddDocumentBookmarks = true; pdfMerge.BookmarkOptions.TitleSource = BookmarkTitleSource.DocumentTitle; pdfMerge.AppendPDFFile("report.pdf"); pdfMerge.AppendPDFFile("invoice.pdf"); pdfMerge.SetBookmarkTitle("Invoice"); pdfMerge.SaveMergedPDFToFile("merged.pdf");
With Enabled set to true the merged pages are saved two by two on landscape sheets of PageSize (A4 sheets, so A5 pages, by default), in the order that gives a booklet when the printed sheets are folded in the middle. Each page is scaled to fit its half of the sheet. The page count is completed to a multiple of 4 with empty halves at the end. With TwoSided the sheets are ordered for double-sided printing (for 8 pages: 8|1, 2|7, 6|3, 4|5; flip on the short edge); otherwise each sheet holds a page and its counterpart from the end, in reading order (1|8, 2|7, 3|6, 4|5). A booklet has no bookmarks; the document information, security and PDF standard apply to it as usual.
Set PdfStandardSubset to save the merged document as PDF/A-1b, PDF/A-2b, PDF/A-2u, PDF/A-3b, PDF/A-3u, PDF/A-4, PDF/A-4e or PDF/A-4f for long term archiving, or as PDF/X-1a for graphics exchange. The pages are imported as they are, so a PDF/A merge only takes source documents that conform to the level. Convert a document that does not with ConvertToPdfA(PdfStandardSubset) first, as below. The PDF/A standards do not allow encryption: do not set passwords for a PDF/A document.
using ExpertPdf.Anywhere.MergePdf; using ExpertPdf.Anywhere.PdfDocument; PdfDocumentOptions options = new PdfDocumentOptions(); options.PdfStandardSubset = ExpertPdf.Anywhere.MergePdf.PdfStandardSubset.Pdf_A_2b; PDFMerge pdfMerge = new PDFMerge(options); pdfMerge.DocumentInfo.Title = "Archived report"; foreach (string source in new string[] { "report.pdf", "invoice.pdf" }) { // each source converted to PDF/A-2b before it is merged using (Document document = new Document(source)) { document.ConvertToPdfA( ExpertPdf.Anywhere.HtmlToPdf.PdfStandardSubset.Pdf_A_2b); pdfMerge.AppendPDFBytes(document.Save()); } } pdfMerge.SaveMergedPDFToFile("archive.pdf");
The samples download has these console applications, in C# and VB.NET, for Windows, Linux and macOS:
MergePdfCommandLine - a command line tool that merges PDF files, images and empty pages, with options for the page size, orientation, compression, PDF standard, title, passwords, a bookmark per document and booklets.
MergePdfFeatures - page ranges, documents from memory and streams, images, document information and security, password protected sources, PDF/A-2b, inserting and reordering pages, a bookmark per document, a booklet.
They work on the documents and the image that come with them and need no arguments.
The MergePdfCommandLine sample is also a ready to use tool. The syntax is:
MergePdfCommandLine {/pdf:file | /image:file | /emptypage}+ [/out:file]
[/pagesize:A4|Letter|...] [/orientation:Portrait|Landscape]
[/compression:NoCompression|BestSpeed|BelowNormal|Normal|AboveNormal|Best]
[/standard:Full|Pdf_A_1b|Pdf_A_2b|Pdf_A_3b|Pdf_A_3u|Pdf_X_1a]
[/title:text] [/userpswd:password] [/ownerpswd:password]
[/bookmarks] [/booklet | /booklet:twosided]The documents, images and empty pages are merged in the order you give them. /bookmarks adds a bookmark for each document, named after the file; /booklet saves a booklet on landscape sheets of the page size. Quote the paths that contain spaces. Example:
MergePdfCommandLine /pdf:"My Documents/Report.pdf" /emptypage /image:chart.png
/standard:Pdf_A_2b /out:Merged.pdfSet LicenseKey once when the application starts, or the LicenseKey property before you save the merged document. Without a license key the library adds an evaluation notice to the pages of the merged document. See Licensing.