Home >Backend Development >C++ >How to Efficiently Merge In-Memory PDFs on the Fly Using ITextSharp for Printing?
How to concatenate multiple PDFs generated in runtime without prior knowledge of file names using ItextSharp for subsequent printing?
To merge PDFs on the fly using ItextSharp, two primary approaches exist:
Using PdfCopy (for Preserving Original Formatting)
using System.Collections.Generic; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.PdfDocument; using iText.Kernel.Pdf.PdfWriter; 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 < pdf.Count; ++i) { PdfDocument reader = new PdfDocument(new PdfReader(pdf[i])); for (int page = 0; page < reader.GetNumberOfPages(); ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } } } mergedPdf = ms.ToArray(); }
Using PdfWriter (for Efficient Page Integration)
using System.Collections.Generic; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.PdfDocument; using iText.Kernel.Pdf.PdfWriter; byte[] mergedPdf = null; using (MemoryStream ms = new MemoryStream()) { using (PdfWriter writer = new PdfWriter(ms)) { PdfDocument document = new PdfDocument(writer); PdfDocumentBuilder pdfBuilder = new PdfDocumentBuilder(document); for (int i = 0; i < pdf.Count; ++i) { PdfDocument reader = new PdfDocument(new PdfReader(pdf[i])); for (int page = 0; page < reader.GetNumberOfPages(); ) { PdfCanvas canvas = new PdfCanvas(pdfBuilder.GetPageAt(++page)); PdfFormXObject importedPage = new PdfFormXObject(reader.GetPage(page)); canvas.AddImportedPage(importedPage); } } } mergedPdf = ms.ToArray(); }
The above is the detailed content of How to Efficiently Merge In-Memory PDFs on the Fly Using ITextSharp for Printing?. For more information, please follow other related articles on the PHP Chinese website!