From 18c74568295b0ed295847b922bc23224bf549509 Mon Sep 17 00:00:00 2001 From: Jacques-Etienne Baudoux Date: Fri, 22 Dec 2023 17:26:13 +0100 Subject: [PATCH] [IMP] pdf_helper: add pdf_embed_xml --- pdf_helper/models/helper.py | 13 +++++++++++++ pdf_helper/readme/USAGE.rst | 2 ++ pdf_helper/tests/test_helper.py | 12 ++++++++++++ 3 files changed, 27 insertions(+) diff --git a/pdf_helper/models/helper.py b/pdf_helper/models/helper.py index cc34487d90..81061915fa 100644 --- a/pdf_helper/models/helper.py +++ b/pdf_helper/models/helper.py @@ -3,9 +3,11 @@ # Copyright 2023 Jacques-Etienne Baudoux (BCIM) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). +import io import logging from odoo import api, models +from odoo.tools.pdf import OdooPdfFileReader, OdooPdfFileWriter from ..utils import PDFParser @@ -31,3 +33,14 @@ def pdf_get_xml_files(self, pdf_file): except parser.get_xml_files_swallable_exceptions() as err: _logger.error("PDF file parsing failed: %s", str(err)) return {} + + @api.model + def pdf_embed_xml(self, pdf_content, xml_filename, xml_string): + """Add an XML attachment in a pdf""" + with io.BytesIO(pdf_content) as reader_buffer, io.BytesIO() as new_pdf_stream: + reader = OdooPdfFileReader(reader_buffer, strict=False) + writer = OdooPdfFileWriter() + writer.cloneReaderDocumentRoot(reader) + writer.addAttachment(xml_filename, xml_string, subtype="text/xml") + writer.write(new_pdf_stream) + return new_pdf_stream.getvalue() diff --git a/pdf_helper/readme/USAGE.rst b/pdf_helper/readme/USAGE.rst index 4cee3e9dbb..a90789e211 100644 --- a/pdf_helper/readme/USAGE.rst +++ b/pdf_helper/readme/USAGE.rst @@ -2,6 +2,8 @@ Inside Odoo env:: res = env["pdf.helper"].pdf_get_xml_files(pdf_filecontent) + new_pdf_filecontent = env["pdf.helper"].pdf_embed_xml(pdf_filecontent, filename, xml) + Outside Odoo env:: from odoo.addons.pdf_helper.utils import PDFParser diff --git a/pdf_helper/tests/test_helper.py b/pdf_helper/tests/test_helper.py index dc9360139c..3aa0c6e189 100644 --- a/pdf_helper/tests/test_helper.py +++ b/pdf_helper/tests/test_helper.py @@ -43,3 +43,15 @@ def test_get_xml_fail(self): "PDF file parsing failed: Cannot read an empty file", log_catcher.output[0], ) + + def test_embed_xml(self): + pdf_content = read_test_file("pdf_with_xml_test.pdf", mode="rb") + filename = "test" + xml = b"test" + newpdf_content = self.env["pdf.helper"].pdf_embed_xml( + pdf_content, filename, xml + ) + attachments = self.env["pdf.helper"].pdf_get_xml_files(newpdf_content) + self.assertTrue(filename in attachments) + etree_content = attachments[filename] + self.assertEqual(xml, etree.tostring(etree_content))