Convert html file to pdf using weasyprint python

697 views Asked by At

I have a lot of HTML file which I want to save as a pdf files in my local

So I am trying weasyprint to convert it but could not do it

can any help me with the code?

def pdf_generate():
    try:
        #Replace '56129.html' with the path to your HTML file
        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 file has been written to: {pdf_file_path}')

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

and getting this error


a bytes-like object is required, not 'NoneType'

1

There are 1 answers

0
Martynas Žiemys On

You have to at least have a look at the documentation

import weasyprint

html = weasyprint.HTML("C:\\test\\file.html")
html.write_pdf(target="C:\\test\\file.pdf")