2

I'm trying to add table of contents to the pdf using fitz package.

Here's my script

doc = fitz.open(path)
bookmarks = [[1, 'INTRODUCTION', 1], [1, 'MANUSCRIPT COMPONENTS', 1], [1, 'MULTIMEDIA FIGURES – VIDEO AND AUDIO FILES', 2], [1, 'MATHEMATICAL EQUATIONS', 3], [1, 'USING THIS TEMPLATE AND ITS AUTOMATIC FORMATTING', 3]]
doc.setToC(bookmarks) # o/p -> 5
doc.save(doc.name, incremental=True) # to save the document with added bookmarks/table of contents
# above line gives the error

Here is the Stack trace

>>> doc.save(doc.name, incremental=True)
mupdf: Can't do incremental writes when changing encryption
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "E:\BookmarkPDF\pdfenv\lib\site-packages\fitz\fitz.py", line 4270, in save
    return _fitz.Document_save(
RuntimeError: Can't do incremental writes when changing encryption
Venkatesh Dharavath
  • 500
  • 1
  • 5
  • 18

3 Answers3

1

Resolved it using lower version of PYmuPDF. pip install PyMuPDF==1.14.20

1

doc.save() uses encryption=PDF_ENCRYPT_NONE by default (see documentation here). Your document must have some type of encryption, which doc.save is attempting to remove (i.e. change to none).

Knowing this, the error is self explanatory: fitz cannot save incrementally and change the encryption.

You expressed no desire to change encryption in your question/code, so you can specify to keep it.

To do this, you can use:

 doc.save(doc.name, incremental=True, encryption=PDF_ENCRYPT_KEEP).

Or you can also use doc.saveIncr() as a convenience abbreviation (see here for docs).

zephel
  • 135
  • 1
  • 8
1

For PyMyPDF==1.18.17

PDF encryption method codes no longer works, you would have to use the following to method. Please refer to the code below.

doc = fitz.open(path)
bookmarks = [[1, 'INTRODUCTION', 1], [1, 'MANUSCRIPT COMPONENTS', 1], [1, 'MULTIMEDIA FIGURES – VIDEO AND AUDIO FILES', 2], [1, 'MATHEMATICAL EQUATIONS', 3], [1, 'USING THIS TEMPLATE AND ITS AUTOMATIC FORMATTING', 3]]
doc.setToC(bookmarks) # o/p -> 5
doc.save(doc.name, incremental=True, encryption=0) 

You would have to give encryption the value of 0 which apperantly fixed the issue for me.

Salman.S
  • 76
  • 2
  • 9