2016-02-21 172 views
2

我在Windows 8.1中有5個打印機,而PDF文件不在本地系統中生成的PHP服務器中。Java - 如何將PDF打印到特定的打印機?

問題。我如何從服務器獲取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); 
    } 


    } 
} 

回答

3

這給你回可用打印機的列表:

PrintService[] services = PrinterJob.lookupPrintServices(); 

你可以循環這個ar並按名稱選擇打印機(服務[i] .getName())