You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.6 KiB

import os
import subprocess
import uuid
def get_docx_content_by_pandoc(docx_file, output_file=None, parent_dir=None):
# 最后拼接的内容
content = ""
# output_file 设置为临时目录下的uuid.md
file_name = uuid.uuid4().hex
# 将docx_file去掉扩展名
prefix = docx_file.split(".")[0].split("/")[-1]
temp_markdown = os.path.join('./static/markdown/', prefix + '.md')
if parent_dir:
temp_markdown = os.path.join('../static/markdown/', prefix + '.md')
# 调用pandoc将docx文件转换成markdown
if parent_dir is None:
os.mkdir("./static/Images/" + file_name)
extract_media = "./static/Images/"
else:
os.mkdir("../static/Images/" + file_name)
extract_media = "../static/Images/"
subprocess.run(['pandoc', docx_file, '-f', 'docx', '-t', 'markdown', '-o', temp_markdown,
'--extract-media=' + extract_media + file_name])
# 读取然后修改内容,输出到新的文件
img_idx = 0 # 图片索引
with open(temp_markdown, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
# 跳过图片高度描述行
if line.startswith('height=') and line.endswith('in"}'):
continue
# 使用find()方法安全地检查图片模式
is_img = line.find("![](") >= 0 and (
line.find(".png") > 0 or
line.find(".jpg") > 0 or
line.find(".jpeg") > 0
)
if is_img:
# ![](media/image3.png){width="3.1251607611548557in"
# height="3.694634733158355in"}
# ![](../static/Images/01b20e04085e406ea5375791da58a60f/media/image3.png){width="3.1251607611548557in"
pos = line.find(")")
q = line[:pos + 1]
q = q.replace("./static", ".")
# q = q[4:-1]
# q='<img src="'+q+'" alt="我是图片">'
img_idx += 1
content += q + "\n"
else:
content += line.strip().replace("**", "") + "\n"
content = content.replace("\phantom", "")
# 将content回写到markdown文件
if output_file is not None:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(content)
print("Conversion completed successfully!")
# 删除临时文件
os.remove(temp_markdown)
return content.replace("\n\n", "\n").replace("\\", "")