0

I'm working on a Python script that uses the PyMuPDF library to modify a PDF document and then save the modified content to a temporary PDF file. However, I'm encountering a "Permission denied" error when trying to write the content of the pdf file the temporary file. I've looked into various solutions, but I'm still stuck. Here's the simplified example of my code:

from tempfile import NamedTemporaryFile
import fitz

doc = fitz.open("test.pdf")

with NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file:
    temp_pdf_path = temp_file.name
    doc.save(temp_pdf_path)
    doc.close()

The error is:

Traceback (most recent call last): File "C:\Users\user\PycharmProjects\test\test.py", line 8, in doc.save(temp_pdf_path) File "C:\Users\user\PycharmProjects\test\venv\lib\site-packages\fitz\fitz.py", line 4629, in save return _fitz.Document_save(self, filename, garbage, clean, deflate, deflate_images, deflate_fonts, incremental, ascii, expand, linear, no_new_id, appearance, pretty, encryption, permissions, owner_pw, user_pw) RuntimeError: cannot remove file 'C:\Users\user\AppData\Local\Temp\tmp1ivvrwvj.pdf': Permission denied

Mazze
  • 383
  • 3
  • 13
  • This problem has nothing to do with PyMuPDF. You would see the same issue with anything else you would save like that. This is OS-related: works under Linux, but not under Windows - see Python documentation. – Jorj McKie Aug 12 '23 at 21:06
  • Use `from tempfile import gettempdir`, then `filename = os.path.join(gettempdir(), "test.pdf")` and save to this file. – Jorj McKie Aug 12 '23 at 21:13
  • thx that works. Turns out creating the temp file with `temp_file = NamedTemporaryFile(suffix=".pdf", delete=False)`, close it afterwards with `temp_file.close()` and then save to this file also works. – Mazze Aug 13 '23 at 16:10

0 Answers0