DEV Community

Cover image for Closing PDF Documents Safely with PyMuPDF
PDF Python Hub
PDF Python Hub

Posted on Originally published at payhip.com

Closing PDF Documents Safely with PyMuPDF

doc.close() closes a PDF document that you previously opened with PyMuPDF.

What does doc.close() do?

doc.close():

  • Releases resources and memory associated with the document.
  • Closes the document and its underlying resources.
  • Makes the Document object unavailable for further document operations.

When should you use it?

Use doc.close() when you are finished working with a PDF, especially when:

  • You created or modified a PDF.
  • You are processing many PDFs in a loop.
  • You want to make sure the document is no longer being held open.

Important: After calling doc.close(), you can no longer work with the document. Attempting to perform operations on a closed document can raise: ValueError: document closed

If you need to work with the PDF again, you can open it with pymupdf.open():

doc = pymupdf.open("sample.pdf")
Enter fullscreen mode Exit fullscreen mode

This creates a new Document object that you can work with normally.

Should you save the PDF document before closing it?

If you modified the PDF, save it before closing it.

For example:

doc.save("sample.pdf")
Enter fullscreen mode Exit fullscreen mode

If you close a modified document without saving it, your changes may be lost.

doc.close() does not save your changes.


Open the notebook

Open the Google Colab notebook for this PDF mini-guide and run the code as you follow along.

[Open in Google Colab]


To open a PDF file with PyMuPDF, check out this mini-guide: Open Your First PDF with PyMuPDF.

Top comments (0)