factur-x
factur-x copied to clipboard
Bookmarks are removed from the original pdf file
When using generate_facturx_from_file on a pdf file with bookmarks, those are removed.
Here a solution that worked for me 1- Collect the outlines from the original pdf file 2- generate facturx xml 3- Restore the outlines
def _collect_outlines(self, pdf_file):
"""
Collect the first level outlines of the given pdf document
:param obj pdf_file: A buffer containing the generated pdf
:returns: A list of 2-uple [(title, destination_page)]
"""
reader = PdfFileReader(pdf_file)
toctree = []
for outline in reader.getOutlines():
if isinstance(outline, Destination):
page = reader.getDestinationPageNumber(outline)
toctree.append((outline.title, page))
return toctree
def _restore_toctree(self, pdf_file, toctree):
"""
Restore the outlines of the original document into the pdf generated by
facturex
"""
writer = PdfFileWriter()
reader = PdfFileReader(pdf_file)
# Here we copy the data from the facturex populated pdf file to the
# writer before adding bookmarks
# NOTE: PyPDF4 clone methods doesn't work as is, this is a solution
# that work
writer.cloneReaderDocumentRoot(reader)
for rpagenum in range(0, reader.getNumPages()):
writer.addPage(reader.getPage(rpagenum))
# Add the bookmarks
for title, page in toctree:
writer.addBookmark(title, page)
writer.write(pdf_file)
return writer
def render(self):
....
# NOTE:
# store the bookmarks (outlines) of the generated pdf to restore it
# after generating facturx pdf file
# See https://github.com/akretion/factur-x/issues/20
outlines = self._collect_outlines(pdf_file)
generate_facturx_from_file(pdf_file, self._get_facturx_xml())
self._restore_outlines(pdf_file, outlines)
Hope this can help
Fixed in release 3.1 ! Cf my last (big) commit !
Thanks a lot !!