背景:
服務器: Ubuntu22.04
Python: 3.10.12
0. 目錄
- word的生成或編輯
1. Word的生成與編輯
安裝:
pip3 install python-docx==0.8.11
使用:
# 生成新word
doc = docx.Document()
# 編輯已有word
doc = docx.Document("../../1.docx")
# 具體操作這個文檔, 操作方式列在下面
...
# 保存
doc.save()
# 替換原有文檔的關鍵字
def find_replace_text(__doc, __replacement_dict):
# data ={search_text: replace_text, search_text: replace_text}
# 如 data = {"username": "王二小", "number": "T001"}
for p in __doc.paragraphs:
for run in p.runs: # 遍歷段落的字塊
for search_text, replace_text in __replacement_dict.items():
run.text = run.text.replace(search_text, replace_text if replace_text else "") # 替換字塊的文字,然后賦值給字塊
for table in __doc.tables:
for row in table.rows:
for cell in row.cells:
if "all_page" in cell.text:
print(cell.text)
cell.paragraphs[0].paragraph_format.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.RIGHT
for search_text, replace_text in __replacement_dict.items():
cell.text = cell.text.replace(search_text, replace_text if replace_text else "")
# 插入文字
paragraph = doc.add_paragraph()
run = paragraph.add_run("王二小") # 插入字
run.bold = True # 粗體
run.font.name = '宋體' # 宋體
run.font.size = docx.shared.Pt(12) # 字體大小
paragraph.paragraph_format.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.CENTER # 居中
# 插入表格
table = doc.add_table(rows=3, cols=6) # 插入一個 3行 8列 的 表格
table.style = 'Table Grid' # 表格添加邊框
# 添加第一行數據
__count = -1
for i in ["ID", "編號", "姓名", "性別", "手機號", "身份證號"]:
__count += 1
table.cell(0, __count).text = i
table.cell(1, 2).text="王二小" # 添加第二行 第三列數據
table.cell(3, 1).paragraphs[0].paragraph_format.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.LEFT # 居左
th = table.cell(4, 0).paragraphs[0].runs[0]
th.font.size = docx.shared.Pt(14) # 字體大小
th.font.name = '宋體' # 字體
th.bold = True # 加粗
# 添加 分頁符(下一頁)
doc.add_section()
# 添加一個橫向頁面
doc.add_section()
# 這一頁是橫向的
section = doc.sections[-1]
new_width, new_height = section.page_height, section.page_width
section.orientation = docx.enum.section.WD_ORIENT.LANDSCAPE
section.page_width = new_width
section.page_height = new_height
2. Word轉PDF
方式: 通過直接調用命令行的方式使用 libreoffice 軟件來轉換1.
2.1 軟件安裝
-
安裝 libreoffice
apt isntall libreoffice
-
為操作系統安裝中文字體
將C:\Windows\Fonts 下的字體全部復制到 /usr/share/fonts/ 下面 apt install xfonts-utils -y mkfontscale mkfontdir fc-cache -fv # 驗證是否安裝成功 fc-list :lang=zh
-
為 libreoffice 安裝中文字體
cp /usr/share/fonts/*.TTF /usr/lib/libreoffice/share/fonts
-
重啟libreoffice
ps -ef |grep office kill掉 nohup /usr/lib/libreoffice/program/soffice.bin & >/dev/null 2>&1 &
-
驗證:
libreoffice --headless --convert-to pdf 1.docx
2.2 python調用
from subprocess import Popen
import subprocess
def doc2pdf(word_file, pdf_path):
stdout, stderr = Popen(['libreoffice', '--headless','--convert-to', 'pdf', word_file, '--outdir', pdf_path]).communicate()
if stderr:
raise subprocess.SubprocessError(stderr)
if __name__ == '__main__':
word_file = "/opt/test/1.docx"
pdf_path = "/opt/test"
doc2pdf(word_file, pdf_path)
生成的 pdf 文件名會與doc文件名一樣
如 user.docx ==> user.pdf
查看 /opt/test 是否有生產的pdf文件