|
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
|
|
|
|
|
11
|
|
|
|
|
12
|
1 |
|
class Representable: |
|
13
|
1 |
|
tag = None |
|
14
|
|
|
|
|
15
|
1 |
|
def html_write(self, target, init_template=PDF_INIT_TEMPLATE): |
|
16
|
|
|
init_template.stream({"c": self, "k": QName(self.tag).localname}).dump(target) |
|
17
|
|
|
|
|
18
|
1 |
|
def html_str(self, init_template=PDF_INIT_TEMPLATE) -> str: |
|
19
|
1 |
|
return init_template.render({"c": self, "k": QName(self.tag).localname}) |
|
20
|
|
|
|
|
21
|
1 |
|
def pdf_write(self, target, init_template=PDF_INIT_TEMPLATE): |
|
22
|
1 |
|
if weasyprint is None: |
|
23
|
|
|
raise ImportError("weasyprint is not installed") |
|
24
|
|
|
|
|
25
|
1 |
|
weasyprint.HTML(string=self.html_str(init_template=init_template)).write_pdf( |
|
26
|
|
|
target=target, |
|
27
|
|
|
stylesheets=[PDF_CSS] |
|
28
|
|
|
) |
|
29
|
|
|
|
|
30
|
1 |
|
def pdf_bytes(self, init_template=PDF_INIT_TEMPLATE) -> bytes: |
|
31
|
|
|
if weasyprint is None: |
|
32
|
|
|
raise ImportError("weasyprint is not installed") |
|
33
|
|
|
|
|
34
|
|
|
return weasyprint.HTML(string=self.html_str(init_template=init_template)).write_pdf( |
|
35
|
|
|
stylesheets=[PDF_CSS] |
|
36
|
|
|
) |
|
37
|
|
|
|
|
38
|
1 |
|
@staticmethod |
|
39
|
1 |
|
def html_write_all(objs, target, init_template=PDF_INIT_TEMPLATE): |
|
40
|
1 |
|
init_template.stream({"c": [(QName(a.tag).localname, a) for a in objs], "k": '_multiple'}).dump(target) |
|
41
|
|
|
|
|
42
|
1 |
|
@staticmethod |
|
43
|
1 |
|
def html_str_all(objs, init_template=PDF_INIT_TEMPLATE) -> str: |
|
44
|
1 |
|
return init_template.render({"c": [(QName(a.tag).localname, a) for a in objs], "k": '_multiple'}) |
|
45
|
|
|
|
|
46
|
1 |
|
@staticmethod |
|
47
|
1 |
|
def pdf_write_all(objs, target, init_template=PDF_INIT_TEMPLATE): |
|
48
|
|
|
if weasyprint is None: |
|
49
|
|
|
raise ImportError("weasyprint is not installed") |
|
50
|
|
|
|
|
51
|
|
|
weasyprint.HTML(string=Representable.html_str_all(objs, init_template=init_template)).write_pdf( |
|
52
|
|
|
target=target, |
|
53
|
|
|
stylesheets=[PDF_CSS] |
|
54
|
|
|
) |
|
55
|
|
|
|
|
56
|
1 |
|
@staticmethod |
|
57
|
1 |
|
def pdf_bytes_all(objs, init_template=PDF_INIT_TEMPLATE) -> bytes: |
|
58
|
|
|
if weasyprint is None: |
|
59
|
|
|
raise ImportError("weasyprint is not installed") |
|
60
|
|
|
|
|
61
|
|
|
return weasyprint.HTML(string=Representable.html_str_all(objs, init_template=init_template)).write_pdf( |
|
62
|
|
|
stylesheets=[PDF_CSS] |
|
63
|
|
|
) |
|
64
|
|
|
|