Stefano.net
Stefano.net

Reputation: 1128

iTextSharp pdf merge spool issue

I have a program that takes several pdfs (even 1000+) and merge them in a single pdf.

The program works perfectly, but I faced a spool error.

If I open the merged pdf with Acrobat and print it, instead of sending a single spool of n pages to printer it sends as many spools as the number of original pdfs, causing the printer to be very slow processing it.

This is an abstract of the class

Document document = new Document ( iTextSharp.text.PageSize.A4 );
PdfWriter writer = PdfWriter.GetInstance ( document, new FileStream ( outputFilename, FileMode.Create ) );
writer.SetFullCompression();            
document.Open();
PdfContentByte cb = writer.DirectContent;

foreach( var file in files ) {
PdfReader reader = new PdfReader ( file );
int n = reader.NumberOfPages;
int i = 0;
while ( i < n) 
{
    i++;
    document.SetPageSize ( reader.GetPageSizeWithRotation ( i ) );                
    document.NewPage();
    page = writer.GetImportedPage ( reader, i );
    rotation = reader.GetPageRotation ( i );        
    cb.AddTemplate ( page, 1f, 0, 0, 1f, 0, 0 );
}
}

document.Close();

Upvotes: 0

Views: 1215

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77546

Please download Chapter 6 of iText in Action - Second Edition. You'll find out that you're using the wrong classes to concatenate PDFs. I've repeated this over and over again, I would really like to know what made you use PdfWriter instead of Pdf(Smart)Copy to concatenate PDFs. Did you find that code sample somewhere on a site? If so, please let me know so that we can spank the author of that page together!

If you use your code sample, you're importing pages as XObjects. This adds a level of nesting that could cause troubles as there's a limit to the level of nesting. Also, when you're adding page after page to PdfWriter, there's a risk that your PDF contains too much redundant information: your file may be bloated. This can be avoided by using PdfSmartCopy.

Finally (something that isn't in the book): you should use the FreeReader() method after you've copied all the pages from a PdfReader object. This will significantly speed up your code, and reduce the memory that is needed.

I realize that none of the above explain why different spools are sent to the printer, but let's start with the obvious flaws in your code first, and then take it from there.

Upvotes: 1

Related Questions