Export HTML string from database to PDF using iTextSharp 4.1.2.0 using C# and VB.Net in ASP.Net

ilanocf
 
on Nov 14, 2021 09:48 PM
Sample_211950.zip
956 Views

Hey guys,

I am using Visual Studio 2010 and I am completing a certificate to be generated in PDF using iTextSharp.

To generate the certificate, I'm bringing information from the database that has information in html with text marking, bold, italic, underlined, etc. formatting.

And I have two situations I need to resolve.

1. A part of the text is the concatenation of a predefined text with the student and course data.

My question is how to make bold only some data.

In the example below I concatenate a predefined text with some information coming from the database:

I certify that Fulano dos Anzóis Pereira completed the course in Basic Digital Electricity at the Centro Vocacional Tecnológico de Beberibe from 16/09 to 13/10/2021 a with a workload of 40h/a.

2. Get all the information from the programmatic content that comes from the database with formats worked in the Ajax Editor where users can use numbered lists, bold, underlined, ... that is, texts that contain characters like:

<div style="text-align: justify;"><span style="font-family: Arial;">Food Education in Self Care;
Macronutrients and their Functions;
Chrononutrition;
Food Behavior;
Functional Foods;
Foods in Disease Prevention;
Learning to Read Labels;
Preservation of Food through Bleaching.</span>

 

Partial Class aluno_relCertificadoVersoPDF
    Inherits System.Web.UI.Page
    Private Certificado As New DETI.objMatriculaCertificado
    Private Secreto As New Criptografia.ClassEncriptaDecripta 
    Private Sub PovoaDados()
        Dim Ds As Data.DataSet 
        ViewState("vlID") = Secreto.Decriptografa(Request("pID"))
        If ViewState("vlID") Is Nothing Or ViewState("vlID") = 0 Then Response.Redirect("index.aspx") 
        LbMensagem.Text = DBNull.Value.ToString 
        Ds = Certificado.ConsultaPadronizada(" SELECT A.ID, A.PESSOAID, A.EDITALITEMID, B.CURSOID, D.CPFCNPJ, C.EMENTA " & _
                                             " FROM MATRICULACERTIFICACAO A " & _
                                             " INNER JOIN EDITALITENS B ON (A.EDITALITEMID = B.ID) " & _
                                             " INNER JOIN CURSOS C ON (B.CURSOID = C.ID) " & _
                                             " INNER JOIN PESSOAS D ON (A.PESSOAID = D.ID) " & _
                                             " WHERE A.MATRICULAID = " & ViewState("vlID"))
        If Not Ds Is Nothing Then
            If Ds.Tables(0).Rows.Count > 0 Then
                CriarRelatorio(Ds.Tables(0).Rows(0)("CPFCNPJ"),
                               Server.HtmlDecode(Ds.Tables(0).Rows(0)("EMENTA")))
            Else
                If Ds.Tables(0).Rows.Count = 0 Then
                    LbMensagem.Text = "<div class='alert alert-danger'>Nenhuma informação foi encontrada.</div>"
                End If
            End If
        Else
            If Ds Is Nothing Then
                LbMensagem.Text = "<div class='alert alert-danger'>Nenhuma informação foi encontrada.</div>"
            End If
        End If 
    End Sub
 
    Private Sub CriarRelatorio(ByVal pCPF As String, ByVal pDados As String)
        Dim pCaminho As String
        pCaminho = Server.MapPath("pdfs")
 
        If File.Exists(pCaminho + "/" & pCPF & ".pdf") Then
            File.Delete(pCaminho + "/" & pCPF & ".pdf")
        End If
 
        'Atribuir fontes do servidor na aplicação
        FontFactory.RegisterDirectory("C:\WINDOWS\Fonts")
        Dim cellFont As Font = FontFactory.GetFont("Arial", 16.0F, Font.NORMAL)
        Dim cellFont3 As Font = FontFactory.GetFont("Arial", 9.0F, 0, Color.BLACK)
 
        'Criar uma instância de document
        Dim doc As New Document(iTextSharp.text.PageSize.A4.Rotate, 20, 20, 20, 20)
        PdfWriter.GetInstance(doc, New FileStream(pCaminho + "/" & pCPF & ".pdf", FileMode.Create))
        hfArquivo.Value = "pdfs/" & pCPF & ".pdf"
 
        Dim phrase As Phrase = Nothing 'Dados do certificado
        doc.Open()
        doc.Add(New Phrase(pDados))
        doc.Close() 
        If File.Exists(pCaminho + "/" & pCPF & ".pdf") Then
            BtnDownload.Visible = True
        End If 
    End Sub
End Class

Thank you in advance for your attention.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunv
 
on Nov 17, 2021 11:49 PM

Hi Ilanocf,

 Please refer below Sample.

Package

Install-Package iTextSharp-4.1.2.0 -Version 4.1.2

HTML

<asp:Label ID="LbMensagem" runat="server" />
<asp:HiddenField ID="hfArquivo" runat="server" />

Namespaces

C#

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Collections;
using System.Data;
using System.IO;

VB.Net

Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Imports System.Collections
Imports System.Data
Imports System.IO

Code

C#

protected void Page_Load(object sender, System.EventArgs e)
{
    if (!IsPostBack)
        PovoaDados();
}

private void PovoaDados()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[]
    {
            new DataColumn("ID"),
            new DataColumn("PESSOAID"),
            new DataColumn("EDITALITEMID"),
            new DataColumn("CURSOID"),
            new DataColumn("CPFCNPJ"),
            new DataColumn("EMENTA")
    });
    dt.Rows.Add("1", "1", "IT", ".Net", "ABC", "123");

    DataSet Ds = new DataSet();
    Ds.Tables.Add(dt);
    if (Ds != null)
    {
        string html = " &lt;div style=&quot;text-align: justify;&quot;&gt; &lt;span style=&quot;font-family: Arial;color: red;font-weight:bold;&quot; &gt; Food Education in Self Care; Macronutrients and their Functions;";
        html += "Chrononutrition;Food Behavior;Functional Foods;Foods in Disease Prevention;Learning to Read Labels;Preservation of Food through Bleaching.&lt;/span&gt;&lt;/div&gt;";
        if (Ds.Tables[0].Rows.Count > 0)
        {
            CriarRelatorio(Ds.Tables[0].Rows[0]["CPFCNPJ"].ToString(), Ds.Tables[0].Rows[0]["EMENTA"].ToString() + Server.HtmlDecode(html));
        }
        else if (Ds.Tables[0].Rows.Count == 0)
        {
            LbMensagem.Text = "<div class='alert alert-danger'>Nenhuma informação foi encontrada.</div>";
        }
    }
    else if (Ds == null)
        LbMensagem.Text = "<div class='alert alert-danger'>Nenhuma informação foi encontrada.</div>";
}

private void CriarRelatorio(string pCPF, string pDados)
{
    string pCaminho;
    pCaminho = Server.MapPath("pdfs");
    if (File.Exists(pCaminho + "/" + pCPF + ".pdf"))
        File.Delete(pCaminho + "/" + pCPF + ".pdf");
    // Atribuir fontes do servidor na aplicação
    FontFactory.RegisterDirectory(@"C:\WINDOWS\Fonts");
    Font cellFont = FontFactory.GetFont("Arial", 16.0F, Font.NORMAL);
    Font cellFont3 = FontFactory.GetFont("Arial", 9.0F, 0, Color.BLACK);
    // Criar uma instância de document
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    PdfWriter.GetInstance(doc, new FileStream(pCaminho + "/" + pCPF + ".pdf", FileMode.Create));
    doc.Open();
    // Convert the html and add to document.
    ArrayList htmlarraylist = HTMLWorker.ParseToList(new StringReader(pDados), null);
    for (int k = 0; k < htmlarraylist.Count; k++)
    {
        doc.Add((IElement)htmlarraylist[k]);
    }
        
    doc.Close();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then PovoaDados()
End Sub

Private Sub PovoaDados()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("ID"), New DataColumn("PESSOAID"), New DataColumn("EDITALITEMID"), New DataColumn("CURSOID"), New DataColumn("CPFCNPJ"), New DataColumn("EMENTA")})
    dt.Rows.Add("1", "1", "IT", ".Net", "ABC", "123")
    Dim Ds As DataSet = New DataSet()
    Ds.Tables.Add(dt)
    If Ds IsNot Nothing Then
        Dim html As String = " &lt;div style=&quot;text-align: justify;&quot;&gt; &lt;span style=&quot;font-family: Arial;color: red;font-weight:bold;&quot; &gt; Food Education in Self Care; Macronutrients and their Functions;"
        html += "Chrononutrition;Food Behavior;Functional Foods;Foods in Disease Prevention;Learning to Read Labels;Preservation of Food through Bleaching.&lt;/span&gt;&lt;/div&gt;"
        If Ds.Tables(0).Rows.Count > 0 Then
            CriarRelatorio(Ds.Tables(0).Rows(0)("CPFCNPJ").ToString(), Ds.Tables(0).Rows(0)("EMENTA").ToString() + Server.HtmlDecode(html))
        ElseIf Ds.Tables(0).Rows.Count = 0 Then
            LbMensagem.Text = "<div class='alert alert-danger'>Nenhuma informação foi encontrada.</div>"
        End If
    ElseIf Ds Is Nothing Then
        LbMensagem.Text = "<div class='alert alert-danger'>Nenhuma informação foi encontrada.</div>"
    End If
End Sub

Private Sub CriarRelatorio(ByVal pCPF As String, ByVal pDados As String)
    Dim pCaminho As String
    pCaminho = Server.MapPath("pdfs")
    If File.Exists(pCaminho & "/" & pCPF & ".pdf") Then File.Delete(pCaminho & "/" & pCPF & ".pdf")
    FontFactory.RegisterDirectory("C:\WINDOWS\Fonts")
    Dim cellFont As Font = FontFactory.GetFont("Arial", 16.0F, Font.NORMAL)
    Dim cellFont3 As Font = FontFactory.GetFont("Arial", 9.0F, 0, Color.BLACK)
    Dim doc As Document = New Document(PageSize.A4, 0, 0, 0, 0)
    PdfWriter.GetInstance(doc, New FileStream(pCaminho & "/" & pCPF & ".pdf", FileMode.Create))
    doc.Open()
    Dim htmlarraylist As ArrayList = HTMLWorker.ParseToList(New StringReader(pDados), Nothing)
    For k As Integer = 0 To htmlarraylist.Count - 1
        doc.Add(CType(htmlarraylist(k), IElement))
    Next
    doc.Close()
End Sub

Screenshot