iTextSharp–Print PDF

To print the HTML page, we use the below code.

window.print();

But the same can not be used to print the PDF as it won’t work. However, iTextSharp provides a way to print the PDF on the client side with the AddJavaScript method of PdfWriter.

Check out the below code:


private void CreatePDF()
    {
        string fileName = string.Empty;

        DateTime fileCreationDatetime = DateTime.Now;

        fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));

        string pdfPath = @"E:\PDFs\" + fileName;

        using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
        {
            //step 1
            using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 10f))
            {
                try
                {
                    // step 2
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);

                    //open the stream
                    pdfDoc.Open();

                    Phrase phrase1 = new Phrase("Hello world. Checking Print Functionality");

                    pdfDoc.Add(phrase1);

                    pdfWriter.AddJavaScript("this.print();");

                    pdfDoc.Close();

                    pdfDoc.Dispose();

                }
                catch (Exception ex)
                {
                    //handle exception
                }

                finally
                {

                }

            }

        }
    }

It won’t print the PDF directly but will open the print dialogue as soon as you open the PDF. One can choose one of the listed printers and print it. There won’t be any print preview. To simulate the print functionality on a web page, one can assign a pdf path to Iframe, which will be hidden on the page.

As you can see, there’s no path assigned to the src attribute in HTML, but in the code behind, as shown below:


pdfViewer.Attributes["src"]= ResolveClientUrl(string.Format("~/PDF/{0}",fileName));

It won’t display the PDF in the browser but will ask the user to print the PDF (without a preview). Both Firefox and Chrome use the inbuilt pdf viewer.

Known Issues:

  • It will not display PDF in IE and Opera but download it if no pdf viewer is installed on the machine and the respective add-on is not installed on both browsers. For Opera 15 onwards, you can install this add-on based on Mozilla’s pdf.js.
  • If pdf viewer has a setting to view pdf in secure mode and is enabled, it will not run javascript and will give a warning.

I hope it helps!


Posted

in

,

by

Comments

Leave a Reply

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

%d bloggers like this: