Using PyMuPDF, I need to create a PDF file, write some text into it, and return its byte stream.
This is the code I have, but it uses the filesystem to create and save the file:
import fitz
path = "PyMuPDF_test.pdf"
doc = fitz.open()
page = doc.newPage()
where = fitz.Point(50, 100)
page.insertText(where, "PDF created with PyMuPDF", fontsize=50)
doc.save(path) # Here Im saving to the filesystem
with open(path, "rb") as file:
return io.BytesIO(file.read()).getvalue()
Is there a way I can create a PDF file, write some text in it, and return its byte stream without using the filesystem?
Checking save() I found write() which gives it directly as bytes
import fitz
#path = "PyMuPDF_test.pdf"
doc = fitz.open()
page = doc.newPage()
where = fitz.Point(50, 100)
page.insertText(where, "PDF created with PyMuPDF", fontsize=50)
print(doc.write())
EDIT: 2025.03
It seems they change something in module.
I can't find write()
in documentation but doc.write()
still works.
But in documentation there is new function tobytes() for this.
And save() can work with file-like object
so it can use io.BytesIO()
import fitz
print('version:', fitz.__version__) # 1.25.3
doc = fitz.open()
page = doc.new_page() # newPage()
where = fitz.Point(50, 100)
page.insert_text(where, "PDF created with PyMuPDF", fontsize=50)
print('\n--- version 1 - write() ---\n')
print(doc.write())
print('\n--- version 2 - tobytes() ---\n')
print(doc.tobytes())
print('\n--- version 3 - io.BytesIO().getvalue() ---\n')
import io
file_like_object = io.BytesIO()
doc.save(file_like_object)
print(file_like_object.getvalue())