BomKhung.Com Đã Quay Trở Lại
Hoạt Động Dưới Tên Miền Hung.Pro.VN
00 Days
00 Hours
00 Minutes
00 Seconds
Hiện website đang cập nhật nội dung bài viết, nếu có lỗi gì mọi người có thể thông báo cho mình Tại đây!

[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

Đăng nhận xét

Đồng ý sữ dụng cookie
Chúng tôi sử dụng cookie trên trang web này để phân tích lưu lượng truy cập, ghi nhớ tùy chọn của bạn và tối ưu hóa trải nghiệm của bạn.
Xem thêm
Oops!
Có vẻ như kết nối internet của bạn có vấn đề. Vui lòng kết nối lại và duyệt web.
AdBlock Detected!
Chúng tôi phát hiện bạn đang sử dụng plugin chặn quảng cáo trong trình duyệt của mình.
Doanh thu chúng tôi kiếm được từ quảng cáo được sử dụng để quản lý trang web này, chúng tôi yêu cầu bạn đưa trang web của chúng tôi vào danh sách trắng trong plugin chặn quảng cáo của bạn.
Site is Blocked
Sorry! This site is not available in your country.
Kỹ thuật số thế hệ tiếp theo Chào mừng bạn đến với trò chuyện WhatsApp
Xin chào! Chúng tôi có thể giúp gì cho bạn hôm nay?
Nhập vào đây...