Skip to content
Advertisement

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

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));
 document.open();
 
 // add text to document
 document.close();

This is how I save it on s3

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

    PutObjectRequest objectRequest = PutObjectRequest.builder()
        .bucket(bucketName)
        .key(folderName + "/" + pathAws)
        .build();
    
    CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,
        AsyncRequestBody.fromFile(Paths.get(pathLocal))
    );
    
    future.whenComplete((resp, err) -> {
      try {
        if (resp != null) {
          System.out.println("Object uploaded. Details: " + resp);
        } else {
          err.printStackTrace();
        }
      } finally {
        s3Client.close();
      }
    });
    
    future.join();
  }

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

Advertisement

Answer

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);

 document.open();

//add stuff to pdf

 document.close();

//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,
        AsyncRequestBody.fromBytes(pdfBytes)
    );
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement