0

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.

4

1 回答 1

1

您需要将 pdf 内容字节作为Body参数传递

蟒蛇2

dir = 'my-dir-name'
file = 'test.pdf'
s3.Bucket(my_bucket).put_object(Key=dir+'/'+file, Body=pdf.output(file, 'S'))

蟒蛇3

dir = 'my-dir-name'
file = 'test.pdf'
s3.Bucket(my_bucket).put_object(Key=dir+'/'+file, Body=pdf.output(file, 'S').encode('latin-1'))

注意:在 Python 2 中,字符串是原始数据,但在 Python 3 中,字符串现在默认是 unicode。如果您使用的是 Python 3.x,则必须使用 pdf.output(dest='S').encode('latin-1') 才能获得输出,如果不这样做,生成的 PDF 将是无效,并且取决于查看器,要么根本不打开,要么显示为一些空白页

文件:pdf.output()

于 2021-10-15T13:51:50.187 回答