输出前展平合并的文档

2024-09-28 18:13:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我对使用python uno脚本创建的邮件合并文件有问题。使用mailmerge向导在LibreOffice自身中运行mailmerge的工作方式与隐藏字段中的工作方式相同,文档中的其他字段被展平/执行,生成的文档具有正确的最终展平输出

相反,当使用下面的代码运行时,生成的是一系列输出文档,其中仍然包含字段代码,并且隐藏的段落仍然可见。每个文档都被设置到mailmerge数据库的相应行,就像我在LibreOffice中设置mailmerge时得到的预览一样。在另一台计算机上打开这些文档时,数据不会显示,因为它需要先访问后端数据库才能获取字段数据

如果在我的脚本中我将SaveFilter设置为“HTML(StarWriter)”或“writer\u pdf\u export”,那么它会压平文件,但无法从输出中删除隐藏的段落

你能帮我复制一下LibreOffice使用uno-python接口进行邮件合并的方式吗

import uno

def mergeit():
    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
    oMailMerge = smgr.createInstanceWithContext( "com.sun.star.text.MailMerge",ctx)
    oMailMerge.DocumentURL = "file:////home/user/templates/testtemplate.odt"  #Source document (forward slashes only)
    oMailMerge.DataSourceName = "jdbcpostgresmailmerge" #name of data source (included in source document)
    oMailMerge.CommandType = 0                                 #0 = table name, 1 = query name, 3 = SQL command
    oMailMerge.Command = "public.mailmergedata"                #name of table in data source
    oMailMerge.OutputType = 2                                  #1 = printer, 2 = file, 3 = email
    oMailMerge.OutputURL = uno.systemPathToFileUrl("/home/user/output/")    #output directory (forward slashes only)
    oMailMerge.SaveFilter = "writer8"
    oMailMerge.FileNameFromColumn = True       #get file name from data source column
    oMailMerge.FileNamePrefix = "mergefilename"      #name of data source column
    oMailMerge.SaveAsSingleFile = False        #save as multiple files
    oMailMerge.execute([])
    # Do a nasty thing before exiting the python process. In case the
    # last call is a oneway call (e.g. see idl-spec of insertString),
    # it must be forced out of the remote-bridge caches before python
    # exits the process. Otherwise, the oneway call may or may not reach
    # the target object.
    # I do this here by calling a cheap synchronous call (getPropertyValue).
    ctx.ServiceManager

def main():
    mergeit()

if __name__ == '__main__':
    main()

系统在ubuntu18x64上运行libreoffice6.0.6.2

以下是调用脚本之前如何启动LibreOffice:

libreoffice --headless --accept="socket,host=localhost,port=2002;urp;"

Tags: ofthename文档脚本sourcedatalibreoffice
1条回答
网友
1楼 · 发布于 2024-09-28 18:13:39

这与其说是一个真正的解决方案,不如说是一个变通办法。我没能和LibreOffice合作。但是,如果更改调用函数:

oMailMerge.execute([])

传递空元组:

oMailMerge.execute((),)

现在它可以在OpenOffice4.1.6上作为后端运行,并且与LibreOffice不同,它可以像预期的那样输出html、文本和pdf类型。它还可以输出writer8文件,因为它仍在输出字段代码,但即使数据源不在那里,它也在填充正确的值,重要的是正确处理隐藏的段落

ooo4.1.6获胜,libreoffice6.0.6.2失败

相关问题 更多 >