将word文件转换为pdf,然后合并pdf



我正在尝试将一些单词转换为pdf,然后合并这些pdf。我在合并部分遇到了问题,我得到了一个空的pdf文件。因为我在有word文件的目录下进行合并,所以我使用path.endwith(".pdf"(只合并pdf文件。代码如下:

import os
import win32com.client
import re
from PyPDF2 import PdfMerger
path = (r'C:Mytesttrials')
word_file_names = []
word = win32com.client.Dispatch('Word.Application')
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:  
if f.lower().endswith(".docx") :
new_name = f.replace(".docx", ".pdf")
in_file =(dirpath + '/'+ f)
new_file =(dirpath + '/' + new_name)
doc = word.Documents.Open(in_file)
doc.SaveAs(new_file, FileFormat = 17)
doc.Close()
if f.lower().endswith(".doc"):
new_name = f.replace(".doc", ".pdf")
in_file =(dirpath +'/' + f)
new_file =(dirpath +'/' + new_name)
doc = word.Documents.Open(in_file)
doc.SaveAs(new_file, FileFormat = 17)
doc.Close()
word.Quit()

merger = PdfMerger()
pdfs = os.scandir(r'C:Mytesttrials')
for pdf in pdfs:
if path.endswith(".pdf"):
merger.append(pdf)
merger.write("merged.pdf")
merger.close()

我找到了一种行之有效的方法。很抱歉没有早点发布。

merger = PyPDF2.PdfFileMerger()
for file in os.listdir(os.curdir):
if file.endswith(".pdf"):
merger.append(file)
merger.write("merged.pdf")
merger.close()

最新更新