Chuyển đổi HTML sang PDF

iTextSharp

Cài đặt thành phần

Mã nguồn được bọc

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

namespace CommonCore.Helpers
{
    public class HtmlToPdfConverter
    {
        /// <summary>
        /// Tạo file PDF
        /// </summary>
        /// <param name="html">Nội dung HTML</param>
        /// <param name="pdfSavePath">Đường dẫn lưu file PDF, ví dụ: @"D:\pdffile"</param>
        /// <param name="fileName">Tên file PDF, ví dụ: @"D:\pdffile\sample.pdf"</param>
        /// <param name="fontPath">Đường dẫn đến file font, nếu có</param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public static bool CreatePDF(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[] pdfData = ConvertHtmlToPdfBytes(html, fontPath);
                    fs.Write(pdfData, 0, pdfData.Length);
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Lỗi khi lưu PDF vào đĩa", ex);
            }
        }

        /// <summary>
        /// Chuyển đổi HTML sang PDF
        /// </summary>
        /// <param name="html">Nội dung HTML</param>
        /// <param name="fontPath">Đường dẫn đến file font, nếu có</param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public static byte[] ConvertHtmlToPdfBytes(string html, string fontPath = "")
        {
            if (string.IsNullOrEmpty(html)) return null;
            try
            {
                MemoryStream output = new MemoryStream();
                byte[] data = Encoding.UTF8.GetBytes(html);
                MemoryStream input = new MemoryStream(data);
                Document document = new Document();
                PdfWriter writer = PdfWriter.GetInstance(document, output);
                PdfDestination destination = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f);
                document.Open();
                
                // Sử dụng XMLWorkerHelper để chuyển đổi HTML sang PDF
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                if (!string.IsNullOrEmpty(fontPath))
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, input, null, Encoding.UTF8, new CustomFontFactory(fontPath));
                }
                else
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, input, null, Encoding.UTF8);
                }

                PdfAction action = PdfAction.GotoLocalPage(1, destination, writer);
                writer.SetOpenAction(action);
                document.Close();
                input.Close();
                output.Close();
                return output.ToArray();
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Lỗi khi chuyển đổi HTML sang PDF", ex);
            }
        }

        /// <summary>
        /// Nhà máy font tùy chỉnh
        /// </summary>
        public class CustomFontFactory : FontFactoryImp
        {
            private readonly string _fontPath;

            public CustomFontFactory(string fontPath)
            {
                _fontPath = fontPath;
            }

            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

Cài đặt thành phần

Ví dụ

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

Cụ thể, tham khảo cách thực hiện chuyển đổi HTML sang PDF trên các nền tảng hệ điều hành khác nhau.

Thẻ: iTextSharp Wkhtmltopdf HTML to PDF C#

Đăng vào ngày 14 tháng 6 lúc 03:55