2014-01-20 103 views
0

我已经安装了doPDF打印机驱动程序,并且我想从Java将它用于将HTML转换为PDF。Java将HTML打印为PDF

PrintService service = getPrinterByName("doPDF");     
DocPrintJob printJob = service.createPrintJob(); 
Doc document = new SimpleDoc(conn.getInputStream(), DocFlavor.INPUT_STREAM.AUTOSENSE, null); 
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet(); 
File f = new File(new File(System.getProperty("user.home")),"out.pdf"); 

attr.add(new Destination(f.toURI())); 
printJob.print(document, attr); 

的问题是,当我打开out.pdf与任何PDF阅读器,它说格式错误,并用记事本++它只显示HTML。

private PrintService getPrinterByName(String name) { 
    PrintService[] list = getPrintersList(); 
    if (list.length > 0) { 
     for (PrintService service : list) { 
      if (service.getName().contains(name)) { 
       return service; 
      } 
     } 
    } 
    return null; 
} 

private PrintService[] getPrintersList() { 
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 
    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null); 

    return services; 
} 
+0

请发布'getPrinterByName()'的源码' – Aerospace

回答

0

我需要这个操作沉默,唯一的方法就是使用OpenOffice API。任何其他方法都需要用户输入/确认。

我用JOD Converter来达到这个目的。还有一点,我将任何文件转换为PDF(即:任何Microsoft Office文档,任何图像,任何Open Office文档,文本,HTML),然后将所有内容合并到一个PDF中,包含页眉和页脚,包括页数,日期,用户等。这适用于Windows或Linux。

万一你不需要沉默:

public void print() { 
     Desktop desktop = Desktop.getDesktop(); 
     try { 
      desktop.print(new File("web.html")); 
     } catch (IOException e) {   
      e.printStackTrace(); 
     } 
    } 

提示用户选择打印机,去的PDFCreator或doPDF。

希望它有帮助!