To merge multiple PDFs generated at runtime using ITextSharp, you have two primary options: using the PdfCopy class family or the PdfWriter class.
PdfCopy Family
The Pdf*Copy* classes allow you to merge PDFs while preserving their original format and interactive annotations. For this approach, follow these steps:
Example Using PdfCopy:
byte[] mergedPdf = null; using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { document.Open(); for (int i = 0; i < pdfBytes.Count; ++i) { PdfReader reader = new PdfReader(pdfBytes[i]); int n = reader.NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } } } mergedPdf = ms.ToArray(); }
PdfWriter Class
The PdfWriter class allows you to integrate pages from source PDFs into a new document without preserving their original interactivity. Use this approach if you are not concerned about annotations or other features in the source PDFs.
using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { using (PdfWriter writer = PdfWriter.GetInstance(document, ms)) { document.Open(); for (int i = 0; i < pdfBytes.Count; ++i) { PdfReader reader = new PdfReader(pdfBytes[i]); int n = reader.NumberOfPages; for (int page = 0; page < n; ) { PdfImportedPage importedPage = writer.GetImportedPage(reader, ++page); writer.Add(importedPage); } reader.Close(); } } } mergedPdf = ms.ToArray(); }
For more details, refer to the iTextSharp documentation or the code examples provided in the linked answer.
The above is the detailed content of How to Merge Multiple Runtime-Generated PDFs Using ITextSharp?. For more information, please follow other related articles on the PHP Chinese website!