先去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/