3

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?

2
  • 1
    I think this problem already was on Stackoverflow - if save() accepts file-like object or file-handler then you can use io.BytesIO in save() Commented Jan 28, 2021 at 23:46
  • 1
    BTW: using filesystem you can write it much simpler return open(path, "rb").read() Commented Jan 28, 2021 at 23:49

1 Answer 1

7

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.