5

I am making a rest API call using Angular. My Rest API look like as below:

@RequestMapping(value = "/getPDF/{projectId}", method = RequestMethod.POST)
    public ResponseEntity<byte[]> generateReport(@PathVariable("projectId") long projectId, @RequestBody Object vo, final HttpServletRequest request) {
        vo.setProjectId(projectId);
        byte[] pdf = blueprintService.generateBluePrint(vo);

        LOG.debug(new StringBuilder("Generating Blueprint for VO: ").append(vo).toString());
        String fileName = null;
        try {
            ProjectDetailsVO pdvo = projectSetupService.getProjectDetails(vo.getProjectId());
            fileName = new StringBuilder(pdvo.getClientName()).append("_")
                    .append(pdvo.getProjectName()).append("_")
                    .append(System.currentTimeMillis()).append(".pdf")
                    .toString();
        } catch (Exception e) {
        }

        if (fileName == null || fileName.trim().isEmpty())
            fileName = new StringBuilder("Project_")
                    .append(vo.getProjectId()).append("_")
                    .append(System.currentTimeMillis())
                    .append(".pdf").toString();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/pdf");

        String userAgent = request.getHeader("User-Agent");

        if (userAgent != null && !(userAgent.contains("Firefox") && userAgent.contains("Mac"))) {
            LOG.debug("Inline BP Content");
            headers.add("Content-Disposition", new StringBuilder("inline; filename=\"").append(fileName).append("\"").toString());
        } else {
            LOG.debug("Attached BP Content");
            headers.add("Content-Disposition", new StringBuilder("attachment; filename=\"").append(fileName).append("\"").toString());
        }

        if (pdf != null)
            headers.setContentLength(pdf.length);

        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
    }

So server is setting file name for the PDF which I want to be the name of the generated PDF.

I tried below angular code:

success: function (data, status, headers, config) {
                        $modalInstance.close();
                        var file = new Blob([data], {type: 'application/pdf'});
                        var fileURL = URL.createObjectURL(file);
                        window.open(fileURL);
                    }

It works fine but it open the pdf of it's own name. Which I think, since Angular is converting the response into PDF. Hence Headers are getting excluded.

Is there any way to make a post request so it will open a PDF in new browser tab some code like as below:

$http.post{
url: myRestURL,
data: postbodyData,
taget: _blank
}

which will open my rest URL in new tab and show the PDF in browser.

Thank you.

Krishna
  • 179
  • 3
  • 17

0 Answers0