In my Spring Boot app, I am generating pdf file from html string and save it a temp location by using the following approach:
@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.
1. The client will receive the blob file and then open it as pdf. In this case I think I should create and save blob file from pdf after generating it? Is that right?
2. How could I generate blob from pdf?
3. Which type should I return the generated blob file? Is MultipartFile
is a proper format? And I think I cannot return blob directly and have to save it first?
CodePudding user response:
The type matching databases blob storages in java are simply bytes array.
From your filepath, you have to get your pdf binaries from filepath and then send it to your persistance storage like you want :
String filePath = request.getDownloadPath() "/" request.getItemUuid() ".pdf";
pdf.saveAs(filePath);
byte[] pdfData = Files.readAllBytes(Paths.get(filePath));
And your pdfResponse should look like this :
@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. 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)