Java – How to send a generated PDF document to the frontend in Restfull in Spring Boot?

How to send a generated PDF document to the frontend in Restfull in Spring Boot?… here is a solution to the problem.

How to send a generated PDF document to the frontend in Restfull in Spring Boot?

I’ve implemented it with a guide pdf generation.
My class PdfView has a method:

@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) {
    response.setHeader("Content-Disposition", "attachment; filename=\"animal-profile.pdf\"");

List<Animal> animals = (List<Animal>) model.get("animals");
    try {
        document.add(new Paragraph("Generated animals: " + LocalDate.now()));
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    PdfPTable table = new PdfPTable(animals.stream().findAny().get().getColumnCount());
    table.setWidthPercentage(100.0f);
    table.setSpacingBefore(10);

Font font = FontFactory.getFont(FontFactory.TIMES);
    font.setColor(BaseColor.WHITE);

PdfPCell cell = new PdfPCell();
    cell.setBackgroundColor(BaseColor.DARK_GRAY);
    cell.setPadding(5);

cell.setPhrase(new Phrase("Animal Id", font));
    table.addCell(cell);

cell.setPhrase(new Phrase("Animal name", font));
    for (Animal animal : animals) {
        table.addCell(animal.getId().toString());
        table.addCell(animal.getName());
    }
    document.add(table);
}

How should I implement a Controller using the GET method to download PDFs?

Solution

Sample code to download images using the API is shown below

@RequestMapping("/api/download/{fileName:.+}")
public void downloadPDFResource(HttpServletRequest request, HttpServletResponse response,@PathVariable("fileName") String fileName) throws IOException {
    String path = somePath + fileName;
    File file = new File(path);
    if (file.exists()) {
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());  for you it would be application/pdf
        if (mimeType == null) mimeType = "application/octet-stream";
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));
        response.setContentLength((int) file.length());
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }
}

Go to url – http://localhost:8080/download/api/download/fileName.pdf
Let’s say your service is deployed on port
8080
You should be able to preview the file.
Note: If you want to download the file, set Content-Disposition as an attachment

Related Problems and Solutions