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
JavaScript
x
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
JavaScript
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
JavaScript
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
JavaScript
CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,
AsyncRequestBody.fromBytes(pdfBytes)
);