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