【Python】一键搞定Word(doc/docx)与PDF文档批量转换(附源码和工具)
				
									
					
					
						 | 
						
							
							admin 
							
							
								2024年12月3日 10:21
								本文热度 2497
							
							 
						 | 
					
					
				 
				今天分享一下如何利用Python实现Word文件和PDF文件的相互转换,尤其是PDF批量转Word。文末有福利哦~
1. Word转PDF文档
Word转PDF很简单,这里提几种方法:
- 最简单的就是打开Word文档,然后另存为时选择“PDF”格式即可。
 - 使用一些在线工具,比如:Smallpdf (https://smallpdf.com/word-to-pdf)。
 - 使用第三方软件,比如我平时一般用福昕阅读器看PDF文件,安装的时候就会在Word里多一个插件,可以用来转PDF。
 
但,如果是几十份、甚至几百份Word文件呢?上面这样转就太吃力了,得请出Python了。
1.1 Word批量转PDF
通过Python,可以很方便地将Word文档批量转换为PDF,具体代码如下:
def convert_word_to_pdf(directory):
    files = os.listdir(directory)
    word_files = [f for f in files if f.endswith(('.doc', '.docx'))]
    
    word = comtypes.client.CreateObject('Word.Application')
    word.Visible = False  
    
    # 遍历每个Word文档文件并转换为PDF
    for word_file in word_files:
        word_file_path = os.path.join(directory, word_file)
        pdf_file_path = os.path.splitext(word_file_path)[0] + '.pdf'
        
        try:
            doc = word.Documents.Open(word_file_path)
            doc.SaveAs(pdf_file_path, FileFormat=17)  # 17代表PDF格式
            doc.Close()
            print(f"Converted {word_file} to {os.path.basename(pdf_file_path)}")
        except Exception as e:
            print(f"Failed to convert {word_file}: {e}")
    
    word.Quit()
if __name__ == "__main__":
    current_directory = os.getcwd()
    convert_word_to_pdf(current_directory)
2. PDF转Word文档
对于单个文件,同样有在线工具可以实现,比如:https://smallpdf.com/pdf-to-word。但是对于批量的PDF文件,显然Python更胜一筹!
2.1 PDF批量转Word
对于PDF转Word,我们可以使用pdf2docx库,这个库提供了简便的PDF到Word转换功能,具体代码如下:
def convert_pdf_to_word(directory):
    files = os.listdir(directory)
    
    pdf_files = [f for f in files if f.endswith('.pdf')]
    
    for pdf_file in pdf_files:
        pdf_file_path = os.path.join(directory, pdf_file)
        word_file_path = os.path.splitext(pdf_file_path)[0] + '.docx'
        
        cv = Converter(pdf_file_path)
        cv.convert(word_file_path)
        cv.close()
        
        print(f"Converted {pdf_file} to {os.path.basename(word_file_path)}")
if __name__ == "__main__":
    current_directory = os.getcwd()
    convert_pdf_to_word(current_directory)
One more thing…
为了朋友们使用方便,我把上述两个功能分别打包成.exe文件了,只要把该文件放到需要转换文件的同级目录,双击运行即可完成转换!
- Word2PDF.exe:Word转PDF可执行工具
 - PDF2Word.exe:PDF转Word可执行工具
 
该文章在 2024/12/3 10:26:54 编辑过