word文件
文件信息查询
常量值 | 含义 | 描述 |
---|---|---|
0 | wdStatisticWords | 统计文档中的单词数。 |
1 | wdStatisticLines | 统计文档中的行数。 |
2 | wdStatisticPages | 统计文档中的页数。 |
3 | wdStatisticCharacters | 统计文档中的字符数(包括空格)。 |
4 | wdStatisticCharactersWithSpaces | 统计文档中的字符数(包括空格和特殊字符)。 |
5 | wdStatisticParagraphs | 统计文档中的段落数。 |
6 | wdStatisticFarEastCharacters | 统计文档中的东亚字符数(如中文、日文、韩文等)。 |
pip install comtypes
import comtypes.client
def get_word_page_count(doc_path: str) -> int:
"""
使用 comtypes 获取 Word 文档的准确页数。
:param doc_path: Word 文档的路径(.doc 或 .docx)
:return: 文档的页数
"""
try:
# 启动 Word 应用程序
word = comtypes.client.CreateObject("Word.Application")
word.Visible = False # 后台运行
# 打开文档
doc = word.Documents.Open(doc_path)
# 获取页数
page_count = doc.ComputeStatistics(2) # 2 表示统计页数
# 关闭文档并退出 Word
doc.Close()
word.Quit()
return page_count
except Exception as e:
print(f"Error: {e}")
return 0
# 使用示例
doc_path = "example.docx"
page_count = get_word_page_count(doc_path)
print(f"Page count: {page_count}")
# 统计文档的页数
page_count = doc.ComputeStatistics(2) # 2 表示统计页数
# 统计文档的单词数
word_count = doc.ComputeStatistics(0) # 0 表示统计单词数
# 统计文档的字符数(包括空格)
char_count = doc.ComputeStatistics(3) # 3 表示统计字符数
word转出格式
格式名称 | 常量值 | 描述 |
---|---|---|
17 | PDF 格式 | |
DOC | 0 | Word 97-2003 文档格式 (.doc) |
DOCX | 16 | Word 文档格式 (.docx) |
DOT | 1 | Word 97-2003 模板格式 (.dot) |
DOTX | 17 | Word 模板格式 (.dotx) |
RTF | 6 | 富文本格式 (.rtf) |
TXT | 2 | 纯文本格式 (.txt) |
HTML | 8 | HTML 格式 (.html) |
MHTML | 9 | MHTML 格式 (.mhtml) |
XML | 11 | XML 格式 (.xml) |
ODT | 23 | OpenDocument 文本格式 (.odt) |
XPS | 18 | XPS 格式 (.xps) |
EPS | 30 | EPS 格式 (.eps) |
JPEG | 26 | JPEG 图片格式 (.jpg) |
PNG | 28 | PNG 图片格式 (.png) |
BMP | 25 | BMP 图片格式 (.bmp) |
GIF | 27 | GIF 图片格式 (.gif) |
TIFF | 29 | TIFF 图片格式 (.tiff) |
EMF | 31 | EMF 图片格式 (.emf) |
WMF | 32 | WMF 图片格式 (.wmf) |
# 是 PDF 格式的文件格式常量
word = comtypes.client.CreateObject("Word.Application")
doc = word.Documents.Open(input_file)
doc.SaveAs(output_file, FileFormat=17)
doc.Close()
word.Quit()
win32com
import os, pathlib
from win32com import client
from pydantic import BaseModel, Field
class WORD_CODE: # 记录所有word代码
pdf: int = 17
class CpsWordConverterConfig(BaseModel):
overwrite: bool = Field(False, description="如果文件已存在,是否覆盖输出")
show_details: bool = Field(False, description="是否打印错误")
class CpsWordConverter:
def __init__(self, config: CpsWordConverterConfig = None):
"""
@Description {description}
- param config=None :{CpsWordConverterConfig} 实例配置
@example
```python
target = r"Z:/xxxdir/xxxx.docx"
target_dir = r"Z:/work/2023/改图/2023职称/周末bk"
# 初始化
Config = CpsWordConverterConfig(overwrite=False, show_details=True)
Convert = CpsWordConverter(Config)
# 单独转换文件
Convert.convert(target)
# 遍历目录
Convert.convert(target_dir)
```
"""
# 检查当前系统环境是否安装了word
if not self.__check():
raise "实例化失败"
if config:
self.config = config
else:
self.config = CpsWordConverterConfig()
self.word = None # 存储word实例
def print(self, *argvs, **keys):
if self.config.show_details:
print(*argvs, **keys)
def convert(self, target: str) -> list[str]:
"""
@Description 转换主函数
- param target :{str} target可以是目录,也可以是文件,如果是目录,将直接进行递归
"""
try:
if not os.path.exists(target):
self.print("目标不存在: ", target)
return []
# 判断是目录还是文件
p = pathlib.Path(target)
result = []
if p.is_file():
result.append(self.__word2pdf(p))
elif p.is_dir():
result = self.__dir_handler(p)
return result
except Exception as e:
self.print("convert err: ", e)
return []
def __del__(self):
if self.word:
self.word.Quit()
self.word = None
def __check(self) -> bool:
return True
def __open_word(self):
self.word = client.Dispatch("Word.Application")
self.word.Visible = False
return self.word
def __dir_handler(self, dir_path: str | pathlib.Path) -> str:
docx = list(pathlib.Path(dir_path).glob("**/*.docx"))
doc = list(pathlib.Path(dir_path).glob("**/*.doc"))
word_list = docx + doc
result = []
if len(word_list) == 0:
return ""
else:
self.print("当前需要处理的文件有: ", len(word_list))
for each in word_list:
result.append(self.__word2pdf(each))
return result
@staticmethod
def word_accept_all_revisions(word):
"""
@Description 对当前的word文件进行一次接收所有修订操作,并原地保存
- param word :{param} word实例
"""
try:
word.ActiveDocument.TrackRevisions = False
# word.WordBasic.AcceptAllChangesInDoc() # 会报错,但也可以接收所有修订
word.ActiveDocument.Revisions.AcceptAll()
if word.ActiveDocument.Comments.Count >= 1:
word.ActiveDocument.DeleteAllComments()
return word
except Exception as err:
print("word_accept_all_revisions: ", err)
return word
def __word2pdf(self, word_file: pathlib.Path) -> str:
"""
- param word_file :{str} `.doc|.docx`结尾的文件
"""
try:
# 获取同名的pdf输出路径
word_file_path = str(word_file.resolve())
output_pdf_path = str(word_file.resolve()).replace(word_file.suffix, ".pdf")
# 已存在pdf,是否进行覆盖
if os.path.exists(output_pdf_path):
# 不覆盖的话,直接跳过
if not self.config.overwrite:
self.print("文件已存在: ", output_pdf_path)
return ""
# 打开word应用程序
if not self.word:
self.word = self.__open_word()
# 打开word文件
doc = self.word.Documents.Open(word_file_path)
# 所有修订
self.word_accept_all_revisions(self.word)
# 另存为后缀为".pdf"的文件,其中参数17表示为pdf
doc.Activate()
doc.SaveAs(output_pdf_path, WORD_CODE.pdf)
# 关闭原来word文件
doc.Close()
self.print("完成转换: ", word_file)
return output_pdf_path
except Exception as e:
self.print("word2pdf err: ", e)
return ""
def example():
target = r"Z:\work\2024\项目\东莞海腾码头补办水利手续\0808珠江水文水资源勘测中心-东莞海腾码头补办水利手续工作大纲及报价书(1).docx"
target_dir = r"Z:\work\2023\改图\2023职称\周末bk"
Config = CpsWordConverterConfig(overwrite=False, show_details=True)
Convert = CpsWordConverter(Config)
Convert.convert(target)
def main(target: str):
Config = CpsWordConverterConfig(overwrite=False, show_details=True)
Convert = CpsWordConverter(Config)
Convert.convert(target)
if __name__ == "__main__":
# example()
import argparse
# 初始化实例
parser = argparse.ArgumentParser()
# 解释参数
parser.add_argument(
"target", # 不要处理的word文件
help="需要处理的.doc/.docx文件,绝对路径",
type=str,
)
args = parser.parse_args()
main(args.target)
comtypes
# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 2024-12-05 12:38:23.143046
# @Last Modified by: CPS
# @Last Modified time: 2024-12-05 12:38:23.144038
# @file_path "D:\CPS\MyProject\test\src\大藤下归档相关"
# @Filename "wordToJpg.py"
# @Description: 使用comtypes调用本地安装的word来转换文件
#
import os, sys
sys.path.append("..")
from os import path
from pathlib import Path
from pydantic import BaseModel
import comtypes.client
# Microsoft Word 文件格式常量映射表
FILE_FORMAT_MAP = {
"PDF": 17, # PDF 格式
"DOC": 0, # Word 97-2003 文档格式 (.doc)
"DOCX": 16, # Word 文档格式 (.docx)
"DOT": 1, # Word 97-2003 模板格式 (.dot)
"DOTX": 17, # Word 模板格式 (.dotx)
"RTF": 6, # 富文本格式 (.rtf)
"TXT": 2, # 纯文本格式 (.txt)
"HTML": 8, # HTML 格式 (.html)
"MHTML": 9, # MHTML 格式 (.mhtml)
"XML": 11, # XML 格式 (.xml)
"ODT": 23, # OpenDocument 文本格式 (.odt)
"XPS": 18, # XPS 格式 (.xps)
"EPS": 30, # EPS 格式 (.eps)
"JPEG": 26, # JPEG 图片格式 (.jpg)
"PNG": 28, # PNG 图片格式 (.png)
"BMP": 25, # BMP 图片格式 (.bmp)
"GIF": 27, # GIF 图片格式 (.gif)
"TIFF": 29, # TIFF 图片格式 (.tiff)
"EMF": 31, # EMF 图片格式 (.emf)
"WMF": 32, # WMF 图片格式 (.wmf)
}
def word_to_pdf(input_file: str, output_file: str) -> None:
"""
将 Word 文件另存为 PDF。
:param input_file: 输入的 Word 文件路径(.docx 或 .doc)
:param output_file: 输出的 PDF 文件路径(.pdf)
:return: None
"""
try:
_, ext = path.splitext(output_file)
if not FILE_FORMAT_MAP[ext.upper()]:
print(f"不支持当前格式输出{ext}")
return
# 启动 Word 应用程序
word = comtypes.client.CreateObject("Word.Application")
# 使 Word 程序在后台运行,不显示界面
word.Visible = False
# 打开 Word 文件
doc = word.Documents.Open(input_file)
# 将 Word 文件另存为 PDF
doc.SaveAs(output_file, FileFormat=FILE_FORMAT_MAP[ext.upper()]) # 17 是 PDF 格式的文件格式常量
# 关闭文档
doc.Close()
# 退出 Word 应用程序
word.Quit()
except Exception as e:
print(e)
def test():
target_dir = r"D:\Work\大藤峡\00 监理要求软件文件\01 开工文档\CB02 施工进度计划申报表"
target_list = []
target_list += [str(name) for name in Path(target_dir).glob("*.doc")]
target_list += [str(name) for name in Path(target_dir).glob("*.docx")]
output_list = []
output_list += [name.replace(".doc", ".pdf") for name in target_list if str(name).endswith(".doc")]
output_list += [name.replace(".docx", ".pdf") for name in target_list if str(name).endswith(".docx")]
for idx, _ in enumerate(target_list):
input_file = _
output_file = output_list[idx]
word_to_pdf(input_file, output_file)
if __name__ == "__main__":
test()
tar = r"D:\Work\大藤峡\归档\电子版\卷002\word\BS·22·01-002-7.docx"
word_to_pdf(tar, output_file)
列出文件夹页码
# 是 PDF 格式的文件格式常量
word = comtypes.client.CreateObject("Word.Application")
doc = word.Documents.Open(input_file)
doc.SaveAs(output_file, FileFormat=17)
doc.Close()
word.Quit()