Convert HTML to PDF with CSS using iText7 in ASP.Net

George616
 
on Sep 28, 2020 07:11 AM
Sample_227548.zip
9128 Views

Hello Forum,

I found that new iText7 supports CSS styles but I do not know how to use the C# code which I saw while searching the internet for solution to convert html to pdf with CSS support

Refer below article

https://stackoverflow.com/questions/47895935/converting-html-to-pdf-using-itext

 C#

public void generatePDF(String htmlFile) 
{
    try 
    {
        //HTML String
        String htmlString = htmlFile;
        //Setting destination 
        FileOutputStream fileOutputStream = new FileOutputStream(new File(dirPath + "/USER-16-PF-Report.pdf"));

        PdfWriter pdfWriter = new PdfWriter(fileOutputStream);
        ConverterProperties converterProperties = new ConverterProperties();
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

        //For setting the PAGE SIZE
        pdfDocument.setDefaultPageSize(new PageSize(PageSize.A3));

        Document document = HtmlConverter.convertToDocument(htmlFile, pdfDocument, converterProperties);
        document.close();
    } 
    catch (Exception e) {
         e.printStackTrace();
    }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 29, 2020 04:08 AM

Hi George616,

iTextSharp supports external css file. So use iTextSharp. Add the latest dll from nuget to your project and add the css style in external css file.

Check this example. Now please take its reference and correct your code.

HTML 

<link href="StyleSheet.css" rel="stylesheet" />
<asp:Panel ID="pnlPerson" runat="server">
    <table border="1" class="tableDetails">
        <tr>
            <td colspan="2" class="header">
                <b>Personal Details</b>
            </td>
        </tr>
        <tr>
            <td><b>Name</b></td>
            <td>
                <asp:Label ID="lblName" runat="server"></asp:Label></td>
        </tr>
        <tr>
            <td><b>Age</b></td>
            <td>
                <asp:Label ID="lblAge" runat="server"></asp:Label></td>
        </tr>
        <tr>
            <td><b>City</b></td>
            <td>
                <asp:Label ID="lblCity" runat="server"></asp:Label></td>
        </tr>
        <tr>
            <td><b>Country</b></td>
            <td>
                <asp:Label ID="lblCountry" runat="server"></asp:Label></td>
        </tr>
    </table>
</asp:Panel>
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />

StyleSheet.css

#tableDetails {
    font-family: Arial;
    font-size: 10pt;
    width: 200px;
}

.header {
    background-color: #18B5F0;
    height: 18px;
    color: White;
    border: 1px solid white;
    text-align: center;
}

Namespaces

C#

using System.Data;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;

VB.Net

Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Imports iTextSharp.tool.xml.html
Imports iTextSharp.tool.xml.parser
Imports iTextSharp.tool.xml.pipeline.css
Imports iTextSharp.tool.xml.pipeline.end
Imports iTextSharp.tool.xml.pipeline.html

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Populate DataTable
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Age");
        dt.Columns.Add("City");
        dt.Columns.Add("Country");
        dt.Rows.Add();
        dt.Rows[0]["Name"] = "Mudassar Khan";
        dt.Rows[0]["Age"] = "27";
        dt.Rows[0]["City"] = "Mumbai";
        dt.Rows[0]["Country"] = "India";

        //Bind Datatable to Labels
        lblName.Text = dt.Rows[0]["Name"].ToString();
        lblAge.Text = dt.Rows[0]["Age"].ToString();
        lblCity.Text = dt.Rows[0]["City"].ToString();
        lblCountry.Text = dt.Rows[0]["Country"].ToString();
    }
}
protected void btnExport_Click(object sender, EventArgs e)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    pnlPerson.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document();
    PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
    cssResolver.AddCssFile(Server.MapPath("~/StyleSheet.css"), true);
    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
    var worker = new XMLWorker(pipeline, true);
    var xmlParse = new XMLParser(true, worker);
    pdfDoc.Open();
    xmlParse.Parse(sr);
    xmlParse.Flush();
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.Add("Name")
        dt.Columns.Add("Age")
        dt.Columns.Add("City")
        dt.Columns.Add("Country")
        dt.Rows.Add()
        dt.Rows(0)("Name") = "Mudassar Khan"
        dt.Rows(0)("Age") = "27"
        dt.Rows(0)("City") = "Mumbai"
        dt.Rows(0)("Country") = "India"
        lblName.Text = dt.Rows(0)("Name").ToString()
        lblAge.Text = dt.Rows(0)("Age").ToString()
        lblCity.Text = dt.Rows(0)("City").ToString()
        lblCountry.Text = dt.Rows(0)("Country").ToString()
    End If
End Sub

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim sw As StringWriter = New StringWriter()
    Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
    pnlPerson.RenderControl(hw)
    Dim sr As StringReader = New StringReader(sw.ToString())
    Dim pdfDoc As Document = New Document()
    Dim PdfWriter As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    Dim htmlContext As HtmlPipelineContext = New HtmlPipelineContext(Nothing)
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory())
    Dim cssResolver As ICSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(False)
    cssResolver.AddCssFile(Server.MapPath("~/StyleSheet.css"), True)
    Dim pipeline As IPipeline = New CssResolverPipeline(cssResolver, New HtmlPipeline(htmlContext, New PdfWriterPipeline(pdfDoc, PdfWriter)))
    Dim worker = New XMLWorker(pipeline, True)
    Dim xmlParse = New XMLParser(True, worker)
    pdfDoc.Open()
    xmlParse.Parse(sr)
    xmlParse.Flush()
    pdfDoc.Close()
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.Write(pdfDoc)
    Response.End()
End Sub

Screenshot

The Form

Exported PDF

George616
 
on Sep 30, 2020 04:28 AM

Hi dharmendr,

I later tried this code and it is working, But the gridview width is not 100% in PDF and height is not the same as the one in the HTML

CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;
using System.Text;
using iText.Html2pdf;


     protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Item"), new DataColumn("Qty"), new DataColumn("Rate"), new DataColumn("Amount") });
            dt.Rows.Add("Supply Of Electrical Equipments", "20", "3000", "60000");
            dt.Rows.Add("Construction of Bore Hole", "2", "350000", "700000");
            dt.Rows.Add("Construction of Fish Pond", "7", "45000", "315000");
            dt.Rows.Add("Purcahse of Water Pump", "2", "70000", "140000");
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
       
    }

    public void generatePDF()
    {
        string fileName = "Invoice" + DateTime.Now.ToString() + ".pdf";

        Response.Clear();
        Response.ContentType = "Application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
        HtmlConverter.ConvertToPdf(getPanelHtml(), Response.OutputStream);
        Response.Flush();
        Response.Close();
        Response.End();
    }

    public string getPanelHtml()
    {
        StringBuilder sb = new StringBuilder();
        StringWriter tw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        Panel1.RenderControl(hw);
        var html = sb.ToString();

        return html;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        generatePDF();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }