Introduction
When automating document generation, it is often necessary to merge multiple dynamically generated PDF files into a single output for printing. This article explores how to achieve this using ItextSharp.
Merge Strategies
ItextSharp offers two primary approaches to merging PDF documents:
Solution Using PdfCopy
The following code sample demonstrates merging PDF files using PdfCopy:
using iTextSharp.text; using iTextSharp.text.pdf; using System.Collections.Generic; using System.IO; namespace MergePdfs { class Program { static void Main(string[] args) { // Create a list of byte arrays for each PDF file List<byte[]> pdfs = new List<byte[]>(); // Read each PDF file into the list foreach (string filePath in args) { pdfs.Add(File.ReadAllBytes(filePath)); } // Merge the PDFs byte[] mergedPdf = null; using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { document.Open(); foreach (byte[] pdf in pdfs) { PdfReader reader = new PdfReader(pdf); int n = reader.NumberOfPages; for (int page = 1; page <= n; page++) { copy.AddPage(copy.GetImportedPage(reader, page)); } } } } mergedPdf = ms.ToArray(); } // Print the merged PDF // ... (code for printing the merged PDF) } } }
In this example, pdfs contains the byte arrays of the PDF files, and the PdfCopy class is used to add pages from each source document.
Other Considerations
PdfCopy can cause performance issues and memory consumption with large documents. PdfSmartCopy and PdfWriter offer alternatives with trade-offs in performance and feature support.
For more comprehensive information and code examples, refer to the iText in Action documentation (chapter 6, section 6.4):
The above is the detailed content of How Can I Merge Multiple Programmatically Generated PDF Files in C# Using ITextSharp?. For more information, please follow other related articles on the PHP Chinese website!