How to add blank pages while concatenating several PDFs using PdfSmartCopy
I'm trying to concatenate a huge number of PDF files to create a print-ready file, so that I don't have to print them one by one. The print-ready file I want needs to be duplex, so for the documents I have which are only 1 page, I need to add a blank page for the "back" of the document, otherwise the following document is messed up.
Is there any way to add blank pages while concatenating files using PdfSmartCopy
? I know PdfWriter
can easily add blank pages, but it isn't made for merging a large number of files, which is why I'm not using it. I've read the answer to the question "How to add blank pages in exist PDF in java?" However, in this case I can't use PdfStamper
either because I require a small file size and it seems PdfSmartCopy
is the only viable option for that, unless I have missed something.
Posted on StackOverflow on Jan 30, 2014
In my answer to the question you refer to, I explained how to insert a blank page into an existing PDF using PdfDocument
:
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PageSize ps = new PageSize(pdfDoc.getFirstPage().getPageSize());
pdfDoc.addNewPage(pdfDoc.getNumberOfPages() + 1, ps);
pdfDoc.close();
There is no PdfCopy
and PdfSmartCopy
classes in iText 7 and merging documents is done using copyPagesTo(int pageFrom, int pageTo, PdfDocument toDocument)
. The smart mode is setting via setSmartMode(true)
method in PdfWriter
class. So you probably need an instance of source PdfDocument
and a few lines of code:
public void createPdf(String[] src, String dest) throws IOException {
// create the resulting PdfDocument instance
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest).setSmartMode(true));
pdfDoc.initializeOutlines();
PdfDocument srcDoc;
PageSize ps;
for (int i = 0; i < src.length; i++) {
// read the source PDF
srcDoc = new PdfDocument(new PdfReader(src[i]));
// copy content to the resulting PDF
srcDoc.copyPagesTo(1, srcDoc.getNumberOfPages(), pdfDoc);
// if the source PDF has only 1 page, add a blank page to the resulting PDF
if (srcDoc.getNumberOfPages() == 1) {
ps = new PageSize(srcDoc.getFirstPage().getPageSize());
pdfDoc.addNewPage(pdfDoc.getNumberOfPages() + 1, ps);
}
}
pdfDoc.close();
}
If you don't need to customize the page size, you can just use:
pdfDoc.addNewPage();
In this case, iText will get the default page size of the document.
Click this link if you want to see how to answer this question in iText 5.