19

我想在 Python 中将以下 HTML 转换为 PNG 图像。

<html>
    <b>Bold text</b>
</html>

当然,这个 HTML 只是一个例子。

我试过'pisa',但它将html转换为PDF,而不是图像。我可以将 HTML 转换为 PDF,然后将 PDF 转换为 PNG,但我想知道是否有任何直接的解决方案(即 HTML 到 PNG)。任何内置或外部模块都可以很好地工作。

如果这可以在 Graphicsmagick 或 Imagemagick 中完成,那就完美了。

4

2 回答 2

12

webkit2.png 原始版本仅适用于 OSX,但幸运的是有一个跨平台的 fork: https ://github.com/AdamN/python-webkit2png

于 2011-04-12T11:00:45.557 回答
8

要扩展 vartec 的答案以解释如何使用它......

安装webkit2png
最简单的方法可能是简单地克隆 github 存储库并运行设置。

mkdir python-webkit2png
git clone https://github.com/adamn/python-webkit2png.git python-webkit2png
python setup.py install

这需要已经安装了 python 和 git。对于 cygwin,这会将 webkit2png 作为命令添加到路径中。我还没有为其他终端/操作系统测试过这个。

运行它
假设您的网站在当前目录中。(我有一个使用 css 样式表的 html 文件 - 但无需考虑 css 文件。)

webkit2png something.html -o something.png

选项
webkit2png -h告诉我们:

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -x WIDTH HEIGHT, --xvfb=WIDTH HEIGHT
                        Start an 'xvfb' instance with the given desktop size.
  -g WIDTH HEIGHT, --geometry=WIDTH HEIGHT
                        Geometry of the virtual browser window (0 means
                        'autodetect') [default: (0, 0)].
  -o FILE, --output=FILE
                        Write output to FILE instead of STDOUT.
  -f FORMAT, --format=FORMAT
                        Output image format [default: png]
  --scale=WIDTH HEIGHT  Scale the image to this size
  --aspect-ratio=RATIO  One of 'ignore', 'keep', 'crop' or 'expand' [default:
                        none]
  -F FEATURE, --feature=FEATURE
                        Enable additional Webkit features ('javascript',
                        'plugins')
  -c COOKIE, --cookie=COOKIE
                        Add this cookie. Use multiple times for more cookies.
                        Specification is value of a Set-Cookie HTTP response
                        header.
  -w SECONDS, --wait=SECONDS
                        Time to wait after loading before the screenshot is
                        taken [default: 0]
  -t SECONDS, --timeout=SECONDS
                        Time before the request will be canceled [default: 0]
  -W, --window          Grab whole window instead of frame (may be required
                        for plugins)
  -T, --transparent     Render output on a transparent background (Be sure to
                        have a transparent background defined in the html)
  --style=STYLE         Change the Qt look and feel to STYLE (e.G. 'windows').
  --encoded-url         Treat URL as url-encoded
  -d DISPLAY, --display=DISPLAY
                        Connect to X server at DISPLAY.
  --debug               Show debugging information.
  --log=LOGFILE         Select the log output file

值得注意的选项是宽度和高度的设置。

使用 cygwin 进行故障排除
,我遇到了 webkit2png: cannot connect to X server :0.0. 为了解决这个问题(我已经执行过export DISPLAY=0.0),我必须启动一个 X-Server。在 cygwin 上,这可以通过startxwin在第二个终端中运行来完成。确保首先通过 cygwin 安装程序安装它。

于 2018-01-31T07:48:10.000 回答