Java - 如何将PDF打印到特定的打印机?

时间:2016-02-21 11:36:06

标签: java windows pdf printing pdfbox

我在Windows 8.1中有5台打印机,而PDF文件不在PHP服务器中生成的本地系统中。

问题。如何从服务器获取PDF文件并打印到特定的打印机?

我正在尝试Apache PDFBox 2.0.0

enter image description here

修改

import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

public class JPrint {

  public static boolean saveFile(URL url, String file) throws IOException {
    boolean download_status = false;

    System.out.println("[OK] - open");
    InputStream in = url.openStream();
    FileOutputStream fos = new FileOutputStream(new File(file));
    System.out.println("[OK] - reading file...");
    int length = -1;
    byte[] buffer = new byte[1024];

    while ((length = in.read(buffer)) > -1) {
        fos.write(buffer, 0, length);
    }
    fos.close();
    in.close();

    download_status = true;
    System.out.println("[OK] - downloaded");
    return download_status;
  }

  public static void main(String[] args) throws IOException, PrinterException {    
    String downloaded_filename = "C:/Users/tpt/Downloads/pdf.pdf";
    String download_pdf_from = "https://github.com/msysgit/msysgit/releases/download/Git-1.9.2-preview20140411/Git-1.9.2-preview20140411.exe";
    String downloaded_filename_open_as_pdf = "C:\\Users\\tpt\\Downloads\\pdf.pdf";
    String printerNameDesired = "DYMO LabelWriter 450"; // Brother HL-6180DW series

    // Get printers
    PrintService[] services = PrinterJob.lookupPrintServices();
    DocPrintJob docPrintJob = null;


    try{
      URL url = new URL(download_pdf_from);

      if(saveFile(url, downloaded_filename)) {
        try {
          PDDocument pdf = PDDocument.load(new File(downloaded_filename_open_as_pdf));
          PrinterJob job = PrinterJob.getPrinterJob();
          for (int i = 0; i < services.length; i++) {
           if (services[i].getName().equalsIgnoreCase(printerNameDesired)) {
             docPrintJob = services[i].createPrintJob();
           }
          }

          job.setPrintService(docPrintJob.getPrintService());
          job.setPageable(new PDFPageable(pdf));
          //docPrintJob = service[i].createPrintJob();
          job.print();

        } catch (Exception e) {
          System.out.println("[FAIL]" + e);
        }      
      } else {
        System.out.println("[FAIL] - download fail");
      }      
    } catch (Exception ae) {
      System.out.println("[FAIL]" + ae);
    }


  }
}

1 个答案:

答案 0 :(得分:4)

这将为您提供可用打印机列表:

PrintService[] services = PrinterJob.lookupPrintServices();

您可以遍历此数组并按名称选择打印机(services [i] .getName())