Link to home
Start Free TrialLog in
Avatar of Michael Sterling
Michael SterlingFlag for United States of America

asked on

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.
Avatar of Najam Uddin
Najam Uddin
Flag of United States of America image

Avatar of Michael Sterling

ASKER

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?
Avatar of LajuanTaylor
LajuanTaylor

@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?
@LajuanTaylor: Yes that's exactly what I get.

User generated image
User generated image
User generated image
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?
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.
ASKER CERTIFIED SOLUTION
Avatar of LajuanTaylor
LajuanTaylor

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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?
@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

@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.
@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

@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));
Thank you for your help with this.
@mikesExpertExchange - No problem.

Regards