Python调用WPS把文档转换PDF,并把PDF转图片

xiaohai 2024-07-10 16:46:19 454人围观 标签: Python  office 
简介Python调用WPS把文档转换PDF,并把PDF转图片,首先需要安装WPS,然后利用pypiwin32把文档转化成PDF,再利用fitz、PyMuPD把PDF转化成图片
一、文档转PDF

1、准备:因为需要用WPS转换文档,那么需要先安装WPS;

2、安装pypiwin32包

pypiwin32是一个用于操作Windows系统的Python模块。它提供了许多用于操作Windows API的函数和类,让开发者能够在Python中方便地进行Windows系统操作。

pip install pypiwin32

3、代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import win32com.client
import time


def ConvertByWps(sourceFile, targetFile):
    if not os.path.exists(sourceFile):
        print(sourceFile + "不存在,无法继续!")
        return False
    typemap = {
        "doc": "word",
        "docx": "word",
        "ppt": "ppt",
        "pptx": "ppt",
        "xls": "excel",
        "xlsx": "excel",
    }
    name_arr = sourceFile.split(".")
    suffix = name_arr[len(name_arr) - 1]
    wpstype = typemap.get(suffix)

    if wpstype is None:
        return False

    os.system("taskkill /im wps.exe")
    # 如果文件存在就删除
    if os.path.exists(targetFile):
        os.remove(targetFile)
    if wpstype == "word":
        ConvertDocToPdf(sourceFile, targetFile)
    elif wpstype == "ppt":
        ConvertPptToPdf(sourceFile, targetFile)
    elif wpstype == "excel":
        ConvertXlsToPdf(sourceFile, targetFile)
    if os.path.exists(targetFile):
        return True
    else:
        return False


# 转换 Word文件档到pdf
def ConvertDocToPdf(src, dst):
    wps = win32com.client.Dispatch("Kwps.Application")
    wps.Visible = False
    doc = wps.Documents.Open(src)
    doc.ExportAsFixedFormat(dst, 17)
    doc.Close()
    wps.Quit()


# 转换 PPT文件档到pdf
def ConvertPptToPdf(src, dst):
    wps = win32com.client.Dispatch("Kwpp.Application")
    wps.Visible = False
    ppt = wps.Presentations.Open(src)
    ppt.SaveAs(dst, 32)
    ppt.Close()
    wps.Quit()


# 转换 XLS文件档到pdf
def ConvertXlsToPdf(src, dst):
    wps = win32com.client.Dispatch("Ket.Application")
    excel = wps.Workbooks.Open(src)
    excel.ExportAsFixedFormat(0, dst)
    excel.Close()
    wps.Quit()


if __name__ == "__main__":
    # 当前目录
    d = os.path.dirname(__file__)
    abspath = os.path.abspath(d)

    # 测试用例
    src = abspath + r"/111.doc"
    dst = abspath + r"/111.pdf"
    r = ConvertByWps(src, dst)
    print(r)

 

二、PDF转图片

1、安装依赖

pip install fitz
pip install PyMuPDF

2、解决错误(没有则跳过)
在安装的过程中需要解决出现的一些问题。

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

出现上面错误参考这个文档:python中,Microsoft Visual C++ 14.0 or greater is required问题解决方案 - 张飞的猪 - 博客园 (cnblogs.com)

3、代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import win32com.client
import time

# 将PDF转化为图片
# pdfPath pdf文件的路径
# imgPath 图像要保存的文件夹
# zoom_x x方向的缩放系数
# zoom_y y方向的缩放系数
# rotation_angle 旋转角度
def pdf_image(pdfPath, imgPath, zoom_x, zoom_y, rotation_angle):
    path_arr = pdfPath.split(os.sep)
    path_arr.reverse()
    filename = ""
    if len(path_arr) > 0:
        filename = path_arr[0].split(".")[0]
    start_time = time.perf_counter()
    pdf = fitz.open(pdfPath)

    pageCount = pdf.page_count
    if pageCount > 3:
        pageCount = 3
    # 逐页读取PDF
    filename_arr = []
    for pg in range(0, pageCount):
        page = pdf[pg]
        # 设置缩放和旋转系数
        trans = fitz.Matrix(zoom_x, zoom_y).prerotate(rotation_angle)
        pm = page.get_pixmap(matrix=trans, alpha=False)
        # 开始写图像
        filename_all = f"{imgPath}{os.sep}{filename}_{str(pg)}.png"
        pm.save(filename_all)
        filename_arr.append(filename_all)
    pdf.close()
    end_time = time.perf_counter()
    print(f"时间差:{end_time-start_time}")
    print(len(filename_arr))


if __name__ == "__main__":
    # 当前目录
    d = os.path.dirname(__file__)
    abspath = os.path.abspath(d)

    dst = abspath + r"\111.pdf"
    pdf_image(dst, abspath, 2, 2, 0)

 

原文地址:Python调用WPS进行文档转换PDF及PDF转图片-腾讯云开发者社区-腾讯云 (tencent.com)