Convert HTML files to PDF using WeasyPrint
P粉729198207
P粉729198207 2023-09-11 14:54:49
0
1
535

I have a lot of HTML files and I want to save them as local PDF files

So I tried to use weasyprint to convert, but failed

Can someone help me write the code?

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

I have HTML files locally and want to save PDF files locally too

I have implemented the answer

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))

And the following error occurred

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

P粉729198207
P粉729198207

reply all(1)
P粉384679266

If your HTML file is a string, you should use the HTML(string=html_string).write_pdf() method.

However, if it is a file in your local directory, you should use the HTML(filename=html_file_path).write_pdf() method.

code show as below:

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()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!