借助iText和Adobe Acrobat的Javascript支持,可以实现PDF文档的自动打印(可以做到不显示打印对话框)
......
PdfReader reader = new PdfReader(pdfStream); [1]
StringBuffer script = new StringBuffer(); [2]
script.append("this.print({bUI: false,bSilent: true,bShrinkToFit: false});")
.append("\r\nthis.closeDoc();");
ByteArrayOutputStream bos = new ByteArrayOutputStream(pdfStream.length);
try {
PdfStamper stamp = new PdfStamper(reader, bos); [3]
stamp.setViewerPreferences(PdfWriter.HideMenubar
| PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
stamp.addJavaScript(script.toString());
stamp.close();
} catch (DocumentException e) {
logger.error(e.getMessage(), e.getCause());
}
return new StreamingResolution("application/pdf",
new BufferedInputStream(new ByteArrayInputStream(bos.toByteArray()))) ;
......
代码说明:
1、pdfStream是用iText生成的PDF文档字节流
2、script是要加入到PDF文档里的Javascript代码。这段Javascript代码先调用PDF文档对象的print方法,然后用closeDoc方法关闭文档。print方法的参数指定了不要显示打印对话框,参数含义参考Acrobat JavaScript Scripting Reference
3、bos用来保存加入Javascript后的PDF文档字节流,它作为PdfStamper对象的输出流。PdfStamper对象调用addJavaScript方法将Javascript代码加入到PDF文档中。
Web页面嵌入PDF文档: