【问题标题】:Save a pdf in AWS S3 location using PDFBox - Java使用 PDFBox - Java 在 AWS S3 位置保存 pdf
【发布时间】:2021-09-16 13:21:11
【问题描述】:

我正在使用 PDFBox 创建 PDF。我想将 PDF 保存在 S3 中。我可以使用 PDFBox 创建 PDF 并将其上传到 S3 位置。我正在考虑使用PDDocument.save(S3location)将PDF直接保存到S3,而不是在本地保存然后上传到S3。有什么办法吗?

【问题讨论】:

  • 试试这个链接stackoverflow.com/a/8752849
  • 除了(可能)稍微干净一点的代码——你的目标是什么?我预计 S3 的延迟会影响任何增量写入的性能,因此在上传文件之前在本地缓存文件几乎肯定会更快。

标签: java amazon-s3 pdfbox flying-saucer


【解决方案1】:

由于您不想在本地存储文件,因此您需要某种输入流。 要在 AWS 中存储对象,您需要 InputStreamcontentLength,正如他们的 doc 中所述:

RequestBody requestBody = RequestBody.fromInputStream(fileInputStream, fileSize)
PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .metadata(metadata)
                    .build();
PutObjectResponse response = s3.putObject(putOb, requestBody);

您需要执行以下操作:

  1. 将 PDDocument 保存到输出流,doc
  2. 使用 PipedOutput/PipedInput Streams 将输出流转换为输入流,如 Stackoverflow answer 中所述
  3. 使用此输入流和内容长度上传到 S3
//create new ByteArrayOutputStream
ByteArrayOutputStream originalOutputStream = new ByteArrayOutputStream();
//save your PDDocument to that stream
pdDocument.save(originalOutputStream);
//Determine the size of the stream as you will need this to store in S3
long size = originalOutputStream.size();


//convert this output stream to input stream
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
new Thread(() -> {
    try {
        // write the original OutputStream to the PipedOutputStream
        // note that in order for the below method to work, you need
        // to ensure that the data has finished writing to the
        // ByteArrayOutputStream
        originalOutputStream.writeTo(out);
    } catch (IOException e) {
        log.error(e.toString());
    } finally {
        // close the PipedOutputStream here because we're done writing data
        // once this thread has completed its run
        if (out != null) {
            // close the PipedOutputStream cleanly
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}).start();
//Use the input stream and size to store the stream in s3
RequestBody requestBody = RequestBody.fromInputStream(in, size);
PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .metadata(metadata)
                    .build();
PutObjectResponse response = s3.putObject(putOb, requestBody);

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2016-07-09
    相关资源
    最近更新 更多