Generate angular pdf using javascript

Asked

Viewed 2,413 times

4

I am trying to generate a pdf in my angular application and I have the following code in controller.js:

   function gerarPdf(){
        restService.relatorio.save({
          id: controller.contrato.id,
          folha: controller.receita.folha,
          descricao: controller.receita.desc},
          function (response){
            var file = new Blob([response], { type: 'application/pdf' });
            var fileURL = URL.createObjectURL(file);
            window.open(fileURL, "EPrescription");
          },
          function(err){
            throw err;
          });
    }

Code of the restService:

service.relatorioPart = $resource(REST_API.url + '/relatorios/participacao', {
    id: '@id',
    folha: '@folha',
    desc: '@descricao'
},
{
  responseType: 'arraybuffer'
});

The method code in the java controller:

@POST
@Secured
@Path("/participacao")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf")
public Response imprimirRelatorioExtratoCoparticipacao(@Context HttpServletRequest request, HashMap<String, Object> filtros) throws PadraoException, Exception {
    try {

        Map dadosUsuario = restUtil.dadosUsuario(request);

        //Retorna um array de byte com os dados buscados no banco
        byte[] bytesRelatorio = nrelatorio.gerarBytesRelatorioExtratoCoparticipacao(filtros, dadosUsuario, "C:\\xxxx\\Desenvolvimento\\as-aplicacao\\");

        if (bytesRelatorio == null) {
            return null;
        }

        return Response.ok(bytesRelatorio).build();
    } catch (Exception e) {
        return Response.status(INTERNAL_SERVER_ERROR).build();
    }
}

Performing test by Postman it normally generates the pdf of the report and already opens the window to save the document. I need that in my application it also save this option or open a new window displaying the report. Com esse código acima ao dar no click no botão na tela chama a função geraPdf() ele dá o resultado

I gave a console.log(Response) to see if it was bringing the array of bytes and had the result:

Resultado do console.log(response) que veio do java

Test done by Postman: [! [insert image description here][3][3]

I believe that for some detail I’m not getting to take this byte array of the java api and angular convert to a pdf document. If anyone has the knowledge to help me I would be very grateful. ^^

4 answers

1

I’m not sure if this can work for you, but it’s the way I download CSV by ajax using Angularjs. You could create a link on the return of the function and associate to the URL the path of the created object...:

$http({
    url: 'END_IP/relatorios/participacao',
    method: 'POST',
    data: {
        id: id,
        folha: folha,
        desc: desc
    }
}).success(function(data) {

    var a = document.createElement("a"); // cria o elemento
    document.body.appendChild(a); // adiciona no DOM
    a.style = "display: none"; // torna invisivel
    // \ufeff - para caracteres especiais
    var blob = new Blob(["\ufeff", data], {
            type: 'application/pdf'
        }),
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = "download.pdf";
    a.click(); // invoca o download do arquivo

    // para informar o navegador que não é mais necessário 
    //manter a referência para o arquivo
    window.URL.revokeObjectURL(url);

}).error(function(erro) {
    console.log(erro);
});

0

I’ve done something similar, the difference is that my Replay in java returns a Bytearrayinputstream. Try the code keeping your java code, if it doesn’t work try to change byte[] by Bytearrayinputstream... I solved it as follows:

I added the code below inside Resource

  cache: true,
  transformResponse: function(data, headersGetter, status) {
     var pdf = data;
     if (data && status < 400) {
        pdf = new Blob([data], {
          type: 'application/pdf'
        });
     }
     return {response: pdf};
   }

So it would look something like this:

Your controller:

restService.relatorio.save({
  id: controller.contrato.id,
  folha: controller.receita.folha,
  descricao: controller.receita.desc},
  function (response){
   var file = URL.createObjectURL(response.response);
   window.open(file);
  },
  function(respostaErro){
   // Aqui recupera alguma string caso o java retorne informando o erro
   var charCodeArray = Array.apply(null, new Uint8Array(
     respostaErro.data.response));
   var mensagem = '';
   for (var i = 0, len = charCodeArray.length; i < len; i++) {
     var code = charCodeArray[i];
     mensagem += String.fromCharCode(code);
   }
   alert(mensagem);
  });

Your service:

service.relatorioPart = $resource(REST_API.url + '/relatorios/participacao', {
    id: '@id',
    folha: '@folha',
    desc: '@descricao'
},
{
  responseType: 'arraybuffer',
  cache: true,
  transformResponse: function(data, headersGetter, status) {
     var pdf = data;
     if (data && status < 400) {
        pdf = new Blob([data], {
          type: 'application/pdf'
        });
     }
     return {response: pdf};
   }
});

0

In that case what I do is the following at the angle:

window.location.href="http://localhost/suaapp/pdf?parametros"

This URL will return a Response content type "application/pdf" and automatically the browser will ask to download.

0

You can do it this way:

creation of Resource:

var app = angular.module('app', ['ngResource']);

app.factory("PDFResource", function ($resource) {
    return $resource("REST_API.url + '/relatorios/participacao',
        {
             id: '@id',
             folha: '@folha',
             desc: '@descricao'
        },
        {
            'save' : {
                 method : 'POST',
                 responseType: 'arraybuffer',
                 transformResponse: function(data, headersGetter) {
                 return { data : data };
            }
        }
    });
)};

Your Service:

@POST
@Secured
@Path("/participacao")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf")
public Response imprimirRelatorioExtratoCoparticipacao(@Context HttpServletRequest request, HashMap<String, Object> filtros) throws              PadraoException, Exception {
    try {

        Map dadosUsuario = restUtil.dadosUsuario(request);
        //Retorna um array de byte com os dados buscados no banco
        byte[] bytesRelatorio =     nrelatorio.gerarBytesRelatorioExtratoCoparticipacao(filtros, dadosUsuario, "C:\\xxxx\\Desenvolvimento\\as-aplicacao\\");

        if (bytesRelatorio == null) {
            return Response.status(204).build();
        }

        return Response.ok(bytesRelatorio).build();
    } catch (Exception e) {
        return Response.status(INTERNAL_SERVER_ERROR).build();
    }
}

And I would use it this way:

PDFResource.save(function(response){
    console.log(response);
    var file = new Blob([response.data], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
}, function (err){
    console.log(err);
});

Pdfresource should be injected into your controller

Browser other questions tagged

You are not signed in. Login or sign up in order to post.