一个将把py3o.template转换为最终libreoffice文档的fusion服务器

py3o.fusion的Python项目详细描述


简介

py3o.fusion是一个提供简单但重要服务的web服务器:

  • transform your py3o.template LibreOffice templates into final LibreOffice documents.
  • transform OpenOffice / LibreOffice documents to any supported format

基本上,您可以将模板化的openoffice/libreoffice文档融合到任何 支持的格式(odt、doc、docx、pdf)

这是为了避免在您自己的应用程序中直接依赖。 这也为其他编程打开了py3o生态系统的大门。 语言胜于python。

展开

我们建议使用我们创建的Docker图像。这是目前为止最快的 以获得一个完整的转换服务和运行没有麻烦。

只需按照我们页面上的说明docker hub

使用它

你可以使用任何语言。

下面是最简单的例子:

# import the wonderful requests lib
# if you need to intall it just try
# pip install --upgrade requests
import requests

# define where is your py3o.fusion endpoint
url = 'http://localhost:8765/form'

# open up the file and stuff it into a dictionary
# tmpl_file is a required field on the form. If you don't give
# it to the endpoint you'll receive an error back from it.
files = {
    'tmpl_file': open('templates/simple.odt', 'rb')
}

# then prepare the other fields of the form
# those 3 fields are also mandatory and failing to POST
# one of them will get you an error back from the server
#
# In this example you can see we leave the datadictionary
# and the image_mapping empty... This is because we won't
# send a template to the server but a simple plain
# old ODT file
fields = {
    "targetformat": 'pdf',
    "datadict": "{}",
    "image_mapping": "{}",
}

# finally POST our request on the endpoint
r = requests.post(url, data=fields, files=files)

# don't forget to close our orginal odt file
files['tmpl_file'].close()

# see if it is a success or a failure
# ATM the server only returns 400 errors... this may change
if r.status_code == 400:
    # server says we have an error...
    # this means it properly catched the error and nicely
    # gave us some info in a JSON answer...
    # let's use this fact
    print r.json()

else:
    # if we're here it is because we should receive a new
    # file back

    # let's stream the file back here...
    chunk_size = 1024

    # fusion server will stream an ODT file content back
    outname = 'request_out.%s' % 'pdf'
    with open(outname, 'wb') as fd:
        for chunk in r.iter_content(chunk_size):
            fd.write(chunk)

    # warn our dear user his file is ready
    print "Your file: %s is ready" % outname

抓住完整的odt2pdf.py source from hereexample ODT from here这是一种一步完成的方法:

$ mkdir -p templates && wget https://bitbucket.org/faide/py3o.fusion/raw/055770694c0c4c1593aed156149d2d43a6042913/py3o/fusion/static/examples/odt2pdf.py && wget https://bitbucket.org/faide/py3o.fusion/src/6817b8bde3895434ed1997b07a1c422e66c033b3/py3o/fusion/static/examples/templates/simple.odt && mv simple.odt templates/

下面是一个更复杂的示例,它使用py3o.template将一个数据字典融合到一个模板化的odt中,并返回结果pdf。您将注意到,您还可以覆盖模板中的图像:

# you'll need to install requests to make this example work
# pip install --upgrade requests
# should do the trick
import requests
import json

# point the client to your own py3o.fusion server
url = 'http://localhost:8765/form'

# target formats you want... can be ODT, PDF, DOC, DOCX
targetformats = ["odt", "pdf", "doc", "docx"]


class MyEncoder1(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Item):
            obj = obj._asdict()
        else:
            obj = super(MyEncoder1, self).default(obj)

        return obj


class Item(object):
    def _asdict(self):
        return self.__dict__


items = list()

item1 = Item()
item1.val1 = 'Item1 Value1'
item1.val2 = 'Item1 Value2'
item1.val3 = 'Item1 Value3'
item1.Currency = 'EUR'
item1.Amount = '12345.35'
item1.InvoiceRef = '#1234'
items.append(item1)

for i in xrange(1000):
    item = Item()
    item.val1 = 'Item%s Value1' % i
    item.val2 = 'Item%s Value2' % i
    item.val3 = 'Item%s Value3' % i
    item.Currency = 'EUR'
    item.Amount = '6666.77'
    item.InvoiceRef = 'Reference #%04d' % i
    items.append(item)

document = Item()
document.total = '9999999999999.999'

data = dict(items=items, document=document)

data_s = json.dumps(data, cls=MyEncoder1)

for targetformat in targetformats:
    # open the files you need
    files = {
        'tmpl_file': open('templates/py3o_example_template.odt', 'rb'),
        'staticimage.img_logo': open('images/new_logo.png', 'rb'),
    }

    # fusion API needs those 3 keys
    fields = {
        "targetformat": targetformat,
        "datadict": data_s,
        "image_mapping": json.dumps({"staticimage.img_logo": "logo"}),
    }

    # and it needs to receive a POST with fields and files
    r = requests.post(url, data=fields, files=files)

    # TODO: handle error codes
    if r.status_code == 400:
        # server says we have a problem...
        # let's give the info back to our human friend
        print r.json()

    else:
        chunk_size = 1024
        # fusion server will stream an ODT file content back
        ext = targetformat.lower()
        with open('request_out.%s' % ext, 'wb') as fd:
            for chunk in r.iter_content(chunk_size):
                fd.write(chunk)

    files['tmpl_file'].close()
    files['staticimage.img_logo'].close()

还有,瞧。您有一个名为out.odt的文件,其中包含最终的odt 与你的数据字典相连接。

对于完整的源代码+模板文件和图片只需下载 它们来自our repo

如果你只想快速测试它,你也可以指向你的浏览器 到服务器http://localhost:8765/form并手动填写表单。

更改日志

2018年7月8日0.8.9

  • Added support for PDF export options
  • fixed the -s command line option

0.8.8 2018年4月11日

  • added a command line option (-s) to only listen on a certain network interface (thanks to Alexis de Lattre)

0.8.7 2017年4月5日

  • introduced form options to be able to control False values escaping and undefined variables escaping

2016年11月29日0.8.6

  • Added py3o.types as a dependency
  • Updated the example odt

0.8.2 2015年6月26日

  • Added new formats (py3o.formats) support instead of using hard coded values, compatible with old formats so clients don’t have to adapt their code
  • Added more information on the form page about the currently supported formats. The information is computed dynamically and takes into account if you have a renderserver or not.
  • Added a server version in the footer.

2015年6月3日0.8

  • bugfix release to fix regression introduced in 0.7 concerning allowed formats calculation in case a renderserver is present. All 0.7 users wishing to use a renderserver (ie: produce non-native formats) should upgrade to 0.8

2015年6月2日0.7

  • Internal refactoring that also changes public API, formats are now handled using py3o.formats instead of using internal functions. This changes format names the user must provide to be lower case instead of upper case. See https://bitbucket.org/faide/py3o.formats for more information about all the supported formats and their names.

5月6日。2015年29日

  • Now gracefully handle case when the caller does not provide an json payload

0.5摄氏度。2014年15日

  • Added better logs (datetime, level, module, message)
  • Fixed rendering of non native formats broken by the skipflag

2014年10月14日0.4

  • Added syntax coloration on features page
  • Added a new keyword to the POST options to skip the fusion step (ie: py3o.template -> plain odt). This is because in some case you only want to transform an already existing ODT file to some target format.

2014年9月12日0.3

  • Added examples that can be downloaded from the feature page of the server itself.

2014年9月11日0.2

  • Fixed an error case when the caller specified an invalid image mapping. The error was catched on the server but not sent back the the client.

2014年9月11日

  • Initial release

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Maven无法识别安装在Ubuntu外壳上的$java_HOME jdk   java如何防止可运行程序在其中一个抛出异常时执行   java Listview在按下项时不触发   如何在WindowsPhone8中使用JavaRESTWebService?   java在spring引导下使用多个dispatcher servlet/web上下文   java为什么在删除容器的绝对大小时不绘制GEF子项?   java在hibernate实体中保留DB约束是好的   JavaSpring选择最高优先级bean   ArrayList<Class>java字符串[]   有向加权边图的Java邻接表实现   字母数字字符串的java Tesseract配置:混合2、Z、6和G   如果输入为空,则带有EditText的java警报对话框将关闭   jsp上的java Struts 2动作响应   java获取IndexOutOfBundException Android   scala AWSJAVASDK:解压缩大小必须小于262144000字节