Skip to content

Assertion fails when adding metadata after cloning document root #3036

@juwu-odoo

Description

@juwu-odoo

What Happened?

Hello, we are using pypdf at Odoo to generate pdf invoices, but we've been encountering an error when using the latest versions when attempting to run add_metadata() after clone_reader_document_root() which seems to be a bug.

Please see a reference discussion here: odoo/odoo#185673

Environment

$ python -m platform
Linux-6.8.0-51-generic-x86_64-with-glibc2.35

$ python -c "import pypdf;print(pypdf._debug_versions)"
pypdf==5.1.0, crypt_provider=('cryptography', '3.4.8'), PIL=9.0.1

Happens with pypdf==5.0.0 as well.

Code + PDF

import pypdf

r = pypdf.PdfReader('INV_2025_00010.pdf')
w = pypdf.PdfWriter()
w.clone_reader_document_root(r)
w.add_metadata({"/foo": "bar"})

PDF file: INV_2025_00010.pdf

Traceback

Traceback (most recent call last):
  File "/home/odoo/git/pypdf-test/test.py", line 6, in <module>
    w.add_metadata({"/foo": "bar"})
  File "/home/odoo/work/multiverse/venvs/17.0/lib/python3.10/site-packages/pypdf/_writer.py", line 1620, in add_metadata
    assert isinstance(self._info, DictionaryObject)
AssertionError

Notes

pypdf 5.0.0 introduced a line in clone_reader_document_root which deletes _info_obj from the writer:
a790532#diff-a0fbeffe546f1499bac6a87052eb32cf536be2731684405ef6bb0266a6a4da5dR1202

An assertion then fails when later adding metadata, causing the traceback since self._info = None:

assert isinstance(self._info, DictionaryObject)

@xmo-odoo and I's best guess is that add_metadata() should have been updated to handle a possible self._info = None (and/or initialize it) with the change introduced in 5.0.0.

Metadata

Metadata

Assignees

No one assigned

    Labels

    PdfWriterThe PdfWriter component is affectedis-regressionRegression introduced as a side-effect of another change

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions