将HTML文件转换为PDF,使用WeasyPrint实现
P粉729198207
P粉729198207 2023-09-11 14:54:49
0
1
508

我有很多HTML文件,我想将它们保存为本地的PDF文件

所以我尝试使用weasyprint来进行转换,但是无法成功

有人可以帮我写代码吗?

def pdf_generate():
    try:

        pdf_file = HTML(string='56129.html').write_pdf()
        with open("my_pdf_file.pdf", 'wb') as f:
            f.write(pdf_file)

    except Exception as e:
        print(str(e))
        return None

我有HTML文件在本地,并且也想将PDF文件保存在本地

我已经实现了答案

def pdf_generate():
    try:
        #将'56129.html'替换为你的HTML文件的路径
        html_file_path = 'farm_management/scripts/56129.html'

        html = HTML(filename=html_file_path)

        pdf_file_path = 'my_pdf_file.pdf'

        pdf_file = html.write_pdf(pdf_file_path)
        with open("my_pdf_file.pdf", 'wb') as f:
            f.write(pdf_file)

        print(f'PDF文件已写入至:{pdf_file_path}')

    except Exception as e:
        print(str(e))

并且出现了以下错误

需要一个类似字节的对象,而不是'NoneType'

P粉729198207
P粉729198207

全部回复(1)
P粉384679266

如果您的HTML文件是一个字符串,您应该使用HTML(string=html_string).write_pdf()方法。

但是,如果它是您本地目录中的一个文件,您应该使用HTML(filename=html_file_path).write_pdf()方法。

代码如下:

from weasyprint import HTML

def pdf_generate():
    try:
        # 将'56129.html'替换为您的HTML文件的路径
        html_file_path = '56129.html'

        html = HTML(filename=html_file_path)

        pdf_file_path = 'my_pdf_file.pdf'

        html.write_pdf(pdf_file_path)

        print(f'PDF文件已写入:{pdf_file_path}')

    except Exception as e:
        print(str(e))

pdf_generate()
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!