Skip to content

Commit

Permalink
[IMP] pdf_helper: add pdf_embed_xml
Browse files Browse the repository at this point in the history
  • Loading branch information
jbaudoux committed Dec 22, 2023
1 parent 0329fc5 commit 18c7456
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pdf_helper/models/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
# Copyright 2023 Jacques-Etienne Baudoux (BCIM) <[email protected]>
# 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

Expand All @@ -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()
2 changes: 2 additions & 0 deletions pdf_helper/readme/USAGE.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions pdf_helper/tests/test_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"<root>test</root>"
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))

0 comments on commit 18c7456

Please sign in to comment.