Home > Software engineering >  Chrome Headless PrintToPDF with HTML String or File?
Chrome Headless PrintToPDF with HTML String or File?

Time:05-01

I'm working on a Unity3D based application and need to generate PDFs from HTML code. I tried other libraries but they're either super slow, outdated, or crazy expensive for my purposes. Because of that, I'm considering using Chrome's PrintToPDF feature which is built right in.

For testing, the following code works to generate a PDF of Google's homepage (or any site), but I need to convert an HTML string to a PDF.

        System.Diagnostics.Process process = new System.Diagnostics.Process();
        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        process.StartInfo.FileName = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

        string arguments = @"--headless --print-to-pdf=""C:\Users\userName\desktop\myReport.pdf"" https://google.com";
        process.StartInfo.Arguments = arguments;
        process.Start();

Is it possible to input either a string with the HTML code or a locally-stored standalone HTML file to convert to PDF using this method?

Thanks!

CodePudding user response:

After much testing, I see that I can pass in the path to an HTML file where it accepts a web URL. As far as I can find this isn't documented anywhere, but it does work as long as the path is formatted correctly. This is only tested on Windows (11), but I believe it works on MacOS as well, as long as all paths are correct.

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

string arguments = @"--headless --disable-gpu --print-to-pdf=""C:\path\to\outputPDFFile.pdf"" ""C:\path\to\sourceHTMLFile.html""";
process.StartInfo.Arguments = arguments;
process.Start();

In order for this to work, the --headless flag needs to be present otherwise it will just open the file in your browser.

Other output options can be added with other arguments. See here for examples.

  • Related