[C#] How to convert HTML to PDF in Netcore

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách chuyển đổi mã code HTML sang tập tin PDF file trên NET Core.

[C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform

Mình cũng đã có bài viết về cách chuyển đổi này tuy nhiên nó làm việc trên Netframework.
Nếu bạn nào đang dùng netcore thì thực hiện theo bài viết này nhé.

Đầu tiên, các bạn cài đặt cho mình thư viện DinktoPDF từ nuget:

NuGet\Install-Package DinkToPdf -Version 1.0.8

Khi các bạn thực hiện tạo pdf trên thư viện này nó xảy ra lỗi như sau.

DllNotFoundException: Unable to load DLL 'libwkhtmltox' or one of its dependencies: The specified module could not be found. (0x8007007E)

Bạn cần import thư viện libwkhtmltox.dll từ source code mình về vào chép vào thư mục chạy ứng dụng.

Ở tập tin program.cs: các bạn load dll dynamic vào như code mình bên dưới:

using System.Runtime.InteropServices;

namespace HTMLTOPDFDemo
{
    internal static class Program
    {

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool SetDllDirectory(string lpPathName);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr LoadLibrary(string lpFileName);

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            string dllPath = Path.Combine(Directory.GetCurrentDirectory(), "NativeLibraries");
            if (!SetDllDirectory(dllPath))
            {
                Console.WriteLine($"Failed to set DLL directory: {Marshal.GetLastWin32Error()}");
                return;
            }

            // Load the required native library
            string libraryName = "libwkhtmltox.dll";
            IntPtr libHandle = LoadLibrary(libraryName);
            if (libHandle == IntPtr.Zero)
            {
                Console.WriteLine($"Failed to load library '{libraryName}': {Marshal.GetLastWin32Error()}");
                return;
            }

            Console.WriteLine("Library loaded successfully!");

            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();
            Application.Run(new Form1());
        }
    }
}

Tiếp đến, các bạn tạo file PDFHelper.cs class

using DinkToPdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HTMLTOPDFDemo
{
    public class PDFHelper
    {
        private  readonly SynchronizedConverter _converter;
        public PDFHelper()
        {
            _converter = new SynchronizedConverter(new PdfTools());
        }
        public  string ConvertHtmlToPdf(string htmlContent)
        {
            try
            {
              
                var customSize = new PechkinPaperSize("150", "220");

                var globalSettings = new GlobalSettings
                {
                    PaperSize = customSize,
                    Orientation = DinkToPdf.Orientation.Portrait,
                    DPI = 300,
                    Margins = new MarginSettings { Top = 5, Bottom = 5, Left = 5, Right = 5 }
                };

                var objectSettings = new ObjectSettings
                {
                    PagesCount = true,
                    HtmlContent = htmlContent,
                    // WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "styles.css") }
                    WebSettings = { DefaultEncoding = "utf-8" }
                };

                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects = { objectSettings }
                };

                byte[] pdfBytes = _converter.Convert(pdf);
                string pdfPath = Path.Combine(Application.StartupPath + "\\pdfExport", $"{Guid.NewGuid()}.pdf");
                File.WriteAllBytes(pdfPath, pdfBytes);

                return pdfPath;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error converting HTML to PDF: {ex.Message}");
                return "";
            }
        }
    }
}

form1.cs, các bạn chỉ cần gọi để sử dụng

using DinkToPdf;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO.Packaging;
using System.Windows.Forms;

namespace HTMLTOPDFDemo
{
    public partial class Form1 : Form
    {
        //NuGet\Install-Package DinkToPdf -Version 1.0.8
      
        public Form1()
        {
            InitializeComponent();
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var htmlText = File.ReadAllText("invoice.html");
            var pdfFile = new PDFHelper(). ConvertHtmlToPdf(htmlText);
            Process.Start(new ProcessStartInfo(pdfFile) { UseShellExecute = true });
           
        }
       
    }
}

Chúc các bạn thành công với tiện ích trên.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

PASSWORD UNZIP: HUNG.PRO.VN
Chúc Mọi Người Thành Công Với Thủ Thuật Trên.
Nếu mọi người có vướng mắc gì mình chia sẽ trên trang có thể gửi liên hê cho mình tại đây nhé.
Cảm ơn mọi người đã quan tâm.

No comments:

All Right Reserved © 2015 By Hung Pro VN