Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python WeasyPrint HTML到图像转换:如何使图像大小适应内容?_Python_Html_Css_Image_Weasyprint - Fatal编程技术网

Python WeasyPrint HTML到图像转换:如何使图像大小适应内容?

Python WeasyPrint HTML到图像转换:如何使图像大小适应内容?,python,html,css,image,weasyprint,Python,Html,Css,Image,Weasyprint,我需要将一些HTML转换成Python中的图像,我正在使用。 我想图像大小适应的内容 使用以下内容时,我得到的图像比内容(A4?)大得多: 但我希望图像大小能够自动适应其内容 将@page size设置为auto似乎采用了先前的默认行为 有什么提示吗?相比之下,wkhtml2pdf似乎有一个选项可以根据内容调整图像大小。 # !pip install weasyprint import weasyprint as wsp img_filepath = 'test.png' html_sou

我需要将一些HTML转换成Python中的图像,我正在使用。 我想图像大小适应的内容

使用以下内容时,我得到的图像比内容(A4?)大得多:

但我希望图像大小能够自动适应其内容

@page size
设置为
auto
似乎采用了先前的默认行为


有什么提示吗?

相比之下,wkhtml2pdf似乎有一个选项可以根据内容调整图像大小。
# !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)
# !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])