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
需要一個類似字節(jié)的對象,而不是'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:
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()