如何从 Linux 上的多个 .doc/.docx 文件中删除行号?

How to remove row line numbers from several .doc/.docx files on Linux?

作为 (Python) 数据处理管道的一部分,我需要从大量 Word .doc/.docx 文件中删除行号。

我知道使用 Word.Interop(例如 )在 C# 中执行此操作的解决方案,但实现此操作会很棒,例如在 --headless 模式下使用 LibreOffice(在评估 MS Word + wine 解决方案之前)。

对于单个文件,使用 UI,可以遵循 https://help.libreoffice.org/Writer/Line_Numbering,但我需要对很多文件执行此操作,因此 macro/script/command 行解决方案

1) 循环浏览一组文件
2) 删除行号并将结果保存到文件

并触发例如Python subprocess 调用会很棒,甚至可以调用 Python API (https://help.libreoffice.org/Common/Scripting)。

对工作目录中的文件列表执行行删除(并将结果输出到 pdf 中)运行 LibreOffice 在 Linux 命令行中:

soffice --headless --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

然后在 Python 解释器中

import uno
import socket
import os
import subprocess
from pythonscript import ScriptContext
from com.sun.star.beans import PropertyValue

# list docfiles in working dir
files = [x for x in os.listdir('.') if x.endswith(".docx")]

# iterate on files
for file in files:

    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
    ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)

    # open file 
    model = desktop.loadComponentFromURL(uno.systemPathToFileUrl(os.path.realpath(file)), "_blank", 0, ())

    # remove line numbers
    model.getLineNumberingProperties().IsOn = False

    # prepare to save output to pdf
    XSCRIPTCONTEXT = ScriptContext(ctx, None, None)

    p = PropertyValue()
    p.Name = 'FilterName'
    p.Value = 'writer_pdf_Export'

    oDoc = XSCRIPTCONTEXT.getDocument()

    # create pdf 
    oDoc.storeToURL("file://" + os.getcwd() + "/" + file + ".pdf", tuple([p]))

这应该会在您的工作目录中创建没有行号的 pdf 文件。

有用的链接:
Add line numbers and export to pdf via macro on OpenOffice forums
LineNumberingProperties documentation
Info on running a macro from the command line