nor*_*ok2 5 html css python image weasyprint
我需要在 Python 中将一些 HTML 转换为图像,并且我正在使用WeasyPrint。我希望图像大小能够适应内容。
使用以下命令时,我得到的图像比内容大得多(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)
Run Code Online (Sandbox Code Playgroud)
我尝试使用CSS的@page 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])
Run Code Online (Sandbox Code Playgroud)
但我希望图像大小能够自动适应其内容。
设置@page size为auto似乎诉诸于之前的默认行为。
有什么提示吗?
| 归档时间: |
|
| 查看次数: |
2210 次 |
| 最近记录: |