1. 安裝win32庫
python -m pip install pypiwin32
缺點:
僅windows平臺,且裝有office
匯出pdf
from win32com.client import Dispatch, constants, gencache
def doc2pdf(input, output):
w = Dispatch('Word.Application')
try:
# 開啟檔案
doc = w.Documents.Open(input, ReadOnly=1)
# 轉換檔案
doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
return True
except:
return False
finally:
w.Quit(constants.wdDoNotSaveChanges)
def GenerateSupport():
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
def main():
input = 'C:\\test\\Word_2_PDF\\Docfile.docx'
output = 'C:\\test\\Word_2_PDF\\2.pdf'
# GenerateSupport()
rc = doc2pdf(input, output)
if rc:
print('轉換成功')
else:
print('轉換失敗')
if __name__ == '__main__':
main()
2. comtypes
失敗
Traceback (most recent call last):
File "/Users/kingdelee/PycharmProjects/SIL/src/py/study/toPdf/MyComtypes.py", line 1, in <module>
from comtypes import client
File "/usr/local/lib/python3.7/site-packages/comtypes/__init__.py", line 23, in <module>
from _ctypes import COMError
ImportError: cannot import name 'COMError' from '_ctypes' (/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_ctypes.cpython-37m-darwin.so)
from comtypes import client
class ComTypes:
def ppt_pdf(self, path):
# PPT 轉 PDF
pdf_path = path.replace('ppt', 'pdf') # pdf儲存路徑 推薦使用絕對路徑
try:
p = client.CreateObject("PowerPoint.Application")
ppt = p.Presentations.Open(path)
ppt.ExportAsFixedFormat(pdf_path, 2, PrintRange=None)
ppt.Close()
p.Quit()
except Exception as e:
pass
def word_pdf(self, path):
# Word轉pdf
pdf_path = path.replace('doc', 'pdf')
w = client.CreateObject("Word.Application")
doc = w.Documents.Open(path)
doc.ExportAsFixedFormat(pdf_path, 17)
doc.Close()
w.Quit()
def excel_pdf(self, path):
# Excel轉pdf
pdf_path = path.replace('xls', 'pdf')
xlApp = client.CreateObject("Excel.Application")
books = xlApp.Workbooks.Open(path)
books.ExportAsFixedFormat(0, pdf_path)
xlApp.Quit()
if __name__ == '__main__':
comty = ComTypes()
comty.word_pdf("/Users/kingdelee/Downloads/Word_2_PDF/Docfile.docx")
3. pdfkit pdf 水印
4. python-docx-template
模板方式
官方文件:
https://docxtpl.readthedocs.io/en/latest/#
參考:
https://blog.csdn.net/weixin_42670653/arti...
https://blog.csdn.net/DaShu0612/article/de...
安裝:
pip install docxtpl
5. python-docx
優點:不依賴作業系統,跨平臺
參考:
https://blog.csdn.net/edogawachia/article/...
https://www.jb51.net/article/143936.htm