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