0

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?

Xar
  • 7,572
  • 19
  • 56
  • 80
  • 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()` – furas Jan 28 '21 at 23:46
  • 1
    BTW: using filesystem you can write it much simpler `return open(path, "rb").read()` – furas Jan 28 '21 at 23:49

1 Answers1

2

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())
furas
  • 134,197
  • 12
  • 106
  • 148