1

I want to store a PDF file in my MongoDB database (In Ubuntu) with with PYMonbgo and gridfs. But I am receiving the error 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte

How can I store and receive a PDF with python in MongoDB?

from pymongo import MongoClient
import gridfs

db = MongoClient('mongodb://localhost:27017/').myDB
fs = gridfs.GridFS( db )
fileID = fs.put( open(('Test.pdf')  ))
out = fs.get(fileID)

1 Answer 1

5

You need to encode the PDF appropriately after reading. I won't pretend to understand the details. But I have gotten it to work. Try this, see if it works for you too. (FYI, Might want to also specify the collection)

import base64
import gridfs

def write_new_pdf(path):
    db = MongoClient('mongodb://localhost:27017/').myDB
    fs = gridfs.GridFS(db)
    # Note, open with the "rb" flag for "read bytes"
    with open(path, "rb") as f:
        encoded_string = base64.b64encode(f.read())
    with fs.new_file(
        chunkSize=800000,
        filename=path) as fp:
        fp.write(encoded_string)

Updaate: How to read the pdf back

def read_pdf(filename):
    # Usual setup
    db = MongoClient('mongodb://localhost:27017/').myDB
    fs = gridfs.GridFS(db)
    # Standard query to Mongo
    data = fs.find_one(filter=dict(filename=filename))
    with open(filename, "wb") as f:
        f.write(base64.b64decode(data.read()))
3
  • Do you know how I can receive this "Test.pdf" back from my "myDB" collection by just passing the file name "Test.pdf" to a function? Commented Oct 2, 2019 at 6:09
  • 2
    I think that will work. Shout if it doesn't. A little busy atm but can look later.
    – Neil
    Commented Oct 2, 2019 at 10:10
  • What do I do If I need to extract text from the PDF extracted and not save it in my PC? Commented May 18, 2021 at 19:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.