Buscar este blog

domingo, 21 de febrero de 2016

XMLHttpRequest - Download PDF and show it in iframe

These snippets show how to download a PDF from a Servlet and how to show it inside a iframe.
The immediate solution would be to invoke the servlet by GET, and to put this URL in de src attribute of the iframe, but in this case I want to invoke the servlet by POST.

Servlet code:
@WebServlet(urlPatterns="/sello")
public class SelloRegistroServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 private final SelloService selloService = new SelloServiceImpl();

 @Override
 protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
     final DatosSello datos = recuperarDatosSello(request);
     final ConfiguracionSello config = recuperarDatosConfig(request);

     final ByteArrayOutputStream baos = selloService.generarSello(datos, config);
  
            response.setContentType("application/pdf");
            response.setContentLength(baos.size());
            response.setHeader("Content-Disposition", "inline;filename=\"selo.pdf\"");
            response.setHeader("filename", "selo.pdf");

            final OutputStream outStream = response.getOutputStream();
            outStream.write(baos.toByteArray());
            outStream.flush();
            outStream.close();
 }
 
 private DatosSello recuperarDatosSello(final HttpServletRequest request) {
     (...)
 }


 private ConfiguracionSello recuperarDatosConfig(final HttpServletRequest request) {
     (...)
 }
}

HTML code:
<html>
<head>          
    <script type="text/javascript">
        var urlSello = 'http://localhost:8080/registro-itext/sello';
        
        var generarSello = function() {          
            var data = {
                    numeroRegistro:             document.getElementsByName("numReg")[0].value,
                    fechaRegistro:              document.getElementsByName("fechaReg")[0].value,
                    codigoOficina:              document.getElementsByName("codigoOfi")[0].value,
                    nombreOficina:              document.getElementsByName("nombreOfi")[0].value,
                    codigoUnidad:               document.getElementsByName("codigoUnidad")[0].value,
                    nombreOficina:              document.getElementsByName("nombreOfi")[0].value
            };
            
            var params = Object.keys(data).map(function(key) {
                return key + '=' +  encodeURI(data[key]);
            }).join('&');
            
            var xhr = new XMLHttpRequest();           
            xhr.onreadystatechange = function(){                
                if (this.readyState == 4 && this.status == 200){
                    console.log(this.response, typeof this.response);               
                    var urlBuilder = window.URL || window.webkitURL;
                    document.getElementById("iFramePDF").src = urlBuilder.createObjectURL(this.response);
                    document.getElementById("iFramePDF").style.display = 'block';               
                }
            };    
            xhr.open('POST', urlSello, true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.setRequestHeader("Content-length", params.length);
            xhr.responseType = 'blob';
            xhr.send(params);                       
        };                
    </script>
</head>

<body>
    <div id="contenido">     
        <button id="btnSello" type="button" onclick="generarSello();">Generar Sello</button>
                  
        <table>
            <tr><td>Numero de registro: </td> <td> <input name="numReg"  type="text" value="899998"></td></tr>
            <tr><td>Fecha de registro</td> <td> <input name="fechaReg"   type="text" value="2015/01/01 10:10:00"></td></tr>
            <tr><td>Codigo de oficina</td> <td> <input name="codigoOfi"  type="text" value="000"></td></tr>
            <tr><td>Nombre de oficina</td> <td> <input name="nombreOfi"  type="text" value="Rexistro Xeral \nProbas"></td></tr>
            <tr><td>Codigo de unidad</td> <td> <input name="codigoUnidad" type="text" value="V0"></td></tr>           
        </table>
    </div>
    

    <iframe id="iFramePDF" name="iFramePDF" src=""  width="100%" height="100%" frameBorder="0" styele="display:none"></iframe>

</body>
</html>

The important parts are:
  1. You create an object with all the params to serialize it in the way "name=value&" and to send the outcome string to the servlet.
  2. You invoke the servlet by using XMLHttpRequest. In the callback function, you convert the whole response to a new URL and pass it to the iframe

No hay comentarios:

Publicar un comentario