代码之家  ›  专栏  ›  技术社区  ›  Davide Fiocco

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

  •  0
  • Davide Fiocco  · 技术社区  · 7 年前

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

    我知道使用word.interop(例如 Is it possible to use Microsoft.Office.Interop.Word to programatically remove line numbering from a Word document? )但如果能做到这一点,比如在 --headless 模式(评估MS Word+葡萄酒解决方案之前)。

    对于一个文件,使用ui,可以跟踪 https://help.libreoffice.org/Writer/Line_Numbering ,但我需要对许多文件执行此操作,因此

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

    并用Python等触发 subprocess 调用会很好,甚至可以调用python api( https://help.libreoffice.org/Common/Scripting ).

    1 回复  |  直到 7 年前
        1
  •  3
  •   Davide Fiocco    7 年前

    要对工作目录中的文件列表执行行删除(并将结果输出放入pdfs),请在Linux命令行中运行LibreOffice:

    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

    推荐文章