如何使用itext将有序列表转换为pdf

如何使用itext将有序列表转换为pdf

本文介绍了如何使用itext将有序列表转换为pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将一个有序列表转换成pdf。存储的数据是html格式。当使用itextsharp导出为pdf时,ol-li标签应该被有序列表替换。

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.

推荐答案

你想要使用iTextSharp的 iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList()方法。下面是一个针对iTextSharp 5.1.1.0的完整工作示例WinForms应用程序,它可以满足您的需求。请参阅内联评论,了解正在发生的事情。

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();
                    }
                }
            }
        }
    }
}

这篇关于如何使用itext将有序列表转换为pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:31