Python - 批量转换Word文件为PDF文件

1,目的

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

Word to PDF .jpg

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,参考资料

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
批量转化Word文件PDF文件,可以使用Python中的`win32com`模块来自动化Word应用程序,将Word文件转换PDF格式。具体步骤如下: 1. 安装`win32com`模块。在命令行中输入以下命令: ``` pip install pywin32 ``` 2. 编写Python脚本。以下是一个示例脚本,将指定目录下的所有Word文件转换PDF文件: ```python import os import win32com.client # Word转换PDF的函数 def word2pdf(input_file, output_file): word = win32com.client.Dispatch('Word.Application') doc = word.Documents.Open(input_file) doc.SaveAs(output_file, FileFormat=17) doc.Close() word.Quit() # 获取指定目录下的所有Word文件 input_dir = 'C:/input_dir' # 替换为你的输入目录 output_dir = 'C:/output_dir' # 替换为你的输出目录 files = os.listdir(input_dir) word_files = [f for f in files if f.endswith('.doc') or f.endswith('.docx')] # 逐个转换Word文件PDF文件 for word_file in word_files: input_file = os.path.join(input_dir, word_file) output_file = os.path.join(output_dir, os.path.splitext(word_file)[0] + '.pdf') word2pdf(input_file, output_file) ``` 3. 将脚本打包成可执行文件。可以使用`pyinstaller`模块将Python脚本打包成可执行文件。在命令行中输入以下命令: ``` pip install pyinstaller pyinstaller --onefile your_script_name.py ``` 这将生成一个单独的可执行文件`your_script_name.exe`,可以在不安装Python环境的情况下运行脚本。 注意:由于使用了`win32com`模块,因此该脚本只能在Windows操作系统上运行。如果在其他操作系统上运行脚本,需要使用其他方式将Word文件转换PDF文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红薯爱帅

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值