简体   繁体   English

如何将生成的 pdf 保存为 Java 中的 blob

[英]How to save generated pdf as blob in Java

In my Spring Boot app, I am generating pdf file from html string and save it a temp location by using the following approach:在我的 Spring 引导应用程序中,我从 html 字符串生成 pdf 文件,并使用以下方法将其保存为临时位置:

@Override
public PdfResponse downloadPdfFromUrl(final PdfRequest request, final String html) {

    // some codes omitted for brevity

    Pdf pdf = new Pdf();
    String filePath = request.getDownloadPath()+ "/" + request.getItemUuid()+ ".pdf";
     pdf.saveAs(filePath);

    PdfResponse response = new PdfResponse();
    response.setFileDownloadPath(filePath);
    response.setFileName(request.getItemUuid());

    return response;
}
@Data
public class PdfResponse {
    private UUID fileName;
    private String fileDownloadPath;
    private Long size;
}

At this point, I want to save the generated pdf as blob and return it in a proper format.此时,我想将生成的 pdf 保存为 blob 并以正确的格式返回。

1. The client will receive the blob file and then open it as pdf. 1.客户端会收到blob文件,然后打开pdf。 In this case I think I should create and save blob file from pdf after generating it?在这种情况下,我认为我应该在生成 Blob 文件后从 pdf 创建并保存它? Is that right?那正确吗?

2. How could I generate blob from pdf? 2.如何从 pdf 生成 blob?

3. Which type should I return the generated blob file? 3.生成的blob文件应该返回哪种类型? Is MultipartFile is a proper format? MultipartFile是正确的格式吗? And I think I cannot return blob directly and have to save it first?而且我认为我不能直接返回 blob 并且必须先保存它?

The type matching databases blob storages in java are simply bytes array. java 中的类型匹配数据库 blob 存储只是字节数组。

From your filepath, you have to get your pdf binaries from filepath and then send it to your persistance storage like you want:从您的文件路径中,您必须从文件路径中获取 pdf 二进制文件,然后将其发送到您想要的持久性存储中:

String filePath = request.getDownloadPath()+ "/" + request.getItemUuid()+ ".pdf";
pdf.saveAs(filePath);
byte[] pdfData = Files.readAllBytes(Paths.get(filePath));

And your pdfResponse should look like this:你的 pdfResponse 应该是这样的:

@Data
public class PdfResponse {
    private UUID fileId;
    private String fileName;
    private byte[] pdfData;
    private Long size;
}

Last but not least I think you will want to be able to download that PDF file from a Spring controller.最后但同样重要的是,我认为您将希望能够从 Spring controller 下载该 PDF 文件。 Then you can achieve it this way (It's same logic for a PDF or an image): https://www.baeldung.com/spring-controller-return-image-file (Just replace.jpg with.pdf)然后你可以通过这种方式实现它(对于 PDF 或图像的逻辑相同): https://www.baeldung.com/spring-controller-return-image-file (只需将.jpg替换为.pdf)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM