Monday, February 11, 2019

How to create pdf and download using c#


In this article i have explain how to create pdf file from html content and download it using c# asp.net. so for doing this job i have used the itextsharp library.

1. Add the reference of itextsharp library. 
   
For doing this go to project solution and right click on it.


Now click on the manage NuGet package then search textsharp in search box and click on it and install it on your project.



2. Create the new web form and add following asp code

<form id="form1" runat="server">
        <div>
            <asp:Button ID="btnGeneratePdf" runat="server" Text="Generate PDF" OnClick="btnGeneratePdf_Click" />

        </div>
</form>
3. Now add the following into cs file 

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System;
using System.IO;
using System.Web;

namespace Google_Portal
{
    public partial class createpdf : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnGeneratePdf_Click(object sender, EventArgs e)
        {
            generatePDf();
        }
        protected void generatePDf()
        {
            string html = "<div style='width:100%;height:10%;text-align:center;background-color:#ddd;margin-top:20px;'>" +
                "<h1>This Is header</h1>" +
                "</div>" +
                 "<div style='width:100%;height:80%;text-align:center;color:red;'>" +
                "<h1>This Is Body</h1>" +
                "</div>" +
                 "<div style='width:100%;text-align:center;background-color:#000;color:#fff;'>" +
                "<h1>This Is Footer</h1>" +
                "</div>";
            string fileName = "demo-file";
            StringReader sr = new StringReader(html);
            Document pdfDoc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();

        }
}
}

Now click on generate PDF button


The Downloaded PDF is bellow 


No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...