Các bạn có thể sử dụng thư viện: CefSharp or Puppetteer, hay một trình duyệt webkit để view nội dung tập tin và xuất thành file PDF.
Ở bài viết này, mình hướng dẫn các bạn cách dùng trình duyệt Chrome để để save html sang PDF chạy ở chế độ headless.
Source code C#:
var url = "https://hung.pro.vn/";
var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
//var chromePath = @"C:\Program Files\Google\Chrome\Application\chrome.exe"; (hoặc nếu bạn sử dụng chạy phiên bản 64bit)
var output = Path.Combine(Environment.CurrentDirectory, "printout.pdf");
using (var p = new Process())
{
p.StartInfo.FileName = chromePath;
p.StartInfo.Arguments = $"--headless --disable-gpu --print-to-pdf={output} {url}";
p.Start();
p.WaitForExit();
}
Chỉ với đoạn code ngắn gọn trên và không cần sử dụng thư viện nào khác, các bạn có thể export thành file PDF một cách nhanh chóng.
![[C#] Convert HTML to PDF using Chrome Browser [C#] Convert HTML to PDF using Chrome Browser](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0BFFLJbONh4OMOVF91fcm3ni9sIHFrPmpVdS-URYai8-T7j4G0S6s7X9giEY9pnVWVleWHdDwuq5wRjq2Oi-iMHsm0AEYBado4I0WQsIfNucjxxY-jl4ww8z1aUtRvgE-neu021TmSRvQRC9sog0WtuKAcgu04s9Opbq1uCFHafJc4aSn7F_bm-5Y34g7/w640-h407/convert_html_to_pdf.webp)
Post a Comment
Post a Comment