Headless Chrome to print pdf

谁说胖子不能爱 提交于 2019-12-08 02:53:42

问题


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


回答1:


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.




回答2:


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




回答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.




回答4:


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




回答5:


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.




回答6:


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




回答7:


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



来源:https://stackoverflow.com/questions/46074235/headless-chrome-to-print-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!