title: iTextSharp PDF printing
body: <p>I'm trying to create a method that will send a PDF file directly to my printer (causing the print dialog to appear).</p>
  
  <p>Below is the code I've been working on - most of it found in the forums <a href="https://stackoverflow.com/questions/270674/print-pdf-from-asp-net-without-preview">here</a>. It works fine if I use iTextSharp to create a new PDF document, but as soon as I try to inject some JavaScript into an existing file, I get an exception when calling the <code>print()</code> method saying </p>
  
  <blockquote>
    <p>Object doesn't support property or method 'print'</p>
  </blockquote>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      function load() {
          try {
              var x = document.getElementById("frame1");
              x.print();
          }
          catch (err) {
          }
      }
  &lt;/script&gt;
  
  &lt;body onload="load();"&gt;
      &lt;form id="form1" runat="server"&gt;
      &lt;div&gt;
         &lt;iframe id="frame1" src="C:/1686850_1.pdf"  runat="server" frameborder="0" style="height: 0px; width: 0px;" /&gt;
      &lt;/div&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>.CS file</p>
  
  <pre><code>using System.IO;
  using iTextSharp.text;
  using iTextSharp.text.pdf;
  
  public partial class Print : System.Web.UI.Page
  {
      protected void Page_Load(object sender, EventArgs e)
      {
          SetPDF(File.ReadAllBytes("C:\\1686850.pdf"), "C:\\1686850_1.pdf"); //test files
      }
  
      private void SetPDF(byte[] file, string outputPath)
      {
          PdfReader reader = new PdfReader(file);
          int pageCount = reader.NumberOfPages;
          Rectangle pageSize = reader.GetPageSize(1);
  
          Document pdf = new Document(pageSize);
          PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(outputPath, FileMode.Create));
          pdf.Open();
  
          //This action leads directly to printer dialogue
          PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
          writer.AddJavaScript(jAction);
          //Omitting this loop and simply adding some text to the file produces the behavior I want.
          for (int i = 0; i &lt; pageCount; i++)
          {
              pdf.NewPage();
              PdfImportedPage page = writer.GetImportedPage(reader, i + 1);
              writer.DirectContent.AddTemplate(page, 0, 0);
          }
          pdf.Close();
  
          //Open the pdf in the frame
          frame1.Attributes["src"] = outputPath;
      }
  }
  </code></pre>