如何在 Wkhtmltopdf/wkhtmltoimage 上运行自定义 Javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22963047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run custom Javascript on Wkhtmltopdf/wkhtmltoimage?
提问by aDoN
I want to run a javascript on a website, but when I do it, nothing changes, I get the pdf as if I run no result of the javascript on it, this is an example of what I do:
我想在网站上运行 javascript,但是当我这样做时,没有任何变化,我得到的 pdf 就好像我没有在上面运行 javascript 的结果一样,这是我所做的一个例子:
xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltoimage --run-script "javascript:($(function(){ $("div").hide() ;}))" google.com google.png
I have also scripts without jquery like:
我也有没有 jquery 的脚本,例如:
xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf --run-script "javascript:(function(){ document.write("AHHHHHHHHHHHHHHHHHHHHHHHHHHHHH"); ;})" google.com p2.pdf
But as I said, no effect on the pdf or the png (because I have tried both wkhtmltoimage and wkhtmltopdf).
但正如我所说,对 pdf 或 png 没有影响(因为我已经尝试过 wkhtmltoimage 和 wkhtmltopdf)。
回答by jgillich
Your command uses quotes incorrectly; try this:
您的命令错误地使用了引号;试试这个:
--run-script "javascript:($(function(){ $('div').hide() ;}))"
Also, try increasing the JavaScript delay:
另外,尝试增加 JavaScript 延迟:
--javascript-delay 1000
回答by justd
About the question
关于问题
"do you know any way of generate a .png with less size? cause every png I generate weights 9MB"
“你知道有什么方法可以生成更小的 .png 吗?因为我生成的每个 png 权重为 9MB”
I had the same problem with large PNG files generated with wkhtmltoimage and managed to fix this with adding the flag --quality 0
, that shrunk the image from 3.5MB to just 38KB. Note that PNG is doing lossless compression so the image quality won't change only will be shrunk in size. Be careful when using --quality
flag when you output to jpg format as this can blur the image is you set it too low.
我在使用 wkhtmltoimage 生成的大型 PNG 文件时遇到了同样的问题,并设法通过添加标志来解决此问题,将--quality 0
图像从 3.5MB 缩小到仅 38KB。请注意,PNG 正在进行无损压缩,因此图像质量不会改变,只会缩小尺寸。--quality
当您输出为 jpg 格式时使用标志时要小心,因为如果您将其设置得太低,这会使图像模糊。