Home > Software engineering >  AWS Object Lambda using PyPDF2 to send back encrypted PDF
AWS Object Lambda using PyPDF2 to send back encrypted PDF

Time:06-03

My AWS OBJECT Lambda Function gets an unencrypted PDF via the Object Lambda inputS3Url. I want to use PyPDF2 to convert this to encrypted PDF, and send back via s3.write_get_object_response. How do I do this?

s3_url = object_get_context["inputS3Url"]

url=s3_url


response = requests.get(url)
my_raw_data = response.content

[SAVE ENCRYPTED my_raw_data TO VARIABLE so it can returned via S3.write_get_object_response - HOW?]

s3 = boto3.client('s3')
s3.write_get_object_response(
Body= [WHAT WOULD GO HERE?]
RequestRoute=request_route,
RequestToken=request_token)

CodePudding user response:

The docs got you! Encrypting PDFs and Streaming Data is what you need (at least if I got you right; let me know if you want to achieve something else than getting a password-protected PDF on S3)

Not tested, but something like this

from PyPDF2 import PdfReader, PdfWriter
from io import BytesIO

reader = PdfReader(BytesIO(my_raw_data))
writer = PdfWriter()

# Add all pages to the writer
for page in reader.pages:
    writer.add_page(page)

# Add a password to the new PDF
writer.encrypt("my-secret-password")

# Save the new PDF to a file
with BytesIO() as bytes_stream:
    writer.write(bytes_stream)
    bytes_stream.seek(0)
    s3 = boto3.client('s3')
    s3.write_get_object_response(
        Body= [WHAT WOULD GO HERE?]
        RequestRoute=request_route,
        RequestToken=request_token
    )
  • Related