通过命令行为LibreOffice文档设置用户定义变量/自定义属性

huangapple go评论60阅读模式
英文:

Set user defined variables/custom properties for LibreOffice document via CLI

问题

以下是您要翻译的内容:

所以有很多问题,如何通过命令行将ODT转换为PDF。
我成功地使用了

soffice --headless --convert-to pdf:"writer_pdf_Export:SelectPdfVersion=1" --outdir outdir testDocument.odt

但是我的文档包含用户定义的变量,这些变量是使用字段注入到文本中的。我想通过命令行设置这样的变量值,以便在生成PDF时包含正确的文本。我在MS Word上做过类似的事情,但在Writer中如何实现呢?

如果有帮助的话,我可以转向自定义属性,而不是变量 - 但我仍然需要在命令行上设置它们。

对我失败的是

soffice --headless --convert-to "odt:{"Version":{"type":"string","value":"1.0"}}" ReadMe.odt 
convert /home/queeg/ReadMe.odt -> /home/queeg/ReadMe.odt 使用过滤器:{"Version":{"type":"string","value":"1.0"}}
覆盖:/home/queeg/ReadMe.odt
错误:请验证输入参数... (SfxBaseModel::impl_store <file:///home/queeg/ReadMe.odt> 失败:0x81a(错误区域:Io 类:参数代码:26) ./sfx2/source/doc/sfxbasemodel.cxx:3202 ./sfx2/source/doc/sfxbasemodel.cxx:1775)

这个命令没有出错,但似乎对我的文档没有影响。它既没有设置自定义属性Version,也没有设置自定义变量Version

soffice --headless --convert-to "pdf:draw_pdf_Export:{"Version":{"type":"string","value":"draft"}}" ReadMe.odt 
convert /home/queeg/ReadMe.odt -> /home/queeg/ReadMe.pdf 使用过滤器:draw_pdf_Export:{"Version":{"type":"string","value":"draft"}}
覆盖:/home/queeg/ReadMe.pdf
英文:

So there are numerous questions how to convert ODT to PDF via command line.
I successfully used

soffice --headless --convert-to pdf:"writer_pdf_Export:SelectPdfVersion=1" --outdir outdir testDocument.odt

However my document contains user defined variables that are injected into the text using fields. I would like to set such variable value via command line so that at PDF generation the correct text is contained. I have done similar stuff on MS Word, but how would this work in Writer?

And if it helps, I can move to custom properties instead of variables - but I would still have to set them on the CLI.

What failed for me was

soffice --headless --convert-to "odt:{\"Version\":{\"type\":\"string\",\"value\":\"1.0\"}}" ReadMe.odt 
convert /home/queeg/ReadMe.odt -> /home/queeg/ReadMe.odt using filter : {"Version":{"type":"string","value":"1.0"}}
Overwriting: /home/queeg/ReadMe.odt
Error: Please verify input parameters... (SfxBaseModel::impl_store <file:///home/queeg/ReadMe.odt> failed: 0x81a(Error Area:Io Class:Parameter Code:26) ./sfx2/source/doc/sfxbasemodel.cxx:3202 ./sfx2/source/doc/sfxbasemodel.cxx:1775)

This command did not error out but also seemed to have no effect on my document. It did neither set the custom property Version nor the custom variable Version:

soffice --headless --convert-to "pdf:draw_pdf_Export:{\“Version\”:{\“type\”:\“string\”,\“value\”:\“draft\”}}" ReadMe.odt 
convert /home/queeg/ReadMe.odt -> /home/queeg/ReadMe.pdf using filter : draw_pdf_Export:{\“Version\”:{\“type\”:\“string\”,\“value\”:\“draft\”}}
Overwriting: /home/queeg/ReadMe.pdf

答案1

得分: 0

Sure, here's the translated content:

我找到了一个基于 https://python-ooo-dev-tools.readthedocs.io/en/latest/index.html 的解决方案,我想与其他人和未来的自己分享。

它包括一个Python脚本,可以加载文档,设置用户定义的属性,并将文档保存为ODT、PDF或任何其他支持的输出格式。

在新安装的Ubuntu系统上,运行以下命令安装:

sudo apt-get install pip3
sudo pip install ooo-dev-tools

然后安装此脚本:

#!/bin/python3

import sys
from ooodev.utils.lo import Lo
from ooodev.utils.info import Info
from com.sun.star.beans import XPropertySet
from com.sun.star.beans import XPropertyAccess

doc = None

def main() -> int:
  print(sys.argv)

  with Lo.Loader(Lo.ConnectSocket(headless=True)) as loader:
    i = 0
    while i < len(sys.argv):
      arg = sys.argv[i]
      match arg:
        case "--load":
          i=i+1
          docname = sys.argv[i]
          print("loading " + docname)
          doc = Lo.open_doc(fnm=docname, loader=loader)
        case "--set":
          i=i+1
          val = sys.argv[i]
          items = val.split("=")
          name = items[0]
          value = items[1]
          print("setting " + name + "=>" + value)
          
          user_props = Info.get_user_defined_props(doc) # XPropertyContainer
          ps = Lo.qi(XPropertySet, user_props, True)
          
          try:
            ps.setPropertyValue(name, value)
          except Exception:
            pa = Lo.qi(XPropertyAccess, user_props, True)
            names = []
            for propertyvalue in pa.getPropertyValues():
              names.append(propertyvalue.Name)
            print ("Cannot set property '" + name + "'. Known properties are ", names)
            return 1
        case "--save":
          i=i+1
          docname = sys.argv[i]
          print("saving " + docname)
          Lo.save_doc(doc=doc, fnm=docname)
        case _:
          print (i, sys.argv[i])
      i=i+1
    return 0

if __name__ == "__main__":
    raise SystemExit(main())

最后像这样运行代码:

convert.py --load mydoc.odt --set propname=propvalue --save mydoc.pdf

请注意,您可以多次使用所有选项,并且它们从左到右进行评估。这意味着您可以加载文档、设置多个属性,将其保存到两个输出文档中,然后加载下一个...

英文:

So I found a solution based on https://python-ooo-dev-tools.readthedocs.io/en/latest/index.html that I want to share with others and my future self.

It consists of a python script that can load a document, set user-defined properties and save the document back as ODT, or PDF or any other supported output format.

For installation on a fresh Ubuntu system, run

sudo apt-get install pip3
sudo pip install ooo-dev-tools

Then install this script:

#!/bin/python3

import sys
from ooodev.utils.lo import Lo
from ooodev.utils.info import Info
from com.sun.star.beans import XPropertySet
from com.sun.star.beans import XPropertyAccess

doc = None

def main() -&gt; int:
  print (sys.argv)

  with Lo.Loader(Lo.ConnectSocket(headless=True)) as loader:
    i = 0
    while i &lt; len(sys.argv):
      arg = sys.argv[i]
      match arg:
        case &quot;--load&quot;:
          i=i+1
          docname = sys.argv[i]
          print(&quot;loading &quot; + docname)
          doc = Lo.open_doc(fnm=docname, loader=loader)
        case &quot;--set&quot;:
          i=i+1
          val = sys.argv[i]
          items = val.split(&quot;=&quot;)
          name = items[0]
          value = items[1]
          print(&quot;setting &quot; + name + &quot;=&gt;&quot; + value)
          
          user_props = Info.get_user_defined_props(doc) # XPropertyContainer
          ps = Lo.qi(XPropertySet, user_props, True)
          
          try:
            ps.setPropertyValue(name, value)
          except Exception:
            pa = Lo.qi(XPropertyAccess, user_props, True)
            names = []
            for propertyvalue in pa.getPropertyValues():
              names.append(propertyvalue.Name)
            print (&quot;Cannot set property &#39;&quot; + name + &quot;&#39;. Known properties are &quot;, names)
            return 1
        case &quot;--save&quot;:
          i=i+1
          docname = sys.argv[i]
          print(&quot;saving &quot; + docname)
          Lo.save_doc(doc=doc, fnm=docname)
        case _:
          print (i, sys.argv[i])
      i=i+1
    return 0
  
if __name__ == &quot;__main__&quot;:
    raise SystemExit(main())

Finally run the code like this:

convert.py --load mydoc.odt --set propname=propvalue -save mydoc.pdf

Be aware you can use all the options multiple times and they are evaluated from left to right.
That means you can load a document, set multiple properties, save it into two output documents, load the next…

huangapple
  • 本文由 发表于 2023年6月15日 15:36:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定