from spire.doc import *
import difflib


# 将文本写入文件
def WriteAllText(fname: str, text: str):
    with open(fname, "w", encoding="utf-8") as fp:
        fp.write(text)


inputFile = "/home/ccran/lufa-contract/demo/修订测试.docx"

# 创建Document类的对象
doc = Document()

# 加载Word文档
doc.LoadFromFile(inputFile)
before_text = doc.GetText()
print("===== 修订前文本 =====")
print(before_text)

# 检查文档是否有未接受的修订
if doc.HasChanges:
    # 接受所有修订
    doc.AcceptChanges()

after_text = doc.GetText()
print("===== 修订后文本 =====")
print(after_text)

before_lines = before_text.splitlines()
after_lines = after_text.splitlines()

diff_lines = list(
    difflib.unified_diff(
        before_lines,
        after_lines,
        fromfile="before_revision",
        tofile="after_revision",
        lineterm="",
    )
)

print("===== Diff 对比结果 =====")
if diff_lines:
    print("\n".join(diff_lines))
else:
    print("修订前后文本一致，无差异。")

doc.Close()
