1
|
1 |
|
from lxml.etree import QName |
2
|
|
|
|
3
|
1 |
|
try: |
4
|
1 |
|
import weasyprint |
5
|
1 |
|
PDF_CSS = weasyprint.CSS(string="@page {margin: 1.0cm 1.27cm 1.1cm 0.85cm;}") |
6
|
|
|
except OSError as ex: |
7
|
|
|
weasyprint = None |
8
|
|
|
|
9
|
1 |
|
from .render import PDF_INIT_TEMPLATE |
10
|
1 |
|
from .render.environment import CFDIEnvironment |
11
|
|
|
|
12
|
|
|
|
13
|
1 |
|
class Representable: |
14
|
1 |
|
tag = None |
15
|
|
|
|
16
|
1 |
|
def html_write(self, target, templates_path=None): |
17
|
|
|
if templates_path: |
18
|
|
|
env = CFDIEnvironment(templates_path=templates_path) |
19
|
|
|
init_template = env.get_template("_init.html") |
20
|
|
|
else: |
21
|
|
|
init_template = PDF_INIT_TEMPLATE |
22
|
|
|
|
23
|
|
|
init_template.stream({"c": self, "k": QName(self.tag).localname}).dump(target) |
24
|
|
|
|
25
|
1 |
|
def html_str(self, templates_path=None) -> str: |
26
|
1 |
|
if templates_path: |
27
|
1 |
|
env = CFDIEnvironment(templates_path=templates_path) |
28
|
1 |
|
init_template = env.get_template("_init.html") |
29
|
|
|
else: |
30
|
1 |
|
init_template = PDF_INIT_TEMPLATE |
31
|
|
|
|
32
|
1 |
|
return init_template.render({"c": self, "k": QName(self.tag).localname}) |
33
|
|
|
|
34
|
1 |
|
def pdf_write(self, target, templates_path=None): |
35
|
1 |
|
if weasyprint is None: |
36
|
|
|
raise ImportError("weasyprint is not installed") |
37
|
|
|
|
38
|
1 |
|
weasyprint.HTML(string=self.html_str(templates_path=templates_path)).write_pdf( |
39
|
|
|
target=target, |
40
|
|
|
stylesheets=[PDF_CSS] |
41
|
|
|
) |
42
|
|
|
|
43
|
1 |
|
def pdf_bytes(self, templates_path=None) -> bytes: |
44
|
|
|
if weasyprint is None: |
45
|
|
|
raise ImportError("weasyprint is not installed") |
46
|
|
|
|
47
|
|
|
return weasyprint.HTML(string=self.html_str(templates_path=templates_path)).write_pdf( |
48
|
|
|
stylesheets=[PDF_CSS] |
49
|
|
|
) |
50
|
|
|
|
51
|
1 |
|
@staticmethod |
52
|
1 |
|
def html_write_all(objs, target, templates_path=None): |
53
|
1 |
|
if templates_path: |
54
|
|
|
env = CFDIEnvironment(templates_path=templates_path) |
55
|
|
|
init_template = env.get_template("_multiple.html") |
56
|
|
|
else: |
57
|
1 |
|
init_template = PDF_INIT_TEMPLATE |
58
|
|
|
|
59
|
1 |
|
init_template.stream({"c": [(QName(a.tag).localname, a) for a in objs], "k": '_multiple'}).dump(target) |
60
|
|
|
|
61
|
1 |
|
@staticmethod |
62
|
1 |
|
def html_str_all(objs, templates_path=None) -> str: |
63
|
1 |
|
if templates_path: |
64
|
|
|
env = CFDIEnvironment(templates_path=templates_path) |
65
|
|
|
init_template = env.get_template("_multiple.html") |
66
|
|
|
else: |
67
|
1 |
|
init_template = PDF_INIT_TEMPLATE |
68
|
|
|
|
69
|
|
|
return init_template.render({"c": [(QName(a.tag).localname, a) for a in objs], "k": '_multiple'}) |
70
|
|
|
|