Sobes.tech
Junior — Middle

How to implement sending a PDF document to a user in an application?

sobes.tech AI

Answer from AI

To send a PDF document to a user in a Java application, such as a Spring Boot web application, you can do the following:

  1. Generate the PDF file or retrieve it from storage.
  2. Set the correct HTTP headers for the response so that the browser understands it's a PDF and offers to download or open the file.
  3. Write the contents of the PDF to the response output stream.

Example of a Spring Boot controller:

@GetMapping("/download/pdf")
public void downloadPdf(HttpServletResponse response) throws IOException {
    // Path to the PDF file
    File pdfFile = new File("path/to/document.pdf");

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=document.pdf");
    response.setContentLength((int) pdfFile.length());

    try (InputStream is = new FileInputStream(pdfFile);
         OutputStream os = response.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
    }
}

If the PDF is generated dynamically, you can use libraries like iText or Apache PDFBox to create the document in memory and send it through the OutputStream.