WeasyPrint HTML-to-image conversion: how to adapt image size to content?

那年仲夏 提交于 2020-05-28 08:25:05

问题


I need to convert some HTML to an image in Python and I am using WeasyPrint. I would like the image size to adapt to the content.

When using the following, I get an image which is much larger than content (an A4?):

# !pip install weasyprint
import weasyprint as wsp


img_filepath = 'test.png'
html_source = '''
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Ciao!</title>
    </head>
    <body>
        Hello World!
    </body>
</html>
'''
html = wsp.HTML(string=html_source)
html.write_png(img_filepath)

test.png


I have tried to use CSS's @page size directive to successfully modify the image size:

# !pip install weasyprint
import weasyprint as wsp


img_filepath = 'test2.png'
css = wsp.CSS(string='@page { size: 400px; }')
html_source = '''
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Ciao!</title>
    </head>
    <body>
        Hello World!
    </body>
</html>
'''
html = wsp.HTML(string=html_source)
html.write_png(img_filepath, stylesheets=[css])

test2.png

but I would like the image size to automatically adapt to its content.

Setting @page size to auto seems to resort to the default behavior from earlier.

Any hint?

来源:https://stackoverflow.com/questions/61155743/weasyprint-html-to-image-conversion-how-to-adapt-image-size-to-content

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