- [DEVEXPRESS] Chia sẻ code các tạo report in nhiều hóa đơn trên XtraReport C#
- [POWER AUTOMATE] Hướng dẫn gởi tin nhắn zalo từ file Excel - No code
- [C#] Chia sẻ code lock và unlock user trong domain Window
- [SOFTWARE] Giới thiệu bộ phần mềm tính Kết Cấu Thép HatteSale, Mộng Đơn, Dầm, Sàn, Móng Cọc, Vách, Xà Gồ, Tính Tải Trọng
- [DEVEXPRESS] Vẽ Biểu Đồ Stock Chứng Khoán - Công Cụ Thiết Yếu Cho Nhà Đầu Tư trên Winform
- [C#] Hướng dẫn bảo mật ứng dụng 2FA (Multi-factor Authentication) trên Winform
- [C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform
- [C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform
- Hướng dẫn khóa file bằng nhiều process id, không cho xóa tập tin
- Hướng dẫn cách tạo Product Id cho ứng dụng phần mềm XXXXX-XXXXX-XXXXX-XXXXX
- [SQLSERVER] Hướng dẫn tạo script sql từ ứng dụng Sqlserver management Studio
- [C#] Hướng dẫn sử dụng thư viện AutoITx lấy id và password Ultraviewer trên winform
- [VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
- [C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
- [DEVEXPRESS] Chia sẻ source code tạo báo cáo report in tem nhãn label trên C# winform
- [DEVEXPRESS] Hướng dẫn vẽ biểu đồ Bar Chart trên Winform
- [C#] Tạo form đăng nhập và đăng ký với hiệu ứng Sliding Animation Effect
- [C#] Hướng dẫn tạo thanh toán đơn hàng qua mã vạch VietQR sử dụng API PayOS hoàn toàn miễn phí
- [C#] Hướng dẫn ghi log ra RichTextBox giống Console trên Winform sử dụng thư viện Serilog
- [C#] Hướng dẫn cách tạo mã QR Code trên file Excel
[C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform
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#] How to convert HTML to PDF in Netcore
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 });
}
}
}
Thanks for watching!