Skip to main content

How to Properly Close a PDF with PyMuPDF

Updated 2 min readMarkdown
How to Properly Close a PDF 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")

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

Should you save the PDF document before closing it?

If you've modified the PDF, make sure you save your changes to a new file before closing the document.

For example:

doc.save("modified.pdf")

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]


More PDF Python Resources

Want to learn how to open a PDF file?

Check out this mini-guide:

Open Your First PDF with PyMuPDF

About the author

  • PDF & Python Lab is dedicated to teaching PDF programming, automation, and engineering with Python through practical, project-based courses. Whether you're a complete beginner or an experienced Python developer, the goal is to help you build the skills needed to work with PDF documents confidently—from reading and extracting data to building enterprise document processing and AI-powered workflows. What You'll Learn The curriculum covers every stage of PDF processing, including: -PDF fundamentals -Document extraction -PDF manipulation -Forms, tables, and images -OCR and scanned documents -Security and redaction -Enterprise automation -AI-powered document processing How You'll Learn Every course is designed to be: -Beginner-friendly with clear, step-by-step explanations -Focused on practical, real-world applications -Built around hands-on projects and assessments -Structured as a complete learning path from beginner to expert

No comments yet. Be the first to comment.