Monday, February 27, 2006

Silently Print a PDF When It Loads (Automatically Print)

Spent a long time searching for this feature... it's called Silent Print. PDFs can have javascript embedded to print. Here's how to do it in a JSP:

Note tha the secret sauce is to get a writer and then add javascript to it like so: writer.addJavaScript("this.print(false);", false);


<%@page import="java.io.ByteArrayOutputStream,
java.io.IOException,
java.io.*,
javax.servlet.ServletException,
javax.servlet.ServletOutputStream,
javax.servlet.http.HttpServlet,
javax.servlet.http.HttpServletRequest,
javax.servlet.http.HttpServletResponse,
com.lowagie.text.Chunk,
com.lowagie.text.Document,
com.lowagie.text.DocumentException,
com.lowagie.text.pdf.PdfWriter"%><%

Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();

try {
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
writer.addJavaScript("this.print(false);", false);
document.add(new Chunk("Silent Auto Print"));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
}

response.setContentType("application/pdf");
response.setContentLength(baos.size());
File f = new File(application.getRealPath("/js.pdf"));
OutputStream pout = new BufferedOutputStream(new FileOutputStream(f));

baos.writeTo(pout);
%>

No comments:

Labels

Blog Archive

Contributors