How to use the docxtpl.DocxTemplate function in docxtpl

To help you get started, we’ve selected a few docxtpl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github elapouya / python-docx-template / tests / horizontal_merge.py View on Github external
# -*- coding: utf-8 -*-

from docxtpl import DocxTemplate

tpl = DocxTemplate('templates/horizontal_merge_tpl.docx')
tpl.render({})
tpl.save('output/horizontal_merge.docx')
github elapouya / python-docx-template / tests / header_footer_image_file_obj.py View on Github external
DEST_FILE = 'output/header_footer_image_file_obj.docx'
DEST_FILE2 = 'output/header_footer_image_file_obj2.docx'

tpl=DocxTemplate('templates/header_footer_image_tpl.docx')

context = {
    'mycompany' : 'The World Wide company',
}

dummy_pic = io.BytesIO(open('templates/dummy_pic_for_header.png', 'rb').read())
new_image = io.BytesIO(open('templates/python.png', 'rb').read())
tpl.replace_media(dummy_pic, new_image)
tpl.render(context)
tpl.save(DEST_FILE)

tpl = DocxTemplate('templates/header_footer_image_tpl.docx')
dummy_pic.seek(0)
new_image.seek(0)
tpl.replace_media(dummy_pic, new_image)
tpl.render(context)

file_obj = io.BytesIO()
tpl.save(file_obj)
file_obj.seek(0)
with open(DEST_FILE2, 'wb') as f:
    f.write(file_obj.read())
github elapouya / python-docx-template / tests / header_footer_utf8.py View on Github external
# -*- coding: utf-8 -*-
'''
Created : 2016-07-19

@author: AhnSeongHyun

Edited : 2016-07-19 by Eric Lapouyade
'''

from docxtpl import DocxTemplate

tpl=DocxTemplate('templates/header_footer_tpl_utf8.docx')

sd = tpl.new_subdoc()
p = sd.add_paragraph(u'This is a sub-document to check it does not break header and footer with utf-8 characters inside the template .docx')

context = {
    'title' : u'헤더와 푸터',
    'company_name' : u'세계적 회사',
    'date' : u'2016-03-17',
    'mysubdoc' : sd,
}

tpl.render(context)
tpl.save('output/header_footer_utf8.docx')
github elapouya / python-docx-template / tests / word2016.py View on Github external
from docxtpl import DocxTemplate, RichText

tpl = DocxTemplate('templates/word2016_tpl.docx')
tpl.render({
    'test_space' : '          ',
    'test_tabs': 5*'\t',
    'test_space_r' : RichText('          '),
    'test_tabs_r': RichText(5*'\t'),
})
tpl.save('output/word2016.docx')
github elapouya / python-docx-template / tests / template_error.py View on Github external
from docxtpl import DocxTemplate, RichText
from jinja2.exceptions import TemplateError
import six

six.print_('=' * 80)
six.print_("Generating template error for testing (so it is safe to ignore) :")
six.print_('.' * 80)
try:
    tpl = DocxTemplate('templates/template_error_tpl.docx')
    tpl.render({
        'test_variable' : 'test variable value'
    })
except TemplateError as the_error:
    six.print_(six.text_type(the_error))
    if hasattr(the_error, 'docx_context'):
        six.print_("Context:")
        for line in the_error.docx_context:
            six.print_(line)
tpl.save('output/template_error.docx')
six.print_('.' * 80)
six.print_(" End of TemplateError Test ")
six.print_('=' * 80)
github elapouya / python-docx-template / tests / inline_image.py View on Github external
# -*- coding: utf-8 -*-
'''
Created : 2017-01-14

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, InlineImage
# for height and width you have to use millimeters (Mm), inches or points(Pt) class :
from docx.shared import Mm, Inches, Pt
import jinja2
from jinja2.utils import Markup

tpl=DocxTemplate('templates/inline_image_tpl.docx')

context = {
    'myimage' : InlineImage(tpl,'templates/python_logo.png',width=Mm(20)),
    'myimageratio': InlineImage(tpl, 'templates/python_jpeg.jpg', width=Mm(30), height=Mm(60)),

    'frameworks' : [{'image' : InlineImage(tpl,'templates/django.png',height=Mm(10)),
                      'desc' : 'The web framework for perfectionists with deadlines'},

                    {'image' : InlineImage(tpl,'templates/zope.png',height=Mm(10)),
                     'desc' : 'Zope is a leading Open Source Application Server and Content Management Framework'},

                    {'image': InlineImage(tpl, 'templates/pyramid.png', height=Mm(10)),
                     'desc': 'Pyramid is a lightweight Python web framework aimed at taking small web apps into big web apps.'},

                    {'image' : InlineImage(tpl,'templates/bottle.png',height=Mm(10)),
                     'desc' : 'Bottle is a fast, simple and lightweight WSGI micro web-framework for Python'},
github elapouya / python-docx-template / tests / cellbg.py View on Github external
# -*- coding: utf-8 -*-
'''
Created : 2015-03-12

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, RichText

tpl=DocxTemplate('templates/cellbg_tpl.docx')

context = {
    'alerts' : [
        {'date' : '2015-03-10', 'desc' : RichText('Very critical alert',color='FF0000', bold=True), 'type' : 'CRITICAL', 'bg': 'FF0000' },
        {'date' : '2015-03-11', 'desc' : RichText('Just a warning'), 'type' : 'WARNING', 'bg': 'FFDD00' },
        {'date' : '2015-03-12', 'desc' : RichText('Information'), 'type' : 'INFO', 'bg': '8888FF' },
        {'date' : '2015-03-13', 'desc' : RichText('Debug trace'), 'type' : 'DEBUG', 'bg': 'FF00FF' },
    ],
}

tpl.render(context)
tpl.save('output/cellbg.docx')
github qzq1111 / flask-restful-example / app / api / report.py View on Github external
def word_write(generated_doc_path):
    # 模板路径文件夹
    template_path = current_app.config.get("REPORT_TEMPLATES")
    path = os.path.join(template_path, 'test.docx')

    # 读取指定位置的模板文件
    doc = DocxTemplate(path)
    # 渲染的内容
    context = {
        # 标题
        'title': "人员信息",
        # 表格
        'table': [
            {"name": "小李", "age": 11},
            {"name": "小张", "age": 21},
            {"name": "小张", "age": 20},
            {"name": "小张1", "age": 10},
            {"name": "小张2", "age": 30},
            {"name": "小张3", "age": 40},
        ],
        # 页眉
        'header': 'xxx公司人员信息管理',
        # 页脚
github adfinis-sygroup / document-merge-service / document_merge_service / api / engines.py View on Github external
def merge(self, data, buf):
        doc = DocxTemplate(self.template)

        doc.render(data, get_jinja_env())
        doc.save(buf)
        return buf
github GhostManager / Ghostwriter / ghostwriter / modules / reportwriter.py View on Github external
def generate_word_docx(self):
        """Generate a Word document for the current report."""
        # Generate the JSON for the report
        report_json = json.loads(self.generate_json())
        # Create Word document writer using the specified template file
        if self.template_loc:
            try:
                self.main_spenny_doc = DocxTemplate(self.template_loc)
            except Exception:
                raise
        else:
            raise
        # Prepare the `context` dict for the Word template rendering
        context = {}
        # Client information
        context['client'] = report_json['client']['full_name']
        context['client_short'] = report_json['client']['short_name']
        context['client_pocs'] = report_json['client']['poc'].values()
        # Assessment information
        context['assessment_name'] = report_json['project']['name']
        context['project_type'] = report_json['project']['project_type']
        context['company'] = settings.COMPANY_NAME
        context['company_pocs'] = report_json['team'].values()
        # Infrastructure information

docxtpl

Python docx template engine

LGPL-2.1
Latest version published 1 month ago

Package Health Score

79 / 100
Full package analysis