How do I use iTextSharp to turn my current page into a .pdf?

I've included iTextSharp into my web app and now I want to know how to, using C#, convert the current page that I'm on into a .pdf file using iTextSharp. I've been unable to find any examples thus far. So for example: if my page is named: "test.aspx" and I'm coding in my: "test.aspx.cs" file, how do I convert my "test.aspx" page into a .pdf? I'm using visual studio 2012.
LVL 1
Michael SterlingWeb Applications DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Najam UddinCommented:
0
Michael SterlingWeb Applications DeveloperAuthor Commented:
Najam, that rendered me a .pdf of the HTML. I need the actual page. From that sample of code, is there a way to get the actual page?
0
LajuanTaylorCommented:
@mikesExpertExchange - When you say " get the actual page",  are you referring to the "test.aspx" page source before it's rendered back to the browser as HTML?
1
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

Michael SterlingWeb Applications DeveloperAuthor Commented:
@LajuanTaylor: Yes that's exactly what I get.

pdf image 1
pdf image 2
pdf image 3
0
LajuanTaylorCommented:
Can you share a sample of the test .aspx page and the code behind?

What version of iTextSharp are you using and what version of .NET framework are you deploying to?
0
Michael SterlingWeb Applications DeveloperAuthor Commented:
No problem. I believe I'm using the latest version of iTextSharp, Version 5.5.7. here is my .aspx page in its entirety.

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="DowloadPrintVolvoCert.aspx.cs"
    Inherits="DowloadPrintVolvoCert" EnableEventValidation="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        .navbar-nav {
            display: none;
            float: left;
            margin: 0;
        }

        .imageDiv, .mainMenuBackground {
            display: none;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <div class="col-xs-12">
        <div class="row">
            <div class="col-xs-12 center" style="background-image: url('Images/VPC-Certificate-050515_FINAL.jpg'); height: 900px; width: 1024px;">
                <div class="row" style="padding: 455px 0 0 289px;">
                    <div class="col-xs-6 col-xs-pull-1 text-left" style="padding: 0 0 0 60px;">
                        <asp:Label runat="server" ID="lblYear" Text="2015" Font-Bold="true" ForeColor="#222021"></asp:Label>
                    </div>
                    <div class="col-xs-6 col-xs-pull-2 text-left" style="padding: 0 0 0 65px;">
                        <asp:Label runat="server" ID="lblMileage" Text="100,000" Font-Bold="true" ForeColor="#222021"></asp:Label>
                    </div>
                </div>
                <div class="row" style="padding: 35px 0 0 289px;">
                    <div class="col-xs-6 col-xs-pull-1 text-left" style="padding: 0 0 0 60px;">
                        <asp:Label runat="server" ID="lblMake" Text="VOLVO" Font-Bold="true" ForeColor="#222021"></asp:Label>
                    </div>
                    <div class="col-xs-6 col-xs-pull-2 text-left" style="padding: 0 0 0 65px;">
                        <asp:Label runat="server" ID="lblVin" Text="4V4NC9EH7CN534799" Font-Bold="true" ForeColor="#222021"></asp:Label>
                    </div>
                </div>
                <div class="row" style="padding: 35px 0 0 289px;">
                    <div class="col-xs-6 col-xs-pull-1 text-left" style="padding: 0 0 0 60px;">
                        <asp:Label runat="server" ID="lblModel" Text="VNL-670" Font-Bold="true" ForeColor="#222021"></asp:Label>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="center">
                <asp:Button ID="btnCreatePDF" runat="server" class="btn btn-primary center" Text="Download PDF" OnClick="btnCreatePDF_Click" />
            </div>
        </div>
    </div>
</asp:Content>

Open in new window


here is my code behind:

    protected void btnCreatePDF_Click(object sender, EventArgs e)
    {
        try
        {
            Response.ContentType = "application/pdf"; // Setting the application

            // Assigning the header
            Response.AddHeader("content-disposition", "attachment;filename=Image.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //Creating the object of the String Writer.
            StringWriter sw = new StringWriter();

            // Creating the object of HTML Writer and passing the object of String Writer to HTMl Text Writer
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            this.Page.RenderControl(hw);

            // Now we what ever is rendered on the page we will give it to the object of the String reader so that we can 
            StringReader srdr = new StringReader(sw.ToString());

            // Creating the PDF DOCUMENT using the Document class from Itextsharp.pdf namespace
            Document pdfDoc = new Document(PageSize.A4, 15F, 15F, 75F, 0.2F);

            // HTML Worker allows us to parse the HTML Content to the PDF Document.To do this we will pass the object of Document class as a Parameter.
            HTMLWorker hparse = new HTMLWorker(pdfDoc);
            // Finally we write data to PDF and open the Document
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();

            // Now we will pass the entire content that is stored in String reader to HTML Worker object to achieve the data from to String to HTML and then to PDF.
            hparse.Parse(srdr);

            pdfDoc.Close();
            // Now finally we write to the PDF Document using the Response.Write method.
            Response.Write(pdfDoc);
            Response.End();

        }
        catch (Exception ex)
        {
        }
    }

Open in new window


I am using version 4.5 of .NET. Also if you notice, in my .aspx page, the dive that surrounds the information has a background image, I need that image in the PDF as well.
0
LajuanTaylorCommented:
@mikesExpertExchange - Please see the attached zip file. I removed the iTextSharp.dll from the bin directory so the demo would upload. I did test using the latest 5.5.7 core from iTextSharp.

One potential warning that I received from my IDE is that the HTMLWorker class is obsolete. The alternative would be to use the iText xmlWorker class. Here is a link to the iText documentation with an example of how to parse HTML using the xmlWorker http://demo.itextsupport.com/xmlworker/itextdoc/flatsite.html#itextdoc-menu-7

As for the attached demo, you have three options to generate the pdf document. I'm recommending that you try the solution that leverages the HTML template approach. Basically, you would create a very basic HTML certificate document with a few dynamic variables that can be populated at runtime.

The instructions that explain the demo can be found in the attached pdf.
PDFCreate.zip
TechNotes_iTextPdf_Using_ASP_NET.pdf
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Michael SterlingWeb Applications DeveloperAuthor Commented:
@LajuanTaylor: This seems pretty straight forward and easy to follow. What seems to be missing thought is how to set a backgrournd image to the PDF. If its possible, I need to set a background image to the entire pdf file. Is this explained or shown in an example somewhere?
0
LajuanTaylorCommented:
@mikesExpertExchange - Yes/No. If you look in the .cs file for the ConvertHTMLtoPDF you will see the code for adding a page image. Perhaps you can place this in a div or use some css in the template .html:

// You can add additional elements to the document. Let's add an image in the upper right corner
        var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/yourImageFile.jpg"));
        logo.SetAbsolutePosition(440, 800);
        document.Add(logo);

Open in new window

0
Michael SterlingWeb Applications DeveloperAuthor Commented:
@LajuanTaylor: Thank you. I'd tried that line initially and it didn't work, but upon further review, I see/saw that I needed to change the starting coordinates to be (0, 0). So my image applied perfectly, with the exception of one final piece. How do I get the pdf to layout in a landscape verses portrait? I still need my content to remain the same, going from top to bottom, but need to make the pdf landscape. How do I do this.
0
LajuanTaylorCommented:
@mikesExpertExchange - Try something like...
Document pdfDoc = new Document(PageSize.A4.Rotate(), 15F, 15F, 75F, 0.2F);

or

document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());

Open in new window

0
Michael SterlingWeb Applications DeveloperAuthor Commented:
@LajuanTaylor: I figured it out (found it out). I just needed to change theoriginal dimensions of the document:

        Document document = new Document(new Rectangle(200f, 300f));
0
Michael SterlingWeb Applications DeveloperAuthor Commented:
Thank you for your help with this.
0
LajuanTaylorCommented:
@mikesExpertExchange - No problem.

Regards
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.