如何在 MySQL 数据库中存储 PDF 而不在 Python 中生成 PDF 文件

How to store PDF in MySQL database without generating PDF file in Python

所以基本上我在 MySQL 数据库中有一个 base64 编码的 PDF 数据,我想操作该数据(更新 PDF 文件数据的表单字段),之后没有 creating/Write PDF我想将该 manipulated/updated 数据存储到数据库中。 Python 代码如下。

这里我使用的是 PyPDF2,代码可以正常工作

import base64, io, PyPDF2

try:
    data_dict = '{"firstName": "John", "lastName": "Joe"}'
    encodedDataOfPDF = base64.b64decode(data)  #base64 encoded data of pdf from database

    file = io.BytesIO(encodedDataOfPDF)
    pdfReader = PyPDF2.PdfFileReader(file)
    pdfWriter = PyPDF2.PdfFileWriter()
    pdfWriter.appendPagesFromReader(pdfReader)

    #Here form fields of PDF gets updated.
    pdfWriter.updatePageFormFieldValues(pdfWriter.getPage(0), data_dict)  


    #If I uncomment below code then it will create a PDF file with updated data.
    #But I Don't want a PDF File, 
    #I just need the base64 encoded data of that updated/manipulated file which I will store in the Database.

    # with open(data[1], 'wb') as f:
    #     pdfWriter.write(f)


except Exception as e:
    app.logger.info(str(e))

注意:请同时阅读代码中的注释

提前致谢。

经过大量研究,我终于找到了获取被称为流的 updated/manipulated 编码数据的正确方法。

import base64, io, PyPDF2

try:
    tempMemory = io.BytesIO() #Added BytesIO
    data_dict = '{"firstName": "John", "lastName": "Joe"}'
    encodedDataOfPDF = base64.b64decode(data)  #base64 encoded data of pdf from database

    file = io.BytesIO(encodedDataOfPDF)
    pdfReader = PyPDF2.PdfFileReader(file)
    pdfWriter = PyPDF2.PdfFileWriter()
    pdfWriter.appendPagesFromReader(pdfReader)

    #Here form fields of PDF gets updated.
    pdfWriter.updatePageFormFieldValues(pdfWriter.getPage(0), data_dict)  

    pdfWriter.write(tempMemory)
    newFileData = tempMemory.getvalue()
    newEncodedPDF= base64.b64encode(newFileData) # Here I get what I want.


except Exception as e:
    app.logger.info(str(e))

我在没有生成 PDF 文件的情况下获得了 base64 编码数据。

谢谢