get pdf from FileOutputStream

0

I'm doing an application where I create a pdf. I have done it in a way that I created it in a directory (FileOutputStream) but I would like it to be opened through the browser when I click on the link that calls the action that creates it. It's in java.

Thanks in advance.

    
asked by Oscar Marés Barrera 04.06.2018 в 23:30
source

1 answer

0

You need a servlet that looks like this:

public class PDFServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pdfFileName = "tu-pdf.pdf";
        String contextPath = getServletContext().getRealPath(File.separator);
        File pdfFile = new File(contextPath + pdfFileName);    
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
        response.setContentLength((int) pdfFile.length());    
        FileInputStream fileInputStream = new FileInputStream(pdfFile);
        OutputStream responseOutputStream = response.getOutputStream();
        int bytes;
        while ((bytes = fileInputStream.read()) != -1) {
            responseOutputStream.write(bytes);
        }    
    }
}

You can also do it in a similar way with other FRAMEWORKS Web for Java, but since you did not specify any, I'll give you the most generic way to carry this out.

    
answered by 04.06.2018 в 23:35