Using iTextSharp, how can I insert a new page at the beginning of the page, when the PdfWriter has been writing pages already? Suppose the case of an index page which should be the first page of the document, but you wouldn't know its contents until you write the whole document. Particularly, on which page is each section/chapter written.
You can't go back to the first page while you're creating a document, but there are different ways to solve your problem.
If you don't expect to have many pages, you could consider the solution that is explained in chapter 5 of iText in Action - Second Edition, more specifically in the MovieHistory1.java example.
In this example, we reorder the pages right before we close the document:
// step 1
Document document = new Document();
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(RESULT));
// IMPORTANT: set linear page mode!
writer.setLinearPageMode();
// step 3
document.open();
// step 4
// Add all your content
// Create a new order for the pages
int total = writer.reorderPages(null);
// change the order
int[] order = new int[total];
for (int i = 0; i < total; i++) {
order[i] = i + toc;
if (order[i] > total)
order[i] -= total;
}
// apply the new order
writer.reorderPages(order);
// step 5
document.close();
Why do I only recommend this for documents with a limited number of pages? For this functionality to work we need to create a linear page tree:
writer.setLinearPageMode();
A linear page tree is not really a tree (it's a tree without any branches) and that is not optimal in PDF.
It is better to reorder the pages in a second go. This is explained in two questions that are bundled in The Best iText Questions on StackOverflow (a free ebook).
The questions were:
I know that having redundant info on SO is not ideal, but this is the code you'd need:
PdfReader reader = new PdfReader(baos.toByteArray());
int n = reader.getNumberOfPages();
reader.selectPages(String.format("%d, 1-%d", n, n-1));
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
stamper.close();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments