Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDFBox. Java: How to print only one page of PDF instead of full document?

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?

like image 573
Rokas Avatar asked Oct 30 '22 13:10

Rokas


1 Answers

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);                
    }
}
like image 189
fabian Avatar answered Nov 15 '22 04:11

fabian