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

 2023-09-11 阅读 29 评论 0

摘要:1、首先,必须去安装相关的库,使用命令:pip install pypiwin32,接下来是主要代码: import win32com.client import pythoncomclass Word_2_PDF(object):def __init__(self, filepath, Debug=False):""":param filepath::pa

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

import win32com.client
import 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')

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

from django.shortcuts import render, redirect, reverse
import os
from apps.user.models import Attachfile
import win32com.client
import 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、以上内容仅供学习参考,谢谢!

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/47344.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息