How to SHOW a PDF brought from JAVA in HTML-JAVASCRIPT?

0

I need to SHOW a pdf that comes from JAVA.

That's what I do with a servlet.

function descargarCarta(){
console.log("entra a descargar");
           var settings = {
               "async": true,
   "crossDomain": true,
   "url": "http://localhost:8080/StaffingApp/accesoServlet?resource=reporteCartaLaboral&codigoVinculacion=00959158-01-TL",
   "method": "GET"
   }

   $.ajax(settings).done(function (response) {
   console.log(response);
   });
}

so I sent it from the servlet

byte[] reporteCarta = null;
reporteCarta = generarReporteCartaLaboral(request, response);
ServletOutputStream servletOutputStream = response.getOutputStream();
response.reset();
String codigo = request.getParameter("codigoVinculacion");
System.out.println("codigo" + codigo);
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=\"Carta_Laboral_" + codigo + ".pdf\"");
servletOutputStream.write(reporteCarta);
servletOutputStream.close();

And it is generated as pdf, but I need to show it as PDF in an HTML project

Thanks for your help.

    
asked by Diego Lopez 29.11.2017 в 22:35
source

1 answer

0

If what you need is to obtain a file, simply from the server you type the content type of the response and send the content:

public void download() throws IOException {
    // Prepare.
    byte[] pdfData = getItSomehow();
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    // Initialize response.
    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType("application/pdf"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setHeader("Content-disposition", "attachment; filename=\"name.pdf\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.

    // Write file to response.
    OutputStream output = response.getOutputStream();
    output.write(pdfData);
    output.close();

    // Inform JSF to not take the response in hands.
    facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

From html you only need a link to the page that generates the content from the byte array, in this case a pdf.

The code is an example, maybe I can help you.

    
answered by 29.11.2017 в 23:04