Reputation: 623
this is one of my first time that I use iText and I have a dount about the correctness of my solution.
Into an application I create a PDF composed by many pages (some hundreds) and I save it on a file, doing something like this:
String result = outputPath + "\\" + pdfName + ".pdf";
com.itextpdf.text.Document document = new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4, 0, 0, 0, 0);
PdfCopy copy = new PdfCopy(document, new FileOutputStream(result));
.......................................................
.......................................................
.......................................................
So, essentially, at the end I will have my .pdf file into a directory. It works fine.
Now I have to count the page number into this file.
Searching some documentation I found this link (that I think is the official documentation): http://www.manning.com/lowagie2/samplechapter6.pdf
Specifically it say:
You can query a PdfReader instance to get the number of pages in the document
So in my code I done something like this:
try {
PdfReader pdfReader = new PdfReader(result);
System.out.println("NUMERO PAGINE PDF CONCATENAZIONE FATTURE: " + pdfReader.getNumberOfPages());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
It works fine but I am asking if, in my case (I have the PdfCopy copy on which I add the PdfImportedPage page object) I have some smarter soluton different to create a new PdfReader object that read the final pdf file. Or is it the best solution?
Tnx
Upvotes: 0
Views: 516
Reputation: 77528
When you have finished creating a PDF, you can create a PdfReader
instance and ask that reader
object for the total number of pages. That is true.
However:
it seems that you are not creating a PDF from scratch. Instead you are using PdfCopy
to concatenate many different documents. Allow me to complete your code:
PdfReader reader1 = new PdfReader(path1);
PdfReader reader2 = new PdfReader(path2);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
document.open();
copy.addDocument(reader1);
copy.addDocument(reader2);
document.close();
reader1.close();
reader2.close();
In your code snippet, you omitted the fact that you are already creating PdfReader
objects, hence you do not need to create a new PdfReader
instance to calculate the total number of pages in the final result. Instead you can just add up the number of pages from the reader
objects you added to PdfCopy
:
int total = reader1.getNumberOfPages() + reader2.getNumberOfPages();
Just make sure you calculate the total number of pages before you close the PdfReader
instances.
Upvotes: 1