Skip to content

Commit

Permalink
add to_pdf helper
Browse files Browse the repository at this point in the history
  • Loading branch information
rvalyi committed Apr 1, 2024
1 parent 5d8b120 commit 1f05fa1
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
50 changes: 48 additions & 2 deletions nfelib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
from os import environ
from pathlib import Path
from typing import Any, Dict, List, Optional
from typing import Any, List, Optional

from lxml import etree
from xsdata.formats.dataclass.parsers import XmlParser
Expand Down Expand Up @@ -124,6 +124,36 @@ def sign_xml(
xml_etree = etree.fromstring(xml.encode("utf-8"))
return Assinatura(certificate).assina_xml2(xml_etree, doc_id)

@classmethod
def xmls_to_pdf(
self,
xml_list: List,
engine: str = "brazilfiscalreport",
image: Optional[str] = None, # (base64 image)
cfg_layout: str = "ICMS_IPI",
receipt_pos: str = "top",
) -> bytes:
"""Serialize a list of xmls strings (usually only one) to a pdf."""
xml_bytes_list = [
xml.encode() if isinstance(xml, str) else xml for xml in xml_list
]
if engine == "brazilfiscalreport":
try:
from brazilfiscalreport.pdf_docs import Danfe
except ImportError:
raise (RuntimeError("brazilfiscalreport package is not installed!"))
return Danfe(
xmls=xml_bytes_list,
image=image,
cfg_layout=cfg_layout,
receipt_pos=receipt_pos,
)
try:
from erpbrasil.edoc.pdf import base
except ImportError:
raise (RuntimeError("erpbrasil.edoc.pdf package is not installed!"))
return base.ImprimirXml.imprimir(string_xml=xml_bytes_list[0])

def to_xml(
self,
pretty_print: str = True,
Expand All @@ -143,7 +173,7 @@ def to_xml(
package = self._get_package()
ns_map = {None: f"http://www.portalfiscal.inf.br/{package}"}
xml = serializer.render(obj=self, ns_map=ns_map)
if doc_id:
if pkcs12_data:
return self.sign_xml(self, xml, pkcs12_data, pkcs12_password, doc_id=doc_id)
return xml

Expand All @@ -152,6 +182,22 @@ def validate_xml(self, schema_path: Optional[str] = None) -> List:
xml = self.to_xml()
return self.schema_validation(xml, schema_path)

def to_pdf(
self,
engine: str = "brazilfiscalreport",
image: Optional[str] = None, # (base64 image)
cfg_layout: str = "ICMS_IPI",
receipt_pos: str = "top",
pkcs12_data: Optional[bytes] = None,
pkcs12_password: Optional[str] = None,
doc_id: Optional[str] = None,
) -> bytes:
"""Serialize binding into pdf bytes."""
xml = self.to_xml()
if pkcs12_data:
xml = self.sign_xml(xml, pkcs12_data, pkcs12_password, doc_id)
return self.xmls_to_pdf([xml.encode()], engine, image, cfg_layout, receipt_pos)

# this was an attempt to keep the signature inside the
# binding before serializing it again. But at the moment it fails
# because xsdata will serialize the Signature elements with their namespaces.
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ test =
requests
beautifulsoup4
erpbrasil.assinatura
brazilfiscalreport

[flake8]
exclude = tests/*
Expand Down
17 changes: 17 additions & 0 deletions tests/nfe/test_nfe.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,23 @@ def test_sign(self):
# signed_xml2 = signed_nfe.to_xml(pretty_print=False)
# self.assertEqual(signed_xml, signed_xml2)

pdf_bytes = nfe.to_pdf(
sign=True,
pkcs12_data=cert_data,
pkcs12_password=cert_password,
element=nfe.NFe.infNFe.Id,
)
self.assertEqual(type(pdf_bytes), bytes)

def test_pdf(self):
path = os.path.join("nfelib", "nfe", "samples", "v4_0", "leiauteNFe")
filename = "42210775277525000178550030000266631762885493-procNFe.xml"
input_file = os.path.join(path, filename)
parser = XmlParser()
nfe = parser.from_path(Path(input_file))
pdf_bytes = nfe.to_pdf()
self.assertEqual(type(pdf_bytes), bytes)

def test_in_out_leiauteNFe(self):
path = os.path.join("nfelib", "nfe", "samples", "v4_0", "leiauteNFe")
for filename in os.listdir(path):
Expand Down

0 comments on commit 1f05fa1

Please sign in to comment.