Convert HTML files to PDF and save as Zip file using C# and VB.Net in ASP.Net

Last Reply 9 days ago By pandeyism

Posted 9 days ago

Hello,

How to convert a list of html files from a dropdownlist box into a list of pdf files, save all converted pdf files in a folder of a project solution in MS Visuo Studio? I'm using ASP.NET and C#

C#:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DropdownListSession
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack)
            {
                if (Session["ListItems"] == null)
                {
                    DataTable dt = DropDownItems();
                    DropDownList1.DataSource = dt;
                    DropDownList1.DataTextField = "Text";
                    DropDownList1.DataValueField = "Value";
                    DropDownList1.DataBind();
                    Session["ListItems"] = dt;
                }
            }
        }

        private DataTable DropDownItems()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Text");
            dt.Columns.Add("Value");
            dt.Rows.Add("Item1", "1");
            dt.Rows.Add("Item2", "2");
            dt.Rows.Add("Item3", "3");
            dt.Rows.Add("Item4", "4");
            return dt;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable dt = Session["ListItems"] as DataTable;
            ListItemCollection liCol = DropDownList1.Items;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ListItem li = liCol[i];
                if (li.Selected)
                {
                    Response.Redirect("Next.aspx");
                    dt.Rows[i].Delete();
                }
            }
            Session["ListItem"] = dt;
            DropDownList1.DataSource = dt;
            DropDownList1.DataTextField = "Text";
            DropDownList1.DataValueField = "Value";
            DropDownList1.DataBind();
        }
    }
}

HTML:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropdownListSession._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>

 

You are viewing reply posted by: pandeyism 9 days ago.
Posted 9 days ago

Hi KatieNgoc,

Refer below sample.

HTML

<asp:DropDownList runat="server" ID="ddlFiles" AutoPostBack="true" OnSelectedIndexChanged="ConverToPDF">
    <asp:ListItem Text="----Files----" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" Text="Download " runat="server" OnClick="Download" />

Namespaces

C#

using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using Ionic.Zip;

VB.Net

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports Ionic.Zip

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        int i = 0;
        foreach (string filePath in Directory.GetFiles(Server.MapPath("~/HtmlFiles")))
        {
            i = i + 1;
            ddlFiles.Items.Insert(i, new System.Web.UI.WebControls.ListItem(filePath, "" + i + ""));
        }
    }
}

protected void ConverToPDF(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            using (StreamReader sr = new StreamReader(ddlFiles.SelectedItem.Text))
            {
                using (FileStream stream = new FileStream(Server.MapPath("~/File/") + "HTMLExport" + ddlFiles.SelectedItem.Value + ".pdf", FileMode.Create))
                {
                    Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                    PdfWriter.GetInstance(pdfDoc, stream);
                    pdfDoc.Open();
                    htmlparser.Parse(sr);
                    pdfDoc.Close();
                    stream.Close();
                }
            }
        }
    }
}

protected void Download(object sender, EventArgs e)
{
    int i = 0;
    using (ZipFile zip = new ZipFile())
    {
        zip.AlternateEncodingUsage = ZipOption.AsNecessary;
        zip.AddDirectoryByName("Files");
        foreach (var filePath in Directory.GetFiles(Server.MapPath("~/File")))
        {
            i = i + 1;
            zip.AddFile(filePath, "Files");
        }
        Response.Clear();
        Response.BufferOutput = false;
        string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
        zip.Save(Response.OutputStream);
        Response.End();
    }
}

VB.Net

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not Me.IsPostBack Then
            Dim i As Integer = 0
            For Each filePath As String In Directory.GetFiles(Server.MapPath("~/HtmlFiles"))
                i = i + 1
                ddlFiles.Items.Insert(i, New System.Web.UI.WebControls.ListItem(filePath, "" & i & ""))
            Next
        End If
    End Sub

    Protected Sub ConverToPDF(ByVal sender As Object, ByVal e As EventArgs)
        Using sw As StringWriter = New StringWriter()
            Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
                Using sr As StreamReader = New StreamReader(ddlFiles.SelectedItem.Text)
                    Using stream As FileStream = New FileStream(Server.MapPath("~/File/") & "HTMLExport" + ddlFiles.SelectedItem.Value & ".pdf", FileMode.Create)
                        Dim pdfDoc As Document = New Document(PageSize.A2, 10F, 10F, 10F, 0F)
                        Dim htmlparser As HTMLWorker = New HTMLWorker(pdfDoc)
                        PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
                        PdfWriter.GetInstance(pdfDoc, stream)
                        pdfDoc.Open()
                        htmlparser.Parse(sr)
                        pdfDoc.Close()
                        stream.Close()
                    End Using
                End Using
            End Using
        End Using
    End Sub

    Protected Sub Download(ByVal sender As Object, ByVal e As EventArgs)
        Dim i As Integer = 0
        Using zip As ZipFile = New ZipFile()
            zip.AlternateEncodingUsage = ZipOption.AsNecessary
            zip.AddDirectoryByName("Files")
            For Each filePath In Directory.GetFiles(Server.MapPath("~/File"))
                i = i + 1
                zip.AddFile(filePath, "Files")
            Next
            Response.Clear()
            Response.BufferOutput = False
            Dim zipName As String = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
            Response.ContentType = "application/zip"
            Response.AddHeader("content-disposition", "attachment; filename=" & zipName)
            zip.Save(Response.OutputStream)
            Response.End()
        End Using
    End Sub

Screenshot