程序生成word與PDF文檔的方法(python)


程序導出word文檔的方法

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

1. unoconv

功能:

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

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

缺點:

1.只能對靜態html進行轉換,對於頁面中有使用ajax異步獲取數據的地方也不能轉換(主要是要保證從web頁面保存下來的html文件中有數據)。
2.只能對html進行轉換,如果頁面中有使用echarts,highcharts等js代碼生成的圖片,是無法將這些圖片轉換到word文檔中;
3.生成的word文檔內容格式不容易控制。

2. python-docx

功能:

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')

缺點:

1.功能非常弱。有很多限制比如不支持模板等,只能生成簡單格式的word文檔。

程序導出PDF文檔方法

1.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。高保真,轉換質量很好,且使用非常簡單。

使用方法:

# 安裝
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這樣的js代碼生成的圖標無法轉換為pdf(因為它的功能主要是將html轉換為pdf,而不是將js轉換為pdf)。對於純靜態頁面的轉換效果還是不錯的。

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


免責聲明!

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



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