I have FPDF object like this below:
import fpdf
pdf = FPDF()
#Cover page
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
pdf.cell(175, 10, 'TEST - report',0,1,'C')
And I try to save this FPDF object to my S3 bucket inside AWS. I am using jupyter notebook on EMR. When I run this:
my_bucket = 'my-bucket-name'
s3 = boto3.resource('s3')
dir = 'my-dir-name'
file = dir 'test.pdf'
s3.Bucket(my_bucket).put_object(Key=file, Body=pdf)
I got error:
ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value: <fpdf.fpdf.FPDF object at 0x7f2dfc2acd10>, type: <class 'fpdf.fpdf.FPDF'>, valid types: <class 'bytes'>, <class 'bytearray'>, file-like object
Do you know how to handle it?
Thanks for any ideas.
CodePudding user response:
You need to pass pdf content bytes as the Body
param
python2
dir = 'my-dir-name'
file = 'test.pdf'
s3.Bucket(my_bucket).put_object(Key=dir '/' file, Body=pdf.output(file, 'S'))
python3
dir = 'my-dir-name'
file = 'test.pdf'
s3.Bucket(my_bucket).put_object(Key=dir '/' file, Body=pdf.output(file, 'S').encode('latin-1'))
NOTICE: In Python 2 strings were raw data but in Python 3 strings are now unicode by default. If you are using Python 3.x you have to use pdf.output(dest='S').encode('latin-1') in order to get the output, if you don't do so the generated PDF will be invalid and depending on the viewer either not open at all or show up as some blank pages
document: pdf.output()