Export Table to PDF with style (CSS) in ASP.Net using iTextSharp

akhter
 
on Dec 19, 2021 11:50 PM
Sample_138880.zip
1136 Views

I want to use below style while exporting, but it is not applying error coming stack empty.

<style>
    table, th, td {
        border: 1px solid black;
    }
</style>

with below code

StringBuilder sb = new StringBuilder();
sb.Append("<table><tr><th width='5%'>Section</th><th width='5%'>Small_Bale_weight</th><th width='5%'>Small_Bale_weight1</th></tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
   
    sb.Append("<tr>");
    sb.Append("<td width='5%'  >" + dt.Rows[i]["Section"] + "</td><td width='5%'>" + dt.Rows[i]["Small_Bale_weight"] + "</td>  ");
    sb.Append("<td width='15%'>" + dt.Rows[i]["Small_Bale_weight1"] + "</td>  ");
    sb.Append("</tr>");
}
sb.Append("</table>");

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 20, 2021 04:28 AM

Hi akhter,

Add a stylesheet to the project and add the css to it. Then use that file to apply the while exporting to pdf.

Refer below example.

HTML

<asp:Button Text="Generate PDF" Font-Bold="true" runat="server" ID="txtGeneratePdf" OnClick="GeneratePDF" />

CSS

table {
    border: 1px solid #ccc;
}

table th, table td {
    border: 1px solid #ccc;
}

Namespaces

C#

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

VB.Net

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

Code

C#

protected void GeneratePDF(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] {
        new DataColumn("ID", typeof(Int32)),
        new DataColumn("Name"),
        new DataColumn("Country")
    });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");

    StringBuilder sb = new StringBuilder();
    sb.Append("<table><tr><th width='5%'>Id</th><th width='20%'>Name</th><th width='15%'>Country</th></tr>");
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        sb.Append("<tr>");
        sb.Append("<td width='5%'>" + dt.Rows[i]["ID"] + "</td><td width='20%'>" + dt.Rows[i]["Name"] + "</td><td width='15%'>" + dt.Rows[i]["Country"] + "</td>");
        sb.Append("</tr>");
    }
    sb.Append("</table>");


    StringReader sr = new StringReader(sb.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 GeneratePDF(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("ID", GetType(Int32)), New DataColumn("Name"), New DataColumn("Country")})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Suzanne Mathews", "France")
    dt.Rows.Add(4, "Robert Schidner", "Russia")
    Dim sb As StringBuilder = New StringBuilder()
    sb.Append("<table><tr><th width='5%'>Id</th><th width='20%'>Name</th><th width='15%'>Country</th></tr>")
    For i As Integer = 0 To dt.Rows.Count - 1 Step 1
        sb.Append("<tr>")
        sb.Append("<td width='5%'>" & dt.Rows(i)("ID") & "</td><td width='20%'>" + dt.Rows(i)("Name") & "</td><td width='15%'>" + dt.Rows(i)("Country") & "</td>")
        sb.Append("</tr>")
    Next
    sb.Append("</table>")
    Dim sr As StringReader = New StringReader(sb.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