• 使用iTextSharp实现html文件转PDF
  • 发布于 2个月前
  • 317 热度
    0 评论
概述
html文件怎么转成PDF文件?有的招聘网上的简历导成DOC文件,不能直接使用,这样造成很大的困扰,那么它还有一个格式,那就是html格式。将文件导出成html格式,然后再转成PDF文件,这样便可以直接使用了。平常在项目中也是很多这样的需求,需要把内容转成pdf文件。下面我们来看下使用  iTextSharp实现HTML转PDF的方法。

代码实现
1、nuget 安装iTextSharp。

using iTextSharp.text;
using iTextSharp.text.pdf;
2、将Html文档转换为pdf。
  /// <summary>
       /// 堆代码 duidaima.com
        /// 将Html文档转换为pdf
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
                return null;
            //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签
            htmlText = "<p>" + htmlText + "</p>";
            using (var outputStream = new MemoryStream())
            {
                byte[] data = Encoding.UTF8.GetBytes(htmlText);
                var msInput = new MemoryStream(data);
                var doc = new Document();//pdf文档,默认A4格式。
                var writer = PdfWriter.GetInstance(doc, outputStream);
                doc.Open();
                //使用XMLWorkerHelper把Html parse到PDF
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
                //指定默认缩放比例为100%
                var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
                //将默认设置写入pdf
                var action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);
                doc.Close();
                msInput.Close();
                outputStream.Close();
                return outputStream.ToArray();
            }
        }
3、Unicode 字体支持。
   /// <summary>
        /// Unicode 字体支持
        /// </summary>
        public class UnicodeFontFactory : FontFactoryImp
        {
            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
            {
                //使用微软雅黑字体解决中文乱码的问题,因为雅黑字体为字体集合所以需要使用,0来指定具体的字体。
                //var chineseFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msyh.ttc,0");
                //宋体
                //BaseFont baseFont = BaseFont.CreateFont(@"c:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //黑体
                BaseFont baseFont = BaseFont.CreateFont(@"c:\Windows\Fonts\SIMHEI.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //var baseFont = BaseFont.CreateFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                return new Font(baseFont, size, style, color);
            }
        }
4、调用生成。
  string content = temp.Content;
            foreach (var dict in dicts)
            {
                content = content.Replace("{{" + dict.Key + "}}", dict.Value);
            }
            var path = _esignInfo.Value.ContractPath;
            //if (entity.ContractType == ContractType.First)
            //{
            //    path += "/" + appId + "/Agreements";
            //}
            entity.OriginalFileUrl = _pdfHelper.WritePdfFile(content, contractNo, path, "PDF");
            bool isSucc = !String.IsNullOrEmpty(entity.OriginalFileUrl);



用户评论