1、首先,必须去安装相关的库,使用命令:pip install pypiwin32,接下来是主要代码:
import win32com.client
import pythoncom
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 = Debug
self.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, reverse
import os
from apps.user.models import Attachfile
import win32com.client
import pythoncom
def show_attach_file(request, id):
"""
用户附件查看
:param request:
:param id: 附件表Attachfile id
:return:
"""
attach = Attachfile.objects.get(id=id)
save_path = attach.savepath
if 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_path
new_file = os.path.abspath('..') + 'factoringms/media/person/'+file_name
if 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 = Debug
self.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_name
return redirect(file_path)
3、这样便可以将一个word文档格式转为pdf格式了,但是这个不知道为啥在linux下安装不了pypiwin32这个库,所以不了了之了,暂时解决不了,很郁闷,试了一些方法都不行。
4、以上内容仅供学习参考,谢谢!