2014-01-21 226 views
2

伙计们我被困在使用java打印PDF文件。 我写的代码如下:使用java在网络打印机中打印pdf

`

public static void main(String[] args) throws PrinterException, PrintException, IOException{ 
     DocFlavor docflavor = new DocFlavor.INPUT_STREAM ("application/octet-stream"); 
    // DocFlavor docflavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE; 
/*  DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.;*/ 
     PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); 
     DocFlavor[] docF = printService.getSupportedDocFlavors(); 
     for(int i = 0; i<docF.length;i++){ 
      System.out.println(docF[i]); 
     } 
     FileInputStream fis = new FileInputStream("pathofpdffile"); 



     Doc pdfDoc = new SimpleDoc(fis, docflavor, null); 


     DocPrintJob printJob = printService.createPrintJob(); 
     PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 

     aset.add(new Copies(1)); 
     aset.add(Sides.ONE_SIDED); 
     printJob.print(pdfDoc,aset); 

     fis.close(); 

}`

上面的代码intiate印刷活动,但问题是,我得到的只有在打印编码字符。我无法获得我的确切文件。

其次,如果我改变的DocFlavor到SERVICE_FORMATTED.PAGEABLE,如果我改变的DocFlavor到INPUT_STREAM.PDF抛出一个错误

java.lang.IllegalArgumentException: data is not of declared type 
at javax.print.SimpleDoc.<init>(Unknown Source) 
at com.calculator.main.PrintingTest.main(PrintingTest.java:42) 

第三,它抛出的错误

`Exception in thread "main" sun.print.PrintJobFlavorException: invalid flavor 
at sun.print.Win32PrintJob.print(Unknown Source) 
at com.calculator.main.PrintingTest.main(PrintingTest.java:49)` 

这一切我正在尝试使用网络打印机。 任何帮助将gr8 ..

+0

请参阅http://stackoverflow.com/questions/2478890/how-to-print-pdf-file-in-a-java-application – RaviH

+0

你使用哪种框架来分析和打印PDF? –

+0

@RaviH:我不喜欢为此使用任何外部jar。我也浏览了你发布的链接。任何更多的帮助! – saharsh

回答

9

只要改变你的代码,使用AUTO_SENSE,如下图所示。

InputStream inputStream = new FileInputStream("C://test.pdf"); 
Doc doc = new SimpleDoc(inputStream, DocFlavor.INPUT_STREAM.AUTOSENSE,null);