我使用java打印多个html文档时遇到问题。我需要的应用程序显示ONE所有可打印文件的打印对话框(文件数可能很大)。首先,我试图做到这一点使用非标准的Java方法:在java中批量打印
if (Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.PRINT))
{
try {
File html1 = new File("c://file1.html");
File html2 = new File("c://file2.html");
desktop.print(html1);
desktop.print(html2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
但我看到每个打印的文件一个一个对话框,它不适合我。然后我试图使用Java打印API,但事实证明,我的打印机不支持DocFlavor的HTML文件,我的支持列表DocFlavor的是这样的:
image/gif; class="[B"
image/gif; class="java.io.InputStream"
image/gif; class="java.net.URL"
image/jpeg; class="[B"
image/jpeg; class="java.io.InputStream"
image/jpeg; class="java.net.URL"
image/png; class="[B"
image/png; class="java.io.InputStream"
image/png; class="java.net.URL"
application/x-java-jvm-local-objectref; class="java.awt.print.Pageable"
application/x-java-jvm-local-objectref; class="java.awt.print.Printable"
application/octet-stream; class="[B"
application/octet-stream; class="java.net.URL"
application/octet-stream; class="java.io.InputStream"
然后我试图打印HTML文件作为图像(PNG,这是我在画图:)画了),我的代码:
PrintRequestAttributeSet pras =
new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(new Copies(1));
aset.add(Sides.ONE_SIDED);
aset.add(Finishings.STAPLE);
PrintService printService[] =
PrintServiceLookup.lookupPrintServices(flavor, pras);
PrintService defaultService =
PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200,
printService, defaultService, flavor, pras);
if (service != null) {
try {
FileInputStream fis = new FileInputStream("c://test//test.png");
DocAttributeSet das = new HashDocAttributeSet();
Doc doc1 = new SimpleDoc(fis, flavor, das);
FileInputStream fis2 = new FileInputStream("c://test//test2.png");
DocAttributeSet das2 = new HashDocAttributeSet();
Doc doc2 = new SimpleDoc(fis2, flavor, das2);
DocPrintJob job1 = service.createPrintJob();
DocPrintJob job2 = service.createPrintJob();
try {
job1.print(doc1, pras);
job2.print(doc2, pras);
} catch (PrintException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
它完美,而是convertation从HTML图像并不简单的问题。我尝试使用swing组件,实现Printable接口并使用Cobra库,但它要求在窗体上显示文档,这对我来说并不是必需的,因为我需要在“无声”模式下打印,而无需打开文档。
任何想法?
在这个例子中,ASET是未使用的。它看起来像pdfbox 2.0.0将支持将PrintRequestAttributeSet传递给'silentPrint()'方法。 – Aaron 2014-06-19 23:24:44