python生成pdf
pdfkit
- 優缺點
功能:
1.wkhtmltopdf主要用於HTML生成PDF。
2.pdfkit是基於wkhtmltopdf的python封裝,支持URL,本地文件,文本內容到PDF的轉換,其最終還是調用wkhtmltopdf命令。是目前接觸到的python生成pdf效果較好的。
優點:
1.wkhtmltopdf:利用webkit內核將HTML轉為PDF
webkit是一個高效、開源的瀏覽器內核,包括Chrome和Safari在內的瀏覽器都使用了這個內核。Chrome打印當前網頁的功能,其中有一個選項就是直接“保存為 PDF”。
2.wkhtmltopdf使用webkit內核的PDF渲染引擎來將HTML頁面轉換為PDF。高保真,轉換質量很好,且使用非常簡單。
缺點:
1.對使用echarts,highcharts這樣的js代碼生成的圖標無法轉換為pdf(因為它的功能主要是將html轉換為pdf,而不是將js轉換為pdf)。對於純靜態頁面的轉換效果還是不錯的。
- 使用方法
安裝依賴wkhtmltopdf
brew cask install wkhtmltopdf
安裝pdfkit
pip install pdfkit
使用
import pdfkit
# url頁面轉化為pdf
pdfkit.from_url('http://google.com', 'out.pdf')
# 文件轉化為pdf
pdfkit.from_file('test.html', 'out.pdf')
# 打開的文件轉化為pdf
with open('file.html') as f:
pdfkit.from_file(f, 'out.pdf')
# 文本內容轉化為pdf
pdfkit.from_string('Hello!', 'out.pdf')
weasyprint
reportlab
本文實例演示了Python生成pdf文件的方法,是比較實用的功能,主要包含2個文件。具體實現方法如下:
pdf.py文件如下:
#!/usr/bin/python
from reportlab.pdfgen import canvas
def hello():
c = canvas.Canvas("helloworld.pdf")
c.drawString(100,100,"Hello,World")
c.showPage()
c.save()
hello()
diskreport.py文件如下:
#!/usr/bin/env python
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
def disk_report():
p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE)
# print p.stdout.readlines()
return p.stdout.readlines()
def create_pdf(input, output="disk_report.pdf"):
now = datetime.datetime.today()
date = now.strftime("%h %d %Y %H:%M:%S")
c = canvas.Canvas(output)
textobject = c.beginText()
textobject.setTextOrigin(inch, 11*inch)
textobject.textLines('''Disk Capcity Report: %s''' %date)
for line in input:
textobject.textLine(line.strip())
c.drawText(textobject)
c.showPage()
c.save()
report = disk_report()
create_pdf(report)