HTML to PDF

一、iTextSharp

1、安装组件

 

2、封装的代码

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

namespace CommonCore.Helpers
{
    public class HtmlToPdfHelper
    {
        /// <summary>
        /// 生成PDF
        /// </summary>
        /// <param name="pdfSavePath">pdf保存的位置 @"D:\pdffile"</param>
        /// <param name="fileName">pdf文件路径 @"D:\pdffile\sample.pdf"</param>
        /// <param name="fileName">完整的字体文件路径</param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public static bool BuilderPDF(string html, string pdfSavePath, string fileName, string fontPath = "")
        {
            try
            {
                if (!Directory.Exists(pdfSavePath)) Directory.CreateDirectory(pdfSavePath);
                using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    byte[] htmlByte = ConvertHtmlTextToPdf(html, fontPath);
                    fs.Write(htmlByte, 0, htmlByte.Length);
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("保存PDF到磁盘时异常", ex);
            }
        }
        /// <summary>
        /// 将html转为PDF
        /// </summary>
        /// <param name="html">html文本</param>
        /// <param name="fontPath">完整的字体文件路径</param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public static byte[] ConvertHtmlTextToPdf(string html, string fontPath = "")
        {
            if (string.IsNullOrEmpty(html)) return null;
            try
            {
                MemoryStream outputStream = new MemoryStream();
                byte[] data = Encoding.UTF8.GetBytes(html);
                MemoryStream msInput = new MemoryStream(data);
                Document doc = new Document();
                PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
                PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
                doc.Open();
                //使用XMLWorkerHelper把Html parse到PDF
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                if (!string.IsNullOrEmpty(fontPath))
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory(fontPath));
                }
                else
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);
                }

                PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);
                doc.Close();
                msInput.Close();
                outputStream.Close();
                return outputStream.ToArray();
            }
            catch (Exception ex)
            {
                throw new ApplicationException("转PDF时异常", ex);
            }
        }
        /// <summary>
        /// 字体工厂
        /// </summary>
        public class UnicodeFontFactory : FontFactoryImp
        {
            public UnicodeFontFactory(string fontPath)
            {
                _fontPath = fontPath;
            }
            public string _fontPath { get; set; }

            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
                bool cached)
            {
                BaseFont baseFont = BaseFont.CreateFont(_fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                return new Font(baseFont, size, style, color);
            }
        }
    }
}

 

二、Wkhtmltopdf.NetCore

1、安装组件

 

2、示例

byte[] pdfBytes = _generatePdf.GetPDF(sb.ToString());

 

具体参考各操作系统平台下实现Html to Pdf

posted @ 2023-03-21 16:16  搬砖滴  阅读(92)  评论(1编辑  收藏  举报