13

I am trying to use Headless feature of the Chrome to convert a html to pdf. However, i am not getting output at all. Console doesn't show any error as well. I am running below commands in my windows m/c.

chrome --headless --disable-gpu --print-to-pdf

I tried all the various options. Nothing is being generated. I am having chrome version 60

user2580925
  • 751
  • 2
  • 7
  • 14

7 Answers7

14

Command Line --print-to-pdf

By default, --print-to-pdf attempts to create a PDF in the User Directory. By default, that user directory is where the actual chrome binary is stored, which is the specific version folder for the version you're running - for example, "C:\Program Files (x86)\Google\Chrome\Application\61.0.3163.100". And, by default... Chrome is not allowed to write to this folder. You can watch it try, and fail, by adding --enable-logging to your command.

So unfortunately, by default, this command fails.*

You can solve this by either providing a path in the argument, where Chrome can write - like

--print-to-pdf="C:\Users\Jane\test.pdf"

Or, you can change the User Directory:

--user-data-dir="C:\Users\Jane"

One reason you might prefer to change the User Directory is if you want the PDF to automatically receive its name from the webpage; Chrome looks at the title tag and then dumps it like <title>My Page</title> => My-Page.pdf

*I think this default behavior is super confusing, and should be filed as a bug against Chrome. However, apparently part of the Chrome team is outright opposed to the mere existence of this command line option, and instead believe it would be better to force everyone using it to get a node.js build going with Puppeteer and the flag removed outright.

Limitations of Command Line on Windows

Invoking chrome in this way will work fine for example in a local dev env on IIS Express with Visual Studio, but it will fail, even in headless mode, on a server running IIS, because IIS users are not given interactive/desktop permissions, and the way chrome grabs this PDF actually requires interactive/desktop permissions. There are complicated ways to provide those permissions, but anyplace you read up on how begins with DON'T PROVIDE INTERACTIVE/DESKTOP PERMISSIONS. Further, the above risk of Chrome one day getting rid of the command-line makes working even harder to get it working an iffy proposition.

Alternatives to chrome command line

wkhtmltopdf

Behind the scenes Chrome simply uses wkhtmltopdf. I haven't tried it but it's likely this will get the job done. The one minor risk is that when producing PDFs in Chrome, testing is obvious: View the page in Chrome. Open Print Preview if you're nervous. In wkhtmltopdf, it's actually a different build of Chromium, and that may produce rendering differences. Maybe.

Selenium

Another alternative is to get ahead of the group looking to get rid of --print-to-pdf and use the browser dev API (via Selenium) as they prefer.**

private static void pdfSeleniumImpl(string url, string pdfPath)
{
    var options = new OpenQA.Selenium.Chrome.ChromeOptions();
    options.AddArgument("headless");

    using (var chrome = new OpenQA.Selenium.Chrome.ChromeDriver(options))
    {
        chrome.Url = url;

        var printToPdfOpts = new Dictionary<string, object>();
        var resultDict = (Dictionary<string, object>)
            chrome.ExecuteChromeCommandWithResult(
                "Page.printToPDF", printToPdfOpts);
        dynamic result = new DDict(resultDict);
        string data = result.data;
        var pdfFile = Convert.FromBase64String(data);
        System.IO.File.WriteAllBytes(pdfPath, pdfFile);
    }
}

The DDict above is the GracefulDynamicDictionary from another of my answers.

https://www.nuget.org/packages/GracefulDynamicDictionary/

https://github.com/b9chris/GracefulDynamicDictionary

https://stackoverflow.com/a/24192518/176877

Ideally this would be async, since all the calls to Selenium are actually network commands, and writing that file could take a lot of Disk IO. The data returned from Chrome is actually a Stream as well. However Selenium's conventionally used library does not use async at all unfortunately, so it would take upgrading that library or identifying a solid async Selenium library for .Net to really do this right.

https://github.com/puppeteer/puppeteer/blob/master/lib/Page.js#L1007

https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

**The Page.pdf chrome Dev API command is also deprecated, so if that contingent gets their way, neither the command line nor the Dev API will work. That said it looks like those lobbying to wreck it gave up 2 years ago.

Community
  • 1
  • 1
Chris Moschini
  • 35,226
  • 19
  • 156
  • 186
  • Don't understand why full path is required for files in current directory - eg: `C:\Users\User\Documents\XstReader>"C:\Program Files (x86)\Google\Chrome\Application\chrome" --headless --disable-gpu --print-to-pdf=C:\Users\User\Documents\XstReader\DemoEmail.pdf --no-margins "C:\Users\User\Documents\XstReader\Demo Email.html"` – flywire Dec 04 '19 at 04:45
  • Because Chrome ignores the current directory, instead using the user data dir. – Chris Moschini Dec 05 '19 at 17:22
  • this is a great answer, should get at least 100 votes. Especially the Selenium Function. Thanks sm @ChrisMoschini – Jeanno Apr 10 '20 at 20:56
  • 4
    "*Behind the scenes Chrome simply uses wkhtmltopdf.*" - citation needed. – Bergi Sep 07 '20 at 17:03
  • 1
    Many thanks for the Selenium tip! Please note that the "headless" option is important, as otherwise by default the necessary extension will be disabled in Chrome, causing a "PrintToPDF is not implemented" error. (Alternatively, it can presumably be explicitly enabled for non-headless mode, but I have not tried that.) – Otto G Sep 19 '20 at 13:48
7

This is working:

chrome --headless --disable-gpu --print-to-pdf=file1.pdf https://www.google.co.in/

creates file in the folder: C:\Program Files (x86)\Google\Chrome\Application\61.0.3163.100.

0xdb
  • 3,364
  • 1
  • 18
  • 35
SURAJ
  • 97
  • 6
3

I was missing "=" after print-to-pdf command.

The correct command is:

chrome --headless --disable-gpu --print-to-pdf="C:/temp/name.pdf" https://www.google.com/

Now it is working.

Moshe Slavin
  • 4,939
  • 5
  • 21
  • 36
user2580925
  • 751
  • 2
  • 7
  • 14
3

Do not forget to open your terminal/cmd with admin rights :) Otherwise it will just not save the file at all.

Dobromir Hristov
  • 1,154
  • 8
  • 16
2

extending the brilliantly simple answer by suraj, I created a small function that is in my sourced path so it works like a CLI tool:

function webtopdf(){
    chromium-browser --headless --disable-gpu --print-to-pdf=$2 $1
}

so a quick

webtopdf https://goo.com/some-article some-article.pdf

does the job for me now

pascalwhoop
  • 2,794
  • 3
  • 24
  • 38
1

This worked for me in windows

start chrome --headless --disable-gpu --print-to-pdf=C:\Users\username\pdfs\chrome.pdf --no-margins https://www.google.com

vipin cp
  • 3,263
  • 3
  • 30
  • 49
  • 1
    You can use in Powershell (and in GitBash) `--print-to-pdf="$(pwd)\output.pdf"` to print in the current folder. For me `--no-margins` have no effect. – Kpym Jan 25 '20 at 11:36
-2

Currently, this is only available for Linux and Mac OS.