Python之將Python字符串生成PDF


  筆者在今天的工作中,遇到了一個需求,那就是如何將Python字符串生成PDF。比如,需要把Python字符串‘這是測試文件’生成為PDF, 該PDF中含有文字‘這是測試文件’。
  經過一番檢索,筆者決定采用wkhtmltopdf這個軟件,它可以將HTML轉化為PDF。wkhtmltopdf的訪問網址為:https://wkhtmltopdf.org/downloads.html ,讀者可根據自己的系統下載對應的文件並安裝。安裝好wkhtmltopdf,我們再安裝這個軟件的Python第三方模塊——pdfkit,安裝方式如下:

pip install pdfkit

  我們再討論如下問題:

  • 如何將Python字符串生成PDF;
  • 如何生成PDF中的表格;
  • 解決PDF生成速度慢的問題。

如何將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爬蟲與算法(微信號為:easy_web_scrape), 歡迎大家關注~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM