用iTextSharp将HTML转换成PDF,ASP.NET C# 代码

先去github下载源代码:https://github.com/itext/itextsharp,当前最新版本为5.5.13

解压后用vs2010打开工程文件BuildAll,生成itextsharp.xmlworker项目

生成的dll文件在src\extras\itextsharp.xmlworker\bin\Debug_woDrawing目录中

在自已的项目引入itextsharp.dll 和 itextsharp.xmlworker.dll

写一个简单的Helper类

using System;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

public class PDFHelper {
    public static void Html2Pdf(string html, string filename) {
            using (Stream fs = new FileStream(filename, FileMode.Create)) {
                using (Document doc = new Document(PageSize.A4)) {

                    PdfWriter writer = PdfWriter.GetInstance(doc, fs);
                    doc.Open();

                    using (StringReader sr = new StringReader(html)) {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
                    }

                    doc.Close();
                    
                }
            }
        }

    }

调用:

string file = Server.MapPath("test.pdf");
string html = "
底部

Hello World! 中文





锚链接
测试内容
"; PDFHelper.Html2Pdf(html, file);

注意:要设置中文字体才能显示中文,默认字体不会显示中文

 

参考:

https://stackoverflow.com/questions/25164257/how-to-convert-html-to-pdf-using-itextsharp

https://itextsupport.com/apidocs/iText5/5.5.12/

https://itextpdf.com/en/resources/examples

http://www.codexy.cn/csharp/csharp-tutorial.html

https://www.codeproject.com/Tips/899658/Create-PDF-With-Bookmark-and-TOC-from-HTML-with-iT

https://www.mikesdotnetting.com/article/84/itextsharp-links-and-bookmarks

https://acrobatusers.com/forum/javascript/change-documents-properties-intial-view-js/

你可能感兴趣的:(C#)