在 Python 中将 FPDF 对象上传到 AWS S3

Upload FPDF object to AWS S3 in Python

我有如下所示的 FPDF 对象:

import fpdf

pdf = FPDF()

#Cover page
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
pdf.cell(175, 10, 'TEST - report',0,1,'C')

然后我尝试将此 FPDF 对象保存到我在 AWS 中的 S3 存储桶中。我在 EMR 上使用 jupyter notebook。 当我 运行 这个:

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)

我收到错误:

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

你知道怎么处理吗?

感谢任何想法。

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

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

文件:pdf.output()