简体   繁体   English

创建一个 pdf 文件,写入其中并使用 PyMuPDF 返回其字节 stream

[英]Create a pdf file, write in it and return its byte stream with PyMuPDF

Using PyMuPDF, I need to create a PDF file, write some text into it, and return its byte stream.使用 PyMuPDF,我需要创建一个 PDF 文件,向其中写入一些文本,并返回其字节 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?有没有一种方法可以创建一个 PDF 文件,在其中写入一些文本,然后在不使用文件系统的情况下返回其字节 stream?

Checking save() I found write() which gives it directly as bytes检查save()我发现write()直接将其作为字节提供

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM