在Python中将HTML字符串转换为图像

2024-06-01 20:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python将下面的HTML转换成PNG图像

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

当然,这个HTML就是一个例子

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

如果这可以在Graphicsmagick或Imagemagick中完成,那么它将是完美的


Tags: 模块text图像pdfpnghtml解决方案内置
2条回答

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

要扩展vartec的答案,还要解释如何使用它

安装webkit2png
最简单的方法可能是简单地克隆github repo并运行安装程序

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服务器。在cygwin上,这可以通过在第二个终端中运行startxwin来完成。确保首先通过cygwin安装程序安装它

相关问题 更多 >