美文网首页
Word的生成与转为PDF

Word的生成与转为PDF

作者: aq_wzj | 来源:发表于2023-09-14 12:02 被阅读0次

背景:

服务器: Ubuntu22.04

Python: 3.10.12

0. 目录

  1. 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 软件安装

  1. 安装 libreoffice

    apt isntall libreoffice

  2. 为操作系统安装中文字体

    将C:\Windows\Fonts 下的字体全部复制到 /usr/share/fonts/ 下面
    apt install xfonts-utils -y
    mkfontscale
    mkfontdir
    fc-cache -fv
    # 验证是否安装成功
    fc-list :lang=zh
    
  3. 为 libreoffice 安装中文字体

    cp /usr/share/fonts/*.TTF /usr/lib/libreoffice/share/fonts

  4. 重启libreoffice

    ps -ef |grep office
    kill掉
    nohup /usr/lib/libreoffice/program/soffice.bin & >/dev/null 2>&1 &
    
  5. 验证:

    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文件

相关文章

网友评论

      本文标题:Word的生成与转为PDF

      本文链接:https://www.haomeiwen.com/subject/bfumvdtx.html