当前位置: 首页 > news >正文

python批量将pdf转成word_python批量实现Word文件转换为PDF文件

本文为大家分享了python批量转换Word文件为PDF文件的具体方法,供大家参考,具体内容如下

1、目的

通过万能的Python把一个目录下的所有Word文件转换为PDF文件。

blank.gif

2、遍历目录

作者总结了三种遍历目录的方法,分别如下。

2.1.调用glob

遍历指定目录下的所有文件和文件夹,不递归遍历,需要手动完成递归遍历功能。

import glob as gb

path = gb.glob('d:\\2\\*')

for path in path:

print path

2.2.调用os.walk

遍历指定目录下的所有文件和文件夹,递归遍历,功能强大,推荐使用。

import os

for dirpath, dirnames, filenames in os.walk('d:\\2\\'):

for file in filenames:

fullpath = os.path.join(dirpath, file)

print fullpath, file

2.3.自己DIY

遍历指定目录下的所有文件和文件夹,递归遍历,自主编写,扩展性强,可以学习练手。

import os;

files = list();

def DirAll(pathName):

if os.path.exists(pathName):

fileList = os.listdir(pathName);

for f in fileList:

if f=="$RECYCLE.BIN" or f=="System Volume Information":

continue;

f=os.path.join(pathName,f);

if os.path.isdir(f):

DirAll(f);

else:

dirName=os.path.dirname(f);

baseName=os.path.basename(f);

if dirName.endswith(os.sep):

files.append(dirName+baseName);

else:

files.append(dirName+os.sep+baseName);

DirAll("D:\\2\\");

for f in files:

print f

# print f.decode('gbk').encode('utf-8');

2.4.备注

注意,如果遍历过程中,出现文件名称或文件路径乱码问题,可以查看本文的参考资料来解决。

3、转换Word文件为PDF

通过Windows Com组件(win32com),调用Word服务(Word.Application),实现Word到PDF文件的转换。因此,要求该Python程序需要在有Word服务(可能至少要求2007版本)的Windows机器上运行。

#coding:utf8

import os, sys

reload(sys)

sys.setdefaultencoding('utf8')

from win32com.client import Dispatch, constants, gencache

input = 'D:\\2\\test\\11.docx'

output = 'D:\\2\\test\\22.pdf'

print 'input file', input

print 'output file', output

# enable python COM support for Word 2007

# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"

gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)

# 开始转换

w = Dispatch("Word.Application")

try:

doc = w.Documents.Open(input, ReadOnly=1)

doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \

Item=constants.wdExportDocumentWithMarkup,

CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

except:

print ' exception'

finally:

w.Quit(constants.wdDoNotSaveChanges)

if os.path.isfile(output):

print 'translate success'

else:

print 'translate fail'

4、批量转换

要实现批量准换,将第2步和第3步的功能组合在一起即可,直接上代码。

# -*- coding:utf-8 -*-

# doc2pdf.py: python script to convert doc to pdf with bookmarks!

# Requires Office 2007 SP2

# Requires python for win32 extension

import glob as gb

import sys

reload(sys)

sys.setdefaultencoding('utf8')

'''

参考:http://blog.csdn.net/rumswell/article/details/7434302

'''

import sys, os

from win32com.client import Dispatch, constants, gencache

# from config import REPORT_DOC_PATH,REPORT_PDF_PATH

REPORT_DOC_PATH = 'D:/2/doc/'

REPORT_PDF_PATH = 'D:/2/doc/'

# Word转换为PDF

def word2pdf(filename):

input = filename + '.docx'

output = filename + '.pdf'

pdf_name = output

# 判断文件是否存在

os.chdir(REPORT_DOC_PATH)

if not os.path.isfile(input):

print u'%s not exist' % input

return False

# 文档路径需要为绝对路径,因为Word启动后当前路径不是调用脚本时的当前路径。

if (not os.path.isabs(input)): # 判断是否为绝对路径

# os.chdir(REPORT_DOC_PATH)

input = os.path.abspath(input) # 返回绝对路径

else:

print u'%s not absolute path' % input

return False

if (not os.path.isabs(output)):

os.chdir(REPORT_PDF_PATH)

output = os.path.abspath(output)

else:

print u'%s not absolute path' % output

return False

try:

print input, output

# enable python COM support for Word 2007

# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"

gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)

# 开始转换

w = Dispatch("Word.Application")

try:

doc = w.Documents.Open(input, ReadOnly=1)

doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \

Item=constants.wdExportDocumentWithMarkup,

CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

except:

print ' exception'

finally:

w.Quit(constants.wdDoNotSaveChanges)

if os.path.isfile(pdf_name):

print 'translate success'

return True

else:

print 'translate fail'

return False

except:

print ' exception'

return -1

if __name__ == '__main__':

# img_path = gb.glob(REPORT_DOC_PATH + "*")

# for path in img_path:

# print path

# rc = word2pdf(path)

# rc = word2pdf('1')

# print rc,

# if rc:

# sys.exit(rc)

# sys.exit(0)

import os

for dirpath, dirnames, filenames in os.walk(REPORT_DOC_PATH):

for file in filenames:

fullpath = os.path.join(dirpath, file)

print fullpath, file

rc = word2pdf(file.rstrip('.docx'))

5、参考资料

利用Python将word 2007的文档转为pdf文件

遍历某目录下的所有文件夹与文件的路径、输出中文乱码问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

您可能感兴趣的文章:

python实现word 2007文档转换为pdf文件

利用python程序生成word和PDF文档的方法

批量将ppt转换为pdf的Python代码 只要27行!

Python实现将DOC文档转换为PDF的方法

python使用reportlab实现图片转换成pdf的方法

Python中使用PyQt把网页转换成PDF操作代码实例

时间: 2018-03-13

相关文章:

  • lstm时间序列预测_pytorch入门使用PyTorch进行LSTM时间序列预测
  • CSDN软件英雄会流水帐
  • jvm内存结构_你真的懂JVM内存结构吗?—深入理解JVM之内存结构
  • 技术大会英雄谱
  • python自动化和java自动化_Python和Java哪个更适合做自动化测试
  • java 创建目录_编程排行榜第一Java语言学习的第一个Java程序,小白快到碗里来...
  • 微软(北京).NET俱乐部第十四次技术沙龙-Visual Studio 2005 Team System企业级开发实训...
  • Visual Basic.net还是C# ——如何选择.net语言
  • c语言解三元一次方程组_人教版初中数学七年级下册三元一次方程组的解法2公开课优质课课件教案视频...
  • 华章公司近期重点产品介绍
  • illegalstateexception是什么异常_Java面试题Iterator怎么使用?有什么特点?
  • 部门预算进行时
  • altium 去掉部分铺铜_【干货】一文读懂铜再生分类与工艺
  • Symbian OS编码诀窍之编码诀窍
  • python set函数是什么意思_python中set是什么意思
  • .pyc 想到的一些问题
  • 【跃迁之路】【585天】程序员高效学习方法论探索系列(实验阶段342-2018.09.13)...
  • java取消线程实例
  • MYSQL如何对数据进行自动化升级--以如果某数据表存在并且某字段不存在时则执行更新操作为例...
  • PHP 使用 Swoole - TaskWorker 实现异步操作 Mysql
  • thinkphp5.1 easywechat4 微信第三方开放平台
  • Travix是如何部署应用程序到Kubernetes上的
  • ViewService——一种保证客户端与服务端同步的方法
  • 爱情 北京女病人
  • 对象引论
  • 解决iview多表头动态更改列元素发生的错误
  • 可能是历史上最全的CC0版权可以免费商用的图片网站
  • 猫头鹰的深夜翻译:Java 2D Graphics, 简单的仿射变换
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 前端js -- this指向总结。
  • 树莓派 - 使用须知
  • 物联网链路协议
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 用jquery写贪吃蛇
  • 终端用户监控:真实用户监控还是模拟监控?
  • 新年再起“裁员潮”,“钢铁侠”马斯克要一举裁掉SpaceX 600余名员工 ...
  • ​ 无限可能性的探索:Amazon Lightsail轻量应用服务器引领数字化时代创新发展
  • # 执行时间 统计mysql_一文说尽 MySQL 优化原理
  • #【QT 5 调试软件后,发布相关:软件生成exe文件 + 文件打包】
  • #快捷键# 大学四年我常用的软件快捷键大全,教你成为电脑高手!!
  • (4)Elastix图像配准:3D图像
  • (java)关于Thread的挂起和恢复
  • (pytorch进阶之路)CLIP模型 实现图像多模态检索任务
  • (独孤九剑)--文件系统
  • (二十五)admin-boot项目之集成消息队列Rabbitmq
  • (论文阅读30/100)Convolutional Pose Machines
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理第3章 信息系统治理(一)
  • (三)centos7案例实战—vmware虚拟机硬盘挂载与卸载
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (详细版)Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (转)scrum常见工具列表
  • ***检测工具之RKHunter AIDE
  • . Flume面试题
  • ../depcomp: line 571: exec: g++: not found