Web页面自动打印PDF文件的实现

借助iText和Adobe Acrobat的Javascript支持,可以实现PDF文档的自动打印(可以做到不显示打印对话框)

  1. ......
  2.  
  3. PdfReader reader = new PdfReader(pdfStream); [1]
  4.  
  5. StringBuffer script = new StringBuffer(); [2]
  6. script.append("this.print({bUI: false,bSilent: true,bShrinkToFit: false});")
  7.   .append("\r\nthis.closeDoc();");
  8.  
  9. ByteArrayOutputStream bos = new ByteArrayOutputStream(pdfStream.length);
  10. try {
  11.   PdfStamper stamp = new PdfStamper(reader, bos); [3]
  12.   stamp.setViewerPreferences(PdfWriter.HideMenubar 
  13.     | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
  14.   stamp.addJavaScript(script.toString());
  15.   stamp.close();
  16. } catch (DocumentException e) {
  17.   logger.error(e.getMessage(), e.getCause());
  18. }
  19.  
  20. return new StreamingResolution("application/pdf"
  21.   new BufferedInputStream(new ByteArrayInputStream(bos.toByteArray()))) ;
  22.  
  23. ......

代码说明:
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文档:

  1. <embed type="application/pdf" src="/PrintPdf.action" width="1" height="1"></embed>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.
For more help see http://daringfireball.net/projects/markdown/syntax

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>