locked
iTextSharp(convert aspx page to pdf ) RRS feed

  • Question

  • User441592953 posted

    Hello all!!

    I am trying to implement a demo certificate issue for my course project. While converting the aspx page to pdf, the image is not getting displayed at all. The image used here is in my own laptop in the same folder as that of the Certification.aspx file. In another laptop, the image is shown once but again the image is not shown. It is happening in  random basis.

    Please help.

    Thanks.

    This is the Certificatication.aspx page

    This page shows a course portal logo as an image and a line of text about the certificate.

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Certification.aspx.cs" Inherits="Certification" EnableEventValidation="false" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
           <!-- <asp:Image ID="Image1" runat="server" Height="402px" ImageUrl="certi.png" Width="923px" />  -->
            <br />
            <br />
            <br />
            
        
        
            
            <asp:Panel ID="Panel1" runat="server" Height="120px">
                
               <!--  <img src = "http://www.aspsnippets.com/images/Blue/Logo.png" /><br />  -->
       
                 <img src="E:\Pictures\1.jpg"  height="402" width="923" alt="Image" /><br/>
                <asp:Label ID="Label3" runat="server"></asp:Label>
            <br />
            <br />
            <b><i>Has successfully completed the requirements to complete the course on</i></b>&nbsp;&nbsp;
            <asp:Label ID="Label4" runat="server"></asp:Label>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Click to download as PDF." OnClick="Button1_Click1" />
    
            </asp:Panel>
        
            
        
        
        </div>
        </form>
    </body>
    </html>
    

    This is the Certification.aspx.cs file

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using iTextSharp.text.html;
    using iTextSharp.text.html.simpleparser;
    using System.Drawing;
    using System.IO;
    
    
    public partial class Certification : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string marks="",name="",course="";
            int marks1=0;
            string id = Session["email"].ToString();
            SqlConnection conn = new SqlConnection(); //creating connection reference object
    
            //conn.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\My Documents\Final Year Project\finalyear\finalyear\App_Data\newdatabase.mdf;Integrated Security=True";
            conn.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\My Documents\Final Year Project\finalyear\finalyear\App_Data\newdatabase.mdf;Integrated Security=True";
            conn.Open();  //opening connection
            string q = "select * from selectcourse where selectcourse.s_emailid='" + id + "'";
            SqlCommand cmd = new SqlCommand(q, conn);
            //execute query
            SqlDataReader reader = cmd.ExecuteReader();
    
            if (reader.Read() == true)
            {
                marks = reader.GetValue(3).ToString();
                marks1 = Convert.ToInt32(marks);
    
            }
            reader.Dispose();
            cmd.Dispose();
            
                string q1 = "select * from studentinfo where studentinfo.s_emailid='" + id + "'";
                SqlCommand cmd1 = new SqlCommand(q1, conn);
                //execute query
                SqlDataReader reader1 = cmd1.ExecuteReader();
    
                if (reader1.Read() == true)
                {
                    name = reader1.GetValue(1).ToString();
                }
                course = Session["course"].ToString();
                
                Label3.Text = name.ToString();
                Label4.Text = course.ToString();
    
            
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        protected void Button1_Click1(object sender, EventArgs e)
        {
            string attachment = "attachment; filename=" + "abc" + ".pdf";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/pdf";
            StringWriter s_tw = new StringWriter();
            HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
            h_textw.AddStyleAttribute("font-size", "7pt");
            h_textw.AddStyleAttribute("color", "Black");
            Panel1.RenderControl(h_textw);//Name of the Panel
            Document doc = new Document();
            doc = new Document(PageSize.A4, 5, 5, 15, 5);
            FontFactory.GetFont("Verdana", 80);
            PdfWriter.GetInstance(doc, Response.OutputStream);
            doc.Open();
            StringReader s_tr = new StringReader(s_tw.ToString());
            HTMLWorker html_worker = new HTMLWorker(doc);
            html_worker.Parse(s_tr);
            /*var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("certi.png"));
            logo.SetAbsolutePosition(0, 0);
            doc.Add(logo);*/ 
            doc.Close();
            Response.Write(doc);
    
        }
    }

    The page gets converted to pdf on the click of the button above.

    Friday, May 27, 2016 5:13 PM

Answers

  • User-821857111 posted

    The image won't display in the browser because your aspx file has a file path instead of a URL for the img tag's src attribute:

    <img src="E:\Pictures\1.jpg"  height="402" width="923" alt="Image" />

    And it won't display in the PDF because you have commented out the lines that add the image to the document.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 2, 2016 8:51 AM

All replies

  • User-1080604707 posted

    iTextSharp is quite good for many PDF tasks but not for HTML to PDF Conversion. I recommend you to try the free html to pdf converter for .net from HiQPdf Software ( I work for this company ). It can be used completely for free to generated small and medium PDF documents as it should be the case of your certificate. For large PDFs or advanced features you can upgrade anytime to professional version. I copy below the relevant HTML to PDF conversion code:

    protected void buttonConvertToPdf_Click(object sender, EventArgs e)
    {
        // create the HTML to PDF converter
        HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
    
        // set browser width
        htmlToPdfConverter.BrowserWidth = int.Parse(textBoxBrowserWidth.Text);
    
        // set browser height if specified, otherwise use the default
        if (textBoxBrowserHeight.Text.Length > 0)
            htmlToPdfConverter.BrowserHeight = int.Parse(textBoxBrowserHeight.Text);
    
        // set HTML Load timeout
        htmlToPdfConverter.HtmlLoadedTimeout = int.Parse(textBoxLoadHtmlTimeout.Text);
    
        // set PDF page size and orientation
        htmlToPdfConverter.Document.PageSize = GetSelectedPageSize();
        htmlToPdfConverter.Document.PageOrientation = GetSelectedPageOrientation();
    
        // set PDF page margins
        htmlToPdfConverter.Document.Margins = new PdfMargins(0);
    
        // set a wait time before starting the conversion
        htmlToPdfConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text);
    
        // convert HTML to PDF
        byte[] pdfBuffer = null;
    
        if (radioButtonConvertUrl.Checked)
        {
            // convert URL to a PDF memory buffer
            string url = textBoxUrl.Text;
    
            pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
        }
        else
        {
            // convert HTML code
            string htmlCode = textBoxHtmlCode.Text;
            string baseUrl = textBoxBaseUrl.Text;
    
            // convert HTML code to a PDF memory buffer
            pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, baseUrl);
        }
    
        // inform the browser about the binary data format
        HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
    
        // let the browser know how to open the PDF document, attachment or inline, and the file name
        HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=HtmlToPdf.pdf; size={1}",
            checkBoxOpenInline.Checked ? "inline" : "attachment", pdfBuffer.Length.ToString()));
    
        // write the PDF buffer to HTTP response
        HttpContext.Current.Response.BinaryWrite(pdfBuffer);
    
        // call End() method of HTTP response to stop ASP.NET page processing
        HttpContext.Current.Response.End();
    }


    Tuesday, May 31, 2016 2:55 PM
  • User-821857111 posted

    The image won't display in the browser because your aspx file has a file path instead of a URL for the img tag's src attribute:

    <img src="E:\Pictures\1.jpg"  height="402" width="923" alt="Image" />

    And it won't display in the PDF because you have commented out the lines that add the image to the document.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 2, 2016 8:51 AM