Convert HTML String To PDF Via iText Library And Download

I decided post this code in this blog for my reference later if i go back again as Developer 🙂 This Project was a Sharepoint 2016 Project and still used web form asp.net application.

  1. Code the ascx (Usercontrol)

When the user is directed to this page, the user control automatically creates some html data regarding the information sent. Then after information are done, if you check on javascript code below, #btnprint triger to click and that button and execute javascript function PrintElem.

The PrintElem function is to collect the HTML code (see on the var printContents) then transfer to control txtPrint. After are done then call server side function btnExportToPdf_Click (__doPostBack(‘<%=btnExportToPdf.UniqueID%>’, ”);)

2. Reference library

HtmlAgilityPack and iText 7, you can download it from manage nuget on your visual studio.

3. Code

protected void btnExportToPdf_Click(object sender, EventArgs e)
{
StringBuilder contents = new StringBuilder(txtPrint.Text);
string mFilePath = string.Empty;

        //fungsi di bawah hanya untuk mendapatkan jumlah page
        using (MemoryStream ms = new MemoryStream())
        {
            HtmlDocument hDocument = new HtmlDocument
            {
                OptionWriteEmptyNodes = true,
                OptionAutoCloseOnEnd = true,
            };

            hDocument.LoadHtml(contents.ToString());
            var closedTags = hDocument.DocumentNode.WriteTo();

            FontProgram fontProgram = FontProgramFactory.CreateFont(@"C:\Windows\Fonts\calibri.ttf");
            PdfFont calibri = PdfFontFactory.CreateFont(fontProgram, PdfEncodings.WINANSI);

            iText.Kernel.Pdf.PdfWriter pdfWriter = new PdfWriter(ms);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            pdfDocument.AddFont(calibri);

            iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfWriter);
            pdfDoc.SetDefaultPageSize(iText.Kernel.Geom.PageSize.A4);

            HeadertFooterHandler handler = new HeadertFooterHandler();
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
            handler.setInfo(DocNo);

            using (Document document = new Document(pdfDoc))
            {
                /*document.SetMargins(10, 10, 10, 10);*/
                document.SetMargins(0, 0, 0, 0);
                document.SetFont(calibri);
                document.SetFontSize(8);
                document.SetWordSpacing(0);

                using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(closedTags.ToString())))
                {
                    /* KB : https://itextpdf.com/en/resources/books/itext-7-converting-html-pdf-pdfhtml/chapter-6-using-fonts-pdfhtml */

                    ConverterProperties properties = new ConverterProperties();
                    properties.SetFontProvider(new iText.Html2pdf.Resolver.Font.DefaultFontProvider(true, true, true));

                    HtmlConverter.ConvertToPdf(htmlMemoryStream, pdfDoc, properties);
                }
            }

            //byte[] mByte = ms.ToArray();

            //TR_AFA_HEADERS afa = AfaHeader;
            //mFilePath = string.Format("{0}/{1}/{2}/AFA_{3}_Print.pdf", SPContext.Current.Web.Url, afa.DocumentLibraryType, afa.AfaHeaderID, afa.Afa_Header_Id);

            //bool sts = Utils.SP_UploadDocument(SPContext.Current.Web.Url, mFilePath, mByte, afa.Afa_Number, afa.Afa_Purpose);

            contents = null;

            pdfDoc.Close();
            pdfWriter.Close();
            ms.Close();
        }

        using (MemoryStream ms = new MemoryStream())
        {
            HtmlDocument hDocument = new HtmlDocument
            {
                OptionWriteEmptyNodes = true,
                OptionAutoCloseOnEnd = true,
            };

            hDocument.LoadHtml(contents.ToString());
            var closedTags = hDocument.DocumentNode.WriteTo();

            FontProgram fontProgram = FontProgramFactory.CreateFont(@"C:\Windows\Fonts\calibri.ttf");
            PdfFont calibri = PdfFontFactory.CreateFont(fontProgram, PdfEncodings.WINANSI);

            iText.Kernel.Pdf.PdfWriter pdfWriter = new PdfWriter(ms);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            pdfDocument.AddFont(calibri);

            iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfWriter);
            pdfDoc.SetDefaultPageSize(iText.Kernel.Geom.PageSize.A4);

            HeadertFooterHandler handler = new HeadertFooterHandler();
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
            handler.setInfo(DocNo);

            using (Document document = new Document(pdfDoc))
            {
                /*document.SetMargins(10, 10, 10, 10);*/
                document.SetMargins(0, 0, 0, 0);
                document.SetFont(calibri);
                document.SetFontSize(8);
                document.SetWordSpacing(0);

                using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(closedTags.ToString())))
                {
                    /* KB : https://itextpdf.com/en/resources/books/itext-7-converting-html-pdf-pdfhtml/chapter-6-using-fonts-pdfhtml */

                    ConverterProperties properties = new ConverterProperties();
                    properties.SetFontProvider(new iText.Html2pdf.Resolver.Font.DefaultFontProvider(true, true, true));

                    HtmlConverter.ConvertToPdf(htmlMemoryStream, pdfDoc, properties);
                }
            }

            byte[] mByte = ms.ToArray();

            TR_AFA_HEADERS afa = AfaHeader;
            mFilePath = string.Format("{0}/{1}/{2}/AFA_{3}_Print.pdf", SPContext.Current.Web.Url, afa.DocumentLibraryType, afa.AfaHeaderID, afa.Afa_Header_Id);

            bool sts = Utils.SP_UploadDocument(SPContext.Current.Web.Url, mFilePath, mByte, afa.Afa_Number, afa.Afa_Purpose);

            contents = null;

            pdfDoc.Close();
            pdfWriter.Close();
            ms.Close();
        }
        loading_screen.Attributes.Add("style", "display:none");
        Response.Redirect(mFilePath);
    }


}

public class HeadertFooterHandler : IEventHandler
{
    String info;
    public void setInfo(String info)
    {
        this.info = info;
    }
    public String getInfo()
    {
        return info;
    }

    public void HandleEvent(Event @event)
    {
        iText.Kernel.Colors.Color colorGray = new DeviceRgb(128, 128, 128);

        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
        PdfPage page = docEvent.GetPage();
        int pageNum = docEvent.GetDocument().GetPageNumber(page);

        iText.Kernel.Geom.Rectangle pageSize = page.GetPageSize();
        PdfDocument pdfDoc = ((PdfDocumentEvent)@event).GetDocument();

        PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);

        new Canvas(pdfCanvas, pdfDoc, pageSize)
         //header
         .SetFontSize(4)
         .SetOpacity(2)
         .SetFontColor(colorGray)
         .ShowTextAligned(info, 10, pageSize.GetTop() - 20, TextAlignment.LEFT, VerticalAlignment.MIDDLE, 0)
         .ShowTextAligned(string.Format("{0:dd MMM yyyy HH:mm:ss}", DateTime.Now), 10, 30, TextAlignment.LEFT, VerticalAlignment.MIDDLE, 0)
         .ShowTextAligned(string.Format("Page {0} of {1}",pageNum.ToString(), docEvent.GetDocument().GetNumberOfPages()), pageSize.GetWidth() - 60, 30, TextAlignment.RIGHT, VerticalAlignment.MIDDLE, 0);
    }
}

Sample screenshot

Happy Sharepoint-ing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.