Search code examples
pythonpymupdf

mupdf: Can't do incremental writes when changing encryption


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

Solution

  • 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.