问题
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