首頁  >  文章  >  後端開發  >  利用python程式產生word和PDF文件的方法

利用python程式產生word和PDF文件的方法

高洛峰
高洛峰原創
2017-02-20 10:18:292537瀏覽

這篇文章主要為大家介紹了利用python程式產生word和PDF文件的方法,文中給了詳細的介紹和範例程式碼,相信對大家具有一定的參考價值,有需要的朋友們下面來一起看看吧。

一、程式導出word文檔的方法

將web/html內容導出為world文檔,再java中有很多解決方案,例如使用Jacob、Apache POI、Java2Word、iText等各種方式,以及使用freemarker這樣的模板引擎這樣的方式。 php中也有一些對應的方法,但在python中將web/html內容產生world文件的方法是很少的。其中最不好解決的就是如何將使用js程式碼非同步取得填滿的數據,圖片匯出到word文件中。

1. unoconv

功能:

1.支援將本地html文檔轉換為docx格式的文檔,所以需要先將網頁中的html文件儲存到本地,再進行轉換。轉換效果也不錯,使用方法非常簡單。

\# 安装
sudo apt-get install unoconv
\# 使用
unoconv -f pdf *.odt
unoconv -f doc *.odt
unoconv -f html *.odt

缺點:

      1.只能以靜態html為確保文件中有數據)。

      2.只能對html轉換,如果頁面中有使用echarts,highcharts等js程式碼產生的圖片,是無法將這些圖片轉換到word文件中;

 word    3.格式不產生的文件內容容易控制。

2. python-docx

功能:

1.python-docx是一個可以讀寫word文檔的python

1.python-docx是一個可以讀寫word文檔的python庫。

使用方法:


1.取得網頁中的數據,使用python手動排版加入word文件。

from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
 'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
 'first item in ordered list', style='ListNumber'
)
document.add_picture('monty-truth.png', width=Inches(1.25))
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
 row_cells = table.add_row().cells
 row_cells[0].text = str(item.qty)
 row_cells[1].text = str(item.id)
 row_cells[2].text = item.desc
document.add_page_break()
document.save('demo.docx')

from docx import Document
from docx.shared import Inches
document = Document()
for row in range(9):
 t = document.add_table(rows=1,cols=1,style = 'Table Grid')
 t.autofit = False #很重要!
 w = float(row) / 2.0
 t.columns[0].width = Inches(w)
document.save('table-step.docx')

缺點:


功能非常弱。有很多限制例如不支援模板等,只能產生簡單格式的word文件。

二、程式匯出PDF文件方法

1.pdfkit

功能:


主要


      2.pdfkit是基於wkhtmltopdf的python封裝,支援URL,本地文件,文字內容到PDF的轉換,其最終還是呼叫wkhtmltopdf指令。是目前接觸到的python生成pdf效果較好的。

優點:


      1.wkhtmltopdf:利用webkit核心將HTML轉為PDF

瀏覽器這個內核。 Chrome列印目前網頁的功能,其中有一個選項就是直接「儲存為 PDF」。

      2.wkhtmltopdf使用webkit核心的PDF渲染引擎來將HTML頁轉換為PDF。高保真,轉換品質很好,且使用非常簡單。
使用方法:

\# 安装
pip install pdfkit
\# 使用
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

缺點:

      1.對使用echarts,highcharts/html 將產生的圖示而不是無法轉換為新程式碼將js轉換為pdf)。對於純靜態頁面的轉換效果還是不錯的。

      2.其他

其他產生pdf的插件還有:weasyprint,reportlab,PyPDF2等,經簡單試驗都不如pdfkit效果好,且有些用法複雜。

更多利用python程式產生word和PDF文件的方法相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn