我有很多HTML文件,我想将它们保存为本地的PDF文件
所以我尝试使用weasyprint来进行转换,但是无法成功
有人可以帮我写代码吗?
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
我有HTML文件在本地,并且也想将PDF文件保存在本地
我已经实现了答案
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))
并且出现了以下错误
需要一个类似字节的对象,而不是'NoneType'
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您的HTML文件是一个字符串,您应该使用
HTML(string=html_string).write_pdf()方法。但是,如果它是您本地目录中的一个文件,您应该使用
HTML(filename=html_file_path).write_pdf()方法。代码如下:
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()