How to get ordered list into pdf using itext?

半世苍凉 提交于 2019-12-25 17:03:14

问题


I have to get an ordered list into pdf.The data stored is in html format.When exporting to pdf using itextsharp,the ol-li tags should be replaced by an ordered list.


回答1:


You'll want to use iTextSharp's iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList() method. Below is a full working sample WinForms app targeting iTextSharp 5.1.1.0 that does what you're looking for. See the inline comments for what's going on.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //File to export to
            string exportFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "HTML.pdf");

            //Create our PDF document
            using (Document doc = new Document(PageSize.LETTER)){
                using (FileStream fs = new FileStream(exportFile, FileMode.Create, FileAccess.Write, FileShare.Read)){
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)){

                        //Open the doc for writing
                        doc.Open();

                        //Insert a page
                        doc.NewPage();

                        //This is our sample HTML
                        String HTML = "<ol><li>Row 1</li><li>Row 2</li></ol>";

                        //Create a StringReader to parse our text
                        using (StringReader sr = new StringReader(HTML))
                        {
                            //Pass our StringReader into iTextSharp's HTML parser, get back a list of iTextSharp elements
                            List<IElement> ies = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);

                            //Loop through each element and add to the document
                            foreach (IElement ie in ies)
                            {
                                doc.Add(ie);
                            }
                        }
                        //Close our document
                        doc.Close();
                    }
                }
            }
        }
    }
}


来源:https://stackoverflow.com/questions/6907580/how-to-get-ordered-list-into-pdf-using-itext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!