Properly Export Html to PDF using iTextsharp c#

iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF).
Export Html to PDF using iTextsharp

Important Note: Make sure, yea, very important make sure that your HTML is well structured and all tags are closed. If not you'll get an error.

Usings


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

Create a method called GetPDF to create PDF stream in memory


public static byte[] GetPDF(string pHTML)
        {
            byte[] bPDF = null;

            MemoryStream ms = new MemoryStream();

            TextReader txtReader = new StringReader(pHTML);

            // 1: create object of a itextsharp document class
            Document doc = new Document(PageSize.A4, 5,5,5, 5);
            
            // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
            PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);

            // 3: we create a worker parse the document

            HTMLWorker htmlWorker = new HTMLWorker(doc);


            // 4: we open document and start the worker on the document
            doc.Open();

            htmlWorker.StartDocument();

            // 5: parse the html into the document
            try
            {
                htmlWorker.Parse(new StringReader(pHTML));
            }
            catch (Exception e)
            {

                MessageBox.Show(e.Message);
            }
          

            // 6: close the document and the worker
            htmlWorker.EndDocument();
            htmlWorker.Close();

            doc.Close();


            bPDF = ms.ToArray();

            return bPDF;
        }

Save The stream into a PDF file

  public static void save_pdf (byte [] pdf_stream, string save_as)
        {
            File.WriteAllBytes(save_as, pdf_stream);
        }

Commentaires

Posts les plus consultés de ce blog

Caractéristiques de PROLAB LIS SILVER (logiciel de gestion de laboratoire d'analyses médicales)

Solution GED sur le Cloud (Gestion électronique des documents)

How Slack's Custom Mobile App Development Solved the £8.2 Billion Productivity Problem