PDFbox. Java: how to print only one pdf page instead of a complete document?

I want to print a specific page of a pdf file. In the example, I have a pdf with 4 pages and I want to print the third page. I am using Apache PDFBox lib. I tried to delete pages other than the ones I want to print, but now it prints all the other pages except the ones I want to print ... any help?

There is my function code that 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 added this line to the code: System.out.println(doc.getPageMap());

The console gives me: {13,0=4, 1,0=2, 7,0=3, 27,0=1} what does this mean?

+5
source share
1 answer

Your code does not work, because you do not take into account that deleting pages also changes the indexes of pages with higher indicators and reduces the number of pages. Also page indexes are based on 0. Remove 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 little closer to your implementation:

 for(int j=doc.getNumberOfPages()-1; j >= 0; j--){ if(i!=j) { doc.removePage(j); } } 
+2
source

Source: https://habr.com/ru/post/1238343/


All Articles