PDF document stays in use after closing (original) (raw)
I want to open an existing PDF file, update it and save it with a new name. Once the updated PDF is saved with a new name, I want to delete the existing / old PDF file. I am using insert_htmlbox() as one of the functions to update the PDF. My observation is that due to insert_htmlbox() the old file is remaining open and hence the os.remove() on old file is giving error.
Below is the code snippet I am using. PyMuPDF version = 1.23.21
import fitz
import os
oldfile = 'your-existing-or-old-filename.pdf'
newfile = 'your-new-filename.pdf'
css2 = """
@font-face {font-family: QuicksandFM; src: url(Quicksand-Regular.ttf);}
@font-face {font-family: QuicksandFM; src: url(Quicksand-Bold.ttf); font-weight: bold;}
body {font-family:QuicksandFM; font-size:9;}
"""
with fitz.open(oldfile) as doc: # open document
page = doc[0]
rect = fitz.Rect(130, 400, 430, 600)
CELLS = fitz.make_table(rect, cols=3, rows=5)
shape = page.new_shape() # create Shape
for i in range(5):
for j in range(3):
qtext = "<b>" + "Ques #" + str(i*3+j+1) + ": " + "</b>"
atext = "<b>" + "Ans:" + "</b>"
qtext = qtext + '<br>' + atext
shape.draw_rect(CELLS[i][j]) # draw rectangle
page.insert_htmlbox(CELLS[i][j], qtext, css=css2, scale_low=0)
shape.finish(width=2.5, color=fitz.pdfcolor["blue"], )
shape.commit() # write all stuff to the page
doc.subset_fonts()
doc.ez_save(newfile)
os.remove(oldfile)
Can this be fixed?