[color=]comtypes
.
[color=]client
import
[color=]os
from
[color=]datetime
import
[color=]datetime
[color=]def
convert_word_to_pdf_comtypes(word_file, pdf_file):
try:
[color=]word
=
[color=]comtypes
.
[color=]client
.
[color=]CreateObject
(
[color=]'Word.Application'
)
[color=]word
.Visible =
[color=]False
[color=]doc
=
[color=]word
.Documents.
[color=]Open
(word_file)
[color=]doc
.
[color=]SaveAs
(pdf_file, FileFormat=
[color=]17
) # 17 代表 PDF 格式
[color=]doc
.
[color=]Close
()
[color=]word
.
[color=]Quit
()
[color=]timestamp
=
[color=]datetime
.
[color=]now
().
[color=]strftime
(
[color=]"%Y-%m-
[color=]%d
[color=] %H:%M:%S"
)
[color=]print
(
[color=]f
[color=]"
[color=]{
[color=]timestamp
[color=]}
[color=] 成功将
[color=]{
word_file
[color=]}
[color=] 转换为
[color=]{
pdf_file
[color=]}
[color=]"
)
except
[color=]Exception
as
[color=]e
:
[color=]print
(
[color=]f
[color=]"转换
[color=]{
word_file
[color=]}
[color=] 失败:
[color=]{
[color=]e
[color=]}
[color=]"
)
[color=]def
batch_convert_word_to_pdf(folder_path):
if
[color=]not
[color=]os
.
[color=]path
.
[color=]exists
(folder_path):
[color=]print
(
[color=]f
[color=]"错误:文件夹路径 '
[color=]{
folder_path
[color=]}
[color=]' 不存在。"
)
return
for
[color=]filename
in
[color=]os
.
[color=]listdir
(folder_path):
if
[color=]filename
.
[color=]endswith
((
[color=]'.doc'
,
[color=]'.docx'
)):
[color=]word_file
=
[color=]os
.
[color=]path
.
[color=]join
(folder_path,
[color=]filename
)
[color=]pdf_file
=
[color=]os
.
[color=]path
.
[color=]join
(folder_path,
[color=]os
.
[color=]path
.
[color=]splitext
(
[color=]filename
)[
[color=]0
] +
[color=]".pdf"
)
[color=]convert_word_to_pdf_comtypes
(
[color=]word_file
,
[color=]pdf_file
)
if
[color=]__name__
==
[color=]"__main__"
:
[color=]folder_path
=
[color=]r
[color=]"
D:\Documents\test
[color=]"
# 替换为你的 Word 文件夹路径
[color=]timestamp
=
[color=]datetime
.
[color=]now
().
[color=]strftime
(
[color=]"%Y-%m-
[color=]%d
[color=] %H:%M:%S"
)
[color=]print
(
[color=]timestamp
+
[color=]" 开始处理"
)
[color=]batch_convert_word_to_pdf
(
[color=]folder_path
)
[color=]timestamp
=
[color=]datetime
.
[color=]now
().
[color=]strftime
(
[color=]"%Y-%m-
[color=]%d
[color=] %H:%M:%S"
)
[color=]print
(
[color=]timestamp
+
[color=]" 全部处理完毕!"
)
微信截图_20241118180649.png (149.93 KB, 下载次数: 0)
下载附件
2024-11-18 18:08 上传