如何將Python字符串生成PDF
該問題的解決思路還是利用將Python字符串嵌入到HTML代碼中解決,注意換行需要用 <br> 標籤,示例代碼如下:
import pdfkit
# PDF中包含的文字
content = '這是一個測試文件。' + '<br>' + 'Hello from Python!'
html = '<html><head><meta charset="UTF-8"></head>' \
'<body><div align="center"><p>%s</p></div></body></html>'%content
# 轉換為PDF
pdfkit.from_string(html, './test.pdf')
輸出的結果如下:
Loading pages (1/6) Counting pages (2/6) Resolving links (4/6) Loading headers and footers (5/6) Printing pages (6/6) Done
生成的test.pdf如下:
如何生成PDF中的表格
接下來我們考慮如何將csv文件轉換為PDF中的表格,思路還是利用HTML代碼。示例的iris.csv文件(部分)如下:
將csv文件轉換為PDF中的表格的Python代碼如下:
import pdfkit
# 讀取csv文件
with open('iris.csv', 'r') as f:
lines = [_.strip() for _ in f.readlines()]
# 轉化為html中的表格樣式
td_width = 100
content = '<table width="%s" border="1" cellspacing="0px" style="border-collapse:collapse">' % (td_width*len(lines[0].split(',')))
for i in range(len(lines)):
tr = '<tr>'+''.join(['<td width="%d">%s</td>'%(td_width, _) for _ in lines[i].split(',')])+'</tr>'
content += tr
content += '</table>'
html = '<html><head><meta charset="UTF-8"></head>' \
'<body><div align="center">%s</div></body></html>' % content
# 轉換為PDF
pdfkit.from_string(html, './iris.pdf')
生成的PDF文件為iris.pdf,部分內容如下:
解決PDF生成速度慢的問題
用pdfkit生成PDF文件雖然方便,但有一個比較大的缺點,那就是生成PDF的速度比較慢,這裡我們可以做個簡單的測試,比如生成100份PDF文件,裡面的文字為“這是第*份測試文件!”。Python代碼如下:
import pdfkit
import time
start_time = time.time()
for i in range(100):
content = '這是第%d份測試文件!'%(i+1)
html = '<html><head><meta charset="UTF-8"></head>' \
'<body><div align="center">%s</div></body></html>' % content
# 轉換為PDF
pdfkit.from_string(html, './test/%s.pdf'%(i+1))
end_time = time.time()
print('一共耗時:%s 秒.' %(end_time-start_time))
在這個程序中,生成100份PDF文件一共耗時約192秒。輸出結果如下:
......
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
一共耗時:191.9226369857788 秒.
如果想要加快生成的速度,我們可以使用多線程來實現,主要使用concurrent.futures模塊,完整的Python代碼如下:
import pdfkit
import time
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
start_time = time.time()
# 函數: 生成PDF
def convert_2_pdf(i):
content = '這是第%d份測試文件!'%(i+1)
html = '<html><head><meta charset="UTF-8"></head>' \
'<body><div align="center">%s</div></body></html>' % content
# 轉換為PDF
pdfkit.from_string(html, './test/%s.pdf'%(i+1))
# 利用多線程生成PDF
executor = ThreadPoolExecutor(max_workers=10) # 可以自己調整max_workers,即線程的個數
# submit()的參數: 第一個為函數, 之後為該函數的傳入參數,允許有多個
future_tasks = [executor.submit(convert_2_pdf, i) for i in range(100)]
# 等待所有的線程完成,才進入後續的執行
wait(future_tasks, return_when=ALL_COMPLETED)
end_time = time.time()
print('一共耗時:%s 秒.' %(end_time-start_time))
在這個程序中,生成100份PDF文件一共耗時約41秒,明顯快了很多~
對Python感興趣的小夥伴,記得私信小編“007”領取全套Python資料哦。
相關推薦
推薦中...