首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

盘点一个Python自动化办公Word转化PDF/PDF转化Word问题

太平本是将军定,不许将军见太平。

大家好,我是皮皮。

一、前言

前几天在Python最强王者交流群【钟爱一生】问了一个Python自动化办公的问题。问题如下:

代码太长了,我就不贴出来了。

二、实现过程

后来【莫生气】给了单独的 pdf 和 word 互转的代码给他,【文件夹下的word文件批量转pdf格式】代码如下:

import os

import sys

import comtypes.client

def word_to_pdf(input_folder, output_folder):

# 获取输入文件夹下的所有Word文档

word_files = [f for f in os.listdir(input_folder) if f.endswith('.docx')]

# 创建输出文件夹(如果不存在)

if not os.path.exists(output_folder):

os.makedirs(output_folder)

# 遍历所有Word文档并转换为PDF格式

for word_file in word_files:

input_file = os.path.join(input_folder, word_file)

output_file = os.path.join(output_folder, word_file.replace('.docx', '.pdf'))

# 打开Word文档

word_app = comtypes.client.CreateObject('Word.Application')

word_app.Visible = False

# 打开Word文档并另存为PDF格式

doc = word_app.Documents.Open(input_file)

doc.SaveAs(output_file, FileFormat=17)  # 17表示PDF格式

doc.Close()

# 关闭Word应用程序

word_app.Quit()

if __name__ == '__main__':

input_folder = r'C:\Users\Desktop\input_files'

output_folder = r'C:\Users\Desktop\output_files'

word_to_pdf(input_folder, output_folder)

【pdf文件转word文档】代码如下:

import pdfplumber

from docx import Document

# 读取PDF文件

with pdfplumber.open("example.pdf") as pdf:

text = ""

for page in pdf.pages:

text += page.extract_text()

# 创建一个新的Word文档

doc = Document()

# 将提取到的文本内容写入到Word文档中

doc.add_paragraph(text)

# 保存Word文档

doc.save("output.docx")

顺利地解决了粉丝的问题。

  • 发表于:
  • 原文链接https://page.om.qq.com/page/OqmV3TJCdSZzrCfAcCRNYj3g0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券