Save text pdf direct to s3 without having to save it locally

Tags: , , ,

I am generating pdf files using itext 5 and Java, and saving them locally then saving these local saved files on AWS S3. Is there a way to just send them straight to S3 without having to save them locally. I have seen a few examples but none is working for me.

This is how am generating the pdf file

 String path = //local directory on my computer
 Document document = new Document();
 PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));;
 // add text to document

This is how I save it on s3

public void saveFileToS3(String pathLocal, String pathAws) {
    // init aws 

    PutObjectRequest objectRequest = PutObjectRequest.builder()
        .key(folderName + "/" + pathAws)
    CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,
    future.whenComplete((resp, err) -> {
      try {
        if (resp != null) {
          System.out.println("Object uploaded. Details: " + resp);
        } else {
      } finally {

String pathLocal is the path where am saving the file locally, while String pathAws is the path on S3 where the file is saved.


So I found out a way, I converted the itext file to a byte array and uploaded the pdf file as a byte array

Document document = new Document();
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 PdfWriter.getInstance(document, byteArrayOutputStream);;

//add stuff to pdf


//convert it into a byte array
byte[] pdfBytes = byteArrayOutputStream.toByteArray()

When uploading it to S3 I passed the bytes instead of the file path as I was doing before

CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,

Source: stackoverflow