Convert html file to pdf using weasyprint

362 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:

        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 the html file in my local and also want to save the pdf file in local

I have implemented the answer

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 best solutions below

2
Ahmad Abdelbaset On

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

But if it's a file in your local directory, you should use the HTML(filename=html_file_path).write_pdf() method instead.

The code will be:

from weasyprint import HTML

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

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

pdf_generate()