Notification texts go here Contact Us Buy Now!

[C#] Convert HTML to PDF using Chrome Browser

[C#] Convert HTML to PDF using Chrome Browser
Khi tập tin HTML của bạn bao gồm: HTML, CSS Javascript, khi render xong và các bạn muốn xuất dữ liệu sang tập tin file PDF.

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.
[C#] Convert HTML to PDF using Chrome Browser

Ở 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.

Chúc các bạn thành công với thủ thuật đơn giản này.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.
NextGen Digital Welcome to WhatsApp chat
Howdy! How can we help you today?
Type here...