600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python利用win32com实现doc文档转为pdf文档的功能

python利用win32com实现doc文档转为pdf文档的功能

时间:2019-07-04 10:44:18

相关推荐

python利用win32com实现doc文档转为pdf文档的功能

1、首先,必须去安装相关的库,使用命令:pip install pypiwin32,接下来是主要代码:

import win32com.clientimport pythoncomclass Word_2_PDF(object):def __init__(self, filepath, Debug=False):""":param filepath::param Debug: 控制过程是否可视化"""self.wordApp = win32com.client.Dispatch('word.Application')self.wordApp.Visible = Debugself.myDoc = self.wordApp.Documents.Open(filepath)def export_pdf(self, output_file_path):"""将Word文档转化为PDF文件:param output_file_path::return:"""self.myDoc.ExportAsFixedFormat(output_file_path, 17, Item=7, CreateBookmarks=0)if __name__ == '__main__':rootpath = 'C:\\word_2_PDF\\' # 文件夹根目录pythoncom.CoInitialize()Word_2_PDF = Word_2_PDF(rootpath + 'Docfile.docx', True)Word_2_PDF.export_pdf(rootpath + 'PDFfile.pdf')

2、完整代码如下,读取表里的路径,之后返回一个网页地址,来打开这个pdf:

from django.shortcuts import render, redirect, reverseimport osfrom apps.user.models import Attachfileimport win32com.clientimport pythoncomdef show_attach_file(request, id):"""用户附件查看:param request::param id: 附件表Attachfile id:return:"""attach = Attachfile.objects.get(id=id)save_path = attach.savepathif type(save_path) != 'str':save_path = str(save_path)file_name = save_path.split("/")[-1].split(".")[0] + '.pdf'url = request._get_scheme() + '://' + request.get_host() + '/user/user_info/media/'old_file = os.path.abspath('..') + 'factoringms/media/' + save_pathnew_file = os.path.abspath('..') + 'factoringms/media/person/'+file_nameif save_path.endswith('.docx'):class Word_2_PDF(object):def __init__(self, filepath, Debug=False):""":param filepath::param Debug: 控制过程是否可视化"""self.wordApp = win32com.client.Dispatch('Word.Application')self.wordApp.Visible = Debugself.myDoc = self.wordApp.Documents.Open(filepath)def export_pdf(self, output_file_path):"""将Word文档转化为PDF文件:param output_file_path::return:"""self.myDoc.ExportAsFixedFormat(output_file_path, 17, Item=7, CreateBookmarks=0)if not os.path.exists(new_file):pythoncom.CoInitialize()Word_2_PDF = Word_2_PDF(old_file, True)Word_2_PDF.export_pdf(new_file)file_path = url + 'person/' + file_namereturn redirect(file_path)

3、这样便可以将一个word文档格式转为pdf格式了,但是这个不知道为啥在linux下安装不了pypiwin32这个库,所以不了了之了,暂时解决不了,很郁闷,试了一些方法都不行。

4、以上内容仅供学习参考,谢谢!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。