引用: 批量转换word为pdf

程序如下:

  1. import os,shutil
  2. from win32com import client
  3. def doc2pdf(doc_name, pdf_name):
  4. """
  5. :word文件转pdf
  6. :param doc_name word文件名称
  7. :param pdf_name 转换后pdf文件名称
  8. """
  9. try:
  10. word = client.DispatchEx("Word.Application")
  11. if os.path.exists(pdf_name):
  12. os.remove(pdf_name)
  13. worddoc = word.Documents.Open(doc_name,ReadOnly = 1)
  14. worddoc.SaveAs(pdf_name, FileFormat = 17)
  15. return pdf_name
  16. except Exception as e:
  17. print(e)
  18. return 1
  19. finally:
  20. worddoc.Close()
  21. word.Quit()
  22. def doc2docx(doc_name,docx_name):
  23. """
  24. :doc转docx
  25. """
  26. try:
  27. # 首先将doc转换成docx
  28. word = client.Dispatch("Word.Application")
  29. doc = word.Documents.Open(doc_name)
  30. #使用参数16表示将doc转换成docx
  31. doc.SaveAs(docx_name,16)
  32. except:
  33. pass
  34. finally:
  35. doc.Close()
  36. word.Quit()
  37. def createDirs(basePath=os.getcwd()):
  38. # 存放转化后的pdf文件夹
  39. pdfs_dir = basePath + '/pdfs'
  40. if not os.path.exists(pdfs_dir):
  41. os.mkdir(pdfs_dir)
  42. return pdfs_dir
  43. def getFileNames(basePath=os.getcwd()):
  44. filenames=[]
  45. # move all .words files to words_dir
  46. for file in os.listdir(basePath):
  47. if file.endswith('.docx'):
  48. filenames.append(file)
  49. elif file.endswith('.doc'):
  50. filenames.append(file)
  51. else:
  52. pass
  53. return filenames
  54. def convert(basePath=os.getcwd(),filenames=[]):
  55. pdfs_dir=createDirs(basePath)
  56. for filename in filenames:
  57. pdfName='.'.join(filename.split('.')[:-1])+'.pdf'
  58. doc2pdf(os.path.join(basePath,filename),os.path.join(pdfs_dir,pdfName))
  59. if __name__ == '__main__':
  60. basePath=r"document directory here"
  61. lfileNames=getFileNames(basePath)
  62. print('are you going to convert these files to pdf?')
  63. for filename in lfileNames:
  64. print(filename)
  65. print("yes/no?")
  66. while True:
  67. command=input()
  68. if command=='yes':
  69. convert(basePath,lfileNames)
  70. break
  71. elif command=='no':
  72. break
  73. else:
  74. print('wrong command,input yes or no please')

注意

安装 win32com 模块时,使用命令 python -m pip install pypiwin32 来安装。 参考