首页 > 解决方案 > 将文本pdf直接保存到s3而无需在本地保存

问题描述

我正在使用 itext 5 和 Java 生成 pdf 文件,并将它们保存在本地,然后将这些本地保存的文件保存在 AWS S3 上。有没有办法直接将它们发送到 S3 而不必在本地保存它们。我看过一些例子,但没有一个对我有用。

这就是生成pdf文件的方式

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

这就是我在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是我在本地保存文件的路径,而String pathAws是 S3 上保存文件的路径。

标签: javaamazon-web-servicesamazon-s3itext

解决方案


所以我找到了一种方法,我将itext文件转换为字节数组并将pdf文件作为字节数组上传

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

将其上传到 S3 时,我传递了字节而不是文件路径,就像我之前所做的那样

CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,
        AsyncRequestBody.fromBytes(pdfBytes)
    );

推荐阅读