PDFBox:如何从 PDF 打印一系列页面

PDFBox: How to print a range of pages from a PDF

我真的不知道该如何处理。我是这个库 (PDFBox) 的新手,我设法实现了代码(使用 Java),它可以打印任何选定的 PDF。

现在,如果需要,我需要允许用户指定要打印的页面范围。 这是我的代码中处理打印的部分...

          try
          {
                    // TODO add your handling code here:
                    PrintService myPrintService = findPrintService(printerCmb.getSelectedItem().toString());
                    PrinterJob job = PrinterJob.getPrinterJob();
                   job.setPageable(doc);

                    job.setPrintService(myPrintService);
                    job.print( );
          }
          catch (PrinterException ex)
          {             
                    Logger.getLogger(PrintDialog.class.getName()).log(Level.SEVERE, null, ex);  

          }

接下来我该做什么?

这就是我创建 "doc" 的方式。

    public Pageable doc;  JFileChooser getPDF = new JFileChooser();
          FileFilter filter = new FileNameExtensionFilter("PDF File", "pdf");
          getPDF.setFileFilter(filter);
          getPDF.setDialogTitle("Select a PDF file");
          getPDF.showOpenDialog(getPDF);
          try
          {
                    Connection conn = null;
                    conn = DriverManager.getConnection(urlDist);
                    //SQLiteConnection new2 = new SQLiteConnection(urlDist, filename);
                    File selPdf = getPDF.getSelectedFile();
                    doc = PDDocument.load(selPdf);

                    if (doc != null)
                    {
                              count = doc.getNumberOfPages();
                              noPagestxt.setText(String.valueOf(count ));
                              filename = selPdf.getName();
                              fileNametxt.setText(filename);
                              pagesPrint.setEnabled(true);
                    }
                    // cleaning memory

                    // cleaning memory
          }
          catch (Exception ex)
          {
                    Logger.getLogger(BioProject.class.getName()).log(Level.SEVERE, null, ex);
          }
Below is the code which can be helpful for  printing data from specific pages in the whole PDF file  hope this would solve your issue.

    PDDocument doc = PDDocument.load("Your PDF path");
    PDFTextStripper stripper = new PDFTextStripper();
    stripper.setStartPage( 1 );
    stripper.setEndPage( Integer.MAX_VALUE );
    List<String>  ans= Arrays.asList(changeText.split(",\n"));
    System.out.println(ans);

所以,我根据用户 TilmanHausherr 的建议解决了这个问题。 我使用 PageRanges() 函数指定了范围 这是代码。

...
 job.setPageable(doc);
 job.setPrintService(myPrintService);
 PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet(); 
 PageRanges pageRng = new PageRanges( lower , upper);
 attr.add(pageRng); 
 job.print(attr);

注意: upperlower 是从用户那里得到的整数变量。