[英]Convert html to pdf using Python/Flask
我想使用 Python + Flask 從 html 生成 pdf 文件。為此,我使用 xhtml2pdf。 這是我的代碼:
def main():
pdf = StringIO()
pdf = create_pdf(render_template('cvTemplate.html', user=user))
pdf_out = pdf.getvalue()
response = make_response(pdf_out)
return response
def create_pdf(pdf_data):
pdf = StringIO()
pisa.CreatePDF(StringIO(pdf_data.encode('utf-8')), pdf)
return pdf
在此代碼文件中是動態生成的。 但是,xhtml2pdf 不支持 CSS 中的許多 styles。因為正確標記頁面這個大問題。 我找到了另一種工具(wkhtmltopdf):但是當我寫下類似的東西時:
pdf = StringIO()
data = render_template('cvTemplate1.html', user=user)
WKhtmlToPdf(data.encode('utf-8'), pdf)
return pdf
引發錯誤:
AttributeError: 'cStringIO.StringO' object has no attribute 'rfind'
我的問題是如何在 Flask 中使用 wkhtmltopdf(動態生成文件)將 html 轉換為 pdf?
預先感謝您的回答。
頁面需要渲染,您可以使用pdfkit:
https://pypi.python.org/pypi/pdfkit
https://github.com/JazzCore/python-pdfkit
文檔中的示例。
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf') # Is your requirement?
您是否嘗試過使用WeasyPrint的 Flask- WeasyPrint ? 他們的網站上有很好的例子,所以我不在這里復制它們。
第1步:下載庫pdfkit
$ pip install pdfkit
第2步:下載wkhtmltopdf
對於Ubuntu / Debian:
sudo apt-get install wkhtmltopdf
對於Windows:
(a)下載鏈接: WKHTMLTOPDF
(b)設置:PATH變量設置環境變量中的二進制文件夾。
Step3:下載Python代碼:
(i)已保存的HTML頁面
import pdfkit
pdfkit.from_file('test.html', 'out.pdf')
(ii)通過網站URL轉換
import pdfkit
pdfkit.from_url('https://www.google.co.in/','shaurya.pdf')
(iii)以PDF格式存儲文本
import pdfkit
pdfkit.from_string('Shaurya Stackoverflow','SOF.pdf')
不確定這是否會幫助任何人,但我的問題是將 Bootstrap5 元素捕獲為 pdf。 pdfkit 沒有這樣做,這是使用 html2image 和 PIL 在 Windows 上解決的方法
from html2image import Html2Image
from PIL import Image
try:
hti.screenshot(html_file=C:\yourfilepath\file.html, save_as="test.png")
finally:
image1 = Image.open(r'C:\yourfilepath\test.png')
im1 = image1.convert('RGB')
im1.save(r'C:\yourfilepath\newpdf.pdf')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.