Passed
Push — main ( d01715...bf48fe )
by Sat CFDI
04:49
created

satcfdi.render.pdf_write()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 3
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 0
b 0
f 0
1 1
from collections.abc import Sequence
2 1
from lxml.etree import QName
3
4 1
from .environment import DefaultCFDIEnvironment
5 1
from ..xelement import XElement
6
7 1
try:
8 1
    import weasyprint
9
10 1
    PDF_CSS = weasyprint.CSS(string="@page {margin: 1.0cm 1.27cm 1.1cm 0.85cm;}")
11
except OSError as ex:
12
    weasyprint = None
13
14 1
PDF_INIT_TEMPLATE = DefaultCFDIEnvironment.get_template("_init.html")
15
16
17 1
def html_write(xlm: XElement | Sequence[XElement], target, init_template=PDF_INIT_TEMPLATE):
18 1
    if isinstance(xlm, Sequence):
19 1
        init_template.stream({"c": [(QName(a.tag).localname, a) for a in xlm], "k": '_multiple'}).dump(target)
20
    else:
21
        init_template.stream({"c": xlm, "k": QName(xlm.tag).localname}).dump(target)
22
23
24 1
def html_str(xlm: XElement | Sequence[XElement], init_template=PDF_INIT_TEMPLATE) -> str:
25 1
    if isinstance(xlm, Sequence):
26 1
        return init_template.render({"c": [(QName(a.tag).localname, a) for a in xlm], "k": '_multiple'})
27
    else:
28 1
        return init_template.render({"c": xlm, "k": QName(xlm.tag).localname})
29
30
31 1
def pdf_write(xlm: XElement | Sequence[XElement], target, init_template=PDF_INIT_TEMPLATE):
32 1
    if weasyprint is None:
33
        raise ImportError("weasyprint is not installed")
34
35 1
    weasyprint.HTML(string=html_str(xlm, init_template=init_template)).write_pdf(
36
        target=target,
37
        stylesheets=[PDF_CSS]
38
    )
39
40
41 1
def pdf_bytes(xlm: XElement | Sequence[XElement], init_template=PDF_INIT_TEMPLATE) -> bytes:
42
    if weasyprint is None:
43
        raise ImportError("weasyprint is not installed")
44
45
    return weasyprint.HTML(string=html_str(xlm, init_template=init_template)).write_pdf(
46
        stylesheets=[PDF_CSS]
47
    )
48