I want to print specific page of pdf file. In example I have pdf with 4 pages, and I want to print third page. I am using Apache PDFBox lib. I tryied to remove my other pages except that one which I want to print, but it now prints all other pages except that which I want to be printed... any help?
There is my code of function I wrote:
void printPDFS(String fileName, int i) throws PrinterException, IOException{
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.getPrintService();
// String test = "\\\\192.168.5.232\\failai\\BENDRAS\\DHL\\test2.pdf";
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printJob.getPrintService());
PDDocument doc = PDDocument.load(fileName);
for(int j=1;j<=doc.getNumberOfPages();j++){
if(i!=j)
{
doc.removePage(j);
}
}
doc.silentPrint(job);
}
I've added this line to code: System.out.println(doc.getPageMap());
Console gives me: {13,0=4, 1,0=2, 7,0=3, 27,0=1}
what does it mean?
Your code doesn't work since you don't take into account that removing pages also changes the indices of the pages at higher indices and decreases the number of pages. Also page indices are 0-based. Remove the pages like this and it should work:
i = Math.max(-1, Math.min(i, doc.getNumberOfPages()));
// remove all pages with indices higher than i
for (int j = doc.getNumberOfPages()-1; j > i; j--) {
doc.removePage(j);
}
// remove all pages with indices lower than i
for (int j = i-1; j >= 0; j--) {
doc.removePage(j);
}
or alternatively a bit closer to your implementation:
for(int j=doc.getNumberOfPages()-1; j >= 0; j--){
if(i!=j)
{
doc.removePage(j);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With