convert HTML to PDF in C#

To convert a HTML file into a PDF file in C# is not as hard as it sounds. All you need is a usefull library, and there are many. For example you can use iTextSharp. This one is for free until version 4.1.6 and you can get it here.

To use it you'll just need one funtion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private void createPDF(string htmlcode, string PDFPath)
        {
            try
            {
                FileStream FS = new FileStream(PDFPath, FileMode.Create);

                TextReader reader = new StringReader(html);


                // step 1: creation of a document-object
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);

                // step 2:
                // we create a writer that listens to the document
                // and directs a XML-stream to a file
                PdfWriter writer = PdfWriter.GetInstance(document, FS);

                // step 3: we create a worker parse the document
                HTMLWorker worker = new HTMLWorker(document);

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

                // step 5: parse the html into the document
                worker.Parse(reader);

                // step 6: close the document, the worker and the filestream
                worker.EndDocument();
                worker.Close();
                document.Close();
                FS.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Comments

Popular posts from this blog

How to support multiple languages in WPF