I try to merge 2 big PDF files without loading them fully in memory.
I tried with a PdfMerger and manually without a PdfMerger thanks to this kind of code :
using(var writer = new PdfWriter(new FileStream(@"C:\Test\OutBig.pdf",FileMode.OpenOrCreate)))
using (var outputDocument = new PdfDocument(writer)) {
using (var inputDoc = new PdfDocument(new PdfReader((@"C:\Test\InBig.pdf")))) {
for (int i = 1; i <= inputDoc.GetNumberOfPages(); i++) {
var newp = outputDocument.AddNewPage();
var canvas = new PdfCanvas(newp);
var origPage = inputDoc.GetPage(i);
var copy = origPage.CopyAsFormXObject(outputDocument);
canvas.AddXObject(copy, 0, 0);
copy.Flush();
origPage = null;
canvas.Release();
newp.Flush();
writer.Flush();
canvas = null;
newp = null;
}
}
The code is working but every page is loaded in memory and stay loaded, and I consequently have more than 1GB loaded in memory.
Do you know any way to merge 2 pdfs files without loading them in memory with itext7 ?
Regards,
Patrice



There are several ways of lowering memory consumption during copying of big documents with
iText7. One of them is to leverage the fact that the objects are read on demand. So you actually can copy pages from source document to the destination document in multiple batches by opening and closing source document multiple times.Here is the code in Java which should convert to C# almost solely by replacing method names to upper case.