先去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 = "<div style=\"font-family:'Microsoft YaHei';\"><a href='#last'>底部</a><h1 style='padding:1000px 0'>Hello World! 中文<br/><br/><br/><br/><br/><br/></h1><a name='last'>锚链接</a><div style='color:#0a0'>测试内容</div></div>";
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/