-1

I have some plots in my code, and I want them saved as Pdf in S3 storage from AWS.

Thuener
  • 1,359
  • 1
  • 13
  • 13
  • 1
    Appreciate that you try to provide content to SO but even questions+self-answers need to be proper questions, your is not. At least the `PdfPages` part needs to be part of the question and then the answer is just the s3 interaction part for which there are a ton of duplicates already. – luk2302 Feb 15 '21 at 10:41

1 Answers1

1

You have to convert everything using BytesIO. You can add as many plots as you want inside the looping using pp.savefig() or pp.savefig(fig). I'm assuming that you have already configured the credentials to authenticate in AWS.

import io
import boto3
from datetime import datetime
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import pyplot as plt

with io.BytesIO() as output:
    with PdfPages(output) as pp:
        fig, ax = plt.subplots(figsize=(12, 6))
        plt.plot([1,2,3,4,5,6],[1,2,3,4,5,6])
        pp.savefig()
    data = output.getvalue()
    
my_bucket = 'my-buketname'
s3 = boto3.resource('s3')
dir = 'my-dir-name'
file = dir + 'test.pdf'
s3.Bucket(my_bucket).put_object(Key=file, Body=data)
Thuener
  • 1,359
  • 1
  • 13
  • 13