英文:
Render HTML and save as PDF with Golang
问题
我正在尝试将本地的HTML文件转换为PDF。目前,我通过终端执行上述命令来生成PDF:google-chrome --headless --print-to-pdf="report.pdf" template.html。这个方法可以正常工作,但是在运行设备上没有安装Chrome的情况下,它将无法工作。我不想使用WKHTMLTOPDF或任何其他已安装的浏览器。但是我可以使用WebKit。是否有其他方法可以使用Golang来实现这个目标呢?
提前感谢!
英文:
I'm trying to convert a local HTML file to a PDF. For that currently,
google-chrome --headless --print-to-pdf="report.pdf" template.html
I'm executing the above-mentioned command via the terminal to generate PDF. It's working fine but without chrome installed on the running device, it won't work. I don't want to use WKHTMLTOPDF or any other installed browsers either. But I can use a webkit. Are there any other ways to do this using Golang?
Thanks in advance!
答案1
得分: 1
你需要在webkit中寻找类似于chrome的--print-to-pdf的功能。如果我没记错的话,QT版本曾经有类似的功能,而WKHTMLTOPDF只是它的一个薄薄的C++命令行包装器。但是如果你只是想在Go上做同样的事情,为什么不使用已经存在的工具呢?
如果你想将HTML模板转换为PDF,你几乎必须使用一个浏览器,除非你想在Go上构建一个完整的CSS + HTML渲染引擎来生成PDF。有一个名为WeasyPrint的Python项目可以做到这一点。
Chromedp提供了很多选项来渲染PDF,你可以在这里看到,并且你可以构建一个无头版本的Chromium或使用一个已经构建好的Docker镜像。
如果你绝对不想运行浏览器,你最好的选择可能是直接在Go上使用一个PDF处理器(例如unipdf)生成PDF模板,而不是从HTML生成。
英文:
You have to look for anything like the --print-to-pdf provided by chrome on your webkit. If I recall correctly QT version used to have something like that and WKHTMLTOPDF is just a thin C++ CLI wrapper for it. But then if you would just do the same on Go, so why not use the tool that is already there?
If you want to convert a html template to PDF you pretty much have use a browser, there is no way around it, unless you want to build an entire CSS + HTML render engine on Go just to generate your PDFs. There is a python project that does exactly that.
Chromedp gives you a lot of options to render your pdf as you can see here and you can build a headless version of chromium or use an already built docker image.
If you absolutely won't run a browser your probably best option is to generate your PDFs template straight on Go using a PDF processor such as instead of generating them from HTML.
答案2
得分: 0
你可以使用Golang-HTML-TO-PDF-Converter
:
英文:
You can use Golang-HTML-TO-PDF-Converter
:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论