2017-05-26 72 views
1

我真诚地不知道如何处理此问题。我是这个图书馆的新手(PDFBox),我设法实现了代码(使用Java),可以打印任何选定的PDF。PDFBox:如何从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); 
      } 
+0

“doc”从哪里来? –

+0

'public Pageable doc;'''doc = PDDocument.load(selPdf);'不起作用。无论如何,在此期间,我发现了一些可能有用的东西,“PageRanges”类。这是一个打印作业属性,所以使用'PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet(); attr.add(new PageRanges(1,1)); job.print(attr);' –

+0

@TilmanHausherr,我会尝试一下。 –

回答

1

于是,我上的使用用户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是从用户得到整型变量。

-1
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); 
+0

如果您对答案满意,则标记为已回答 – VRJ

+0

您的代码不会将任何内容打印到打印机。它只是提取文本并输出它。 –

+0

是的,它读取数据并打印 – VRJ