I my current project I have to print a pdf without using an applet (all because the spanish electronic identity card ask for its password any time it open a connection). We have to do it silently, or a least with the less posible user intervention.
The idea is to insert an iframe which calls for the pdf, inside it we set javascript into the pdf for printing. I didn’t know that I could insert js into a pdf, but it is possible and easy with itext/itextsharp library.
Here is the page_load event in the page that returns the pdf. This is where all the magic is done:
1: protected void Page_Load(object sender, EventArgs e)
2: { 3: MemoryStream ms = new MemoryStream();
4: 5: var urlPdf = new Uri(getBaseUrl() + "prueba.pdf");
6: 7: PdfReader ps = new PdfReader(urlPdf);
8: 9: /*inserts js into pdf*/
10: PdfStamper pdf = new PdfStamper(ps, ms);
11: pdf.JavaScript="this.print(false);";
12: pdf.Close(); 13: 14: HttpContext.Current.Response.ClearContent(); 15: HttpContext.Current.Response.ClearHeaders(); 16: HttpContext.Current.Response.ContentType = "application/pdf";
17: HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=recibo.pdf");
18: HttpContext.Current.Response.BinaryWrite(ms.ToArray()); 19: HttpContext.Current.Response.End(); 20: }And later we have just a page in which the iframe is inserted using jQuery:
1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SilentPDFPrinting._Default" %>
2: 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4: 5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head runat="server">
7: <title></title>
8: <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>1:2: <script src="js/default.js" type="text/javascript"></script>
9: </head>
10: <body>
11: <form id="form1" runat="server">
12: <div>
13: <input id="Button1" type="button" value="button" onclick="printPDFSilently();" /></div>
14: <div id="diviframe"></div>
15: </form>
16: </body>
17: </html>
Here the jQuery:
1: function printPDFSilently() {
2: /*inserts an iframe which downloads the pdf*/
3: var jIframe = jQuery("<iframe id='iframehidden' src='/PdfPrinter.aspx' width='0' height='0' ></iframe>");
4: jIframe.insertAfter("#diviframe");
5: }As you can see it is very easy. Here you have the code
Hope this helps to anyone.
