java - Spring启动Angular2,以JSON返回PDF

标签 java spring angular spring-boot filesaver.js

我有一个 Spring boot REST API,它必须返回 PDF。我已将 PDF 转换为字节数组,然后将其编码为 Base64,然后将其返回给客户端。

这是我的界面:

@ApiOperation(value = "Update an existing form", notes = "Update an existing form ", response = Void.class, tags={  })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "form response", response = Void.class),
            @ApiResponse(code = 200, message = "unexpected error", response = Void.class) })
    @RequestMapping(value = "/forms/{formId}/submissions/{submissionId}/pdf",
            method = RequestMethod.GET)
    ResponseEntity<Resource> pdf(
            @ApiParam(value = "Id of the form that needs to be updated", required = true) @PathVariable("formId") Long formId,
            @ApiParam(value = "Id of the submission that needs to be updated", required = true) @PathVariable("submissionId") Long submissionId,
            @ApiParam(value = "token to be passed as a header", required = true) @RequestHeader(value = "token", required = true) String token
    );

以及实现的方法:

@Override
    public ResponseEntity<Resource> pdf(@ApiParam(value = "Id of the form that needs to be updated", required = true) @PathVariable("formId") Long formId, @ApiParam(value = "Id of the submission that needs to be updated", required = true) @PathVariable("submissionId") Long submissionId, @ApiParam(value = "token to be passed as a header", required = true) @RequestHeader(value = "token", required = true) String token) {
        String name = JWTutils.getEmailInToken(token);

        if(name == null) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }

        User user = userRepository.findByEmail(name);

        if(user == null){
            return  new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }

        Form form = formRepository.findById(formId);

        if(form == null){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        Submission submission = submissionRepository.findOne(submissionId);

        if(submission == null){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        //Saving the document
        final PDPage singlePage = new PDPage();
        final PDFont courierBoldFont = PDType1Font.COURIER_BOLD;
        final int fontSize = 12;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (final PDDocument document = new PDDocument())
        {
            document.addPage(singlePage);
            final PDPageContentStream contentStream = new PDPageContentStream(document, singlePage);
            contentStream.beginText();
            contentStream.setFont(courierBoldFont, fontSize);
            contentStream.newLineAtOffset(150, 750);
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.showText("Hello PDFBox");
            contentStream.endText();
            contentStream.close();  // Stream must be closed before saving document.
            //document.save("pdfs/" + UUID.randomUUID().toString() + ".pdf");
            document.save(out);
        }
        catch (IOException ioEx)
        {
            ioEx.printStackTrace();
        }

        byte[] b64 = Base64.getEncoder().encode(out.toByteArray());
        ByteArrayResource resource = new ByteArrayResource(b64);

        return ResponseEntity.ok()
                .contentLength(b64.length)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

这是 Angular2 中的代码:

generatePdf(){
    this.submissionService.generatePdf(this.form.id, this.submission.id).then(data => {
        console.log(JSON.stringify(data));
        let file = new Blob([atob(data._body)]);
        FileSaver.saveAs(file, 'helloworld.pdf')
    }).catch(error => {
        console.log(error);
    });
}

我在有效负载中收到的 PDF 如下所示:PasteBin

当我打开下载的 PDF 时,它只包含一页空白,而真正的 pdf 包含文本。知道发生了什么吗?我觉得这与编码有关。


解决方案

我必须更改服务中的 GET 请求。我已将此添加到我的请求 responseType: ResponseContentType.Blob;

return this.http.get(this.formsUrl + "/" + formId + "/submissions/" + submissionId + "/pdf", {headers: headers, responseType: ResponseContentType.Blob})
        .toPromise()
        .then(res => res)
        .catch(this.handleError);

最佳答案

解决方案

我必须更改服务中的 GET 请求。我已将此添加到我的请求 responseType: ResponseContentType.Blob;

return this.http.get(this.formsUrl + "/" + formId + "/submissions/" + submissionId + "/pdf", {headers: headers, responseType: ResponseContentType.Blob})
        .toPromise()
        .then(res => res)
        .catch(this.handleError);

关于java - Spring启动Angular2,以JSON返回PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965989/

相关文章:

java - 通过手机进行坐标检测

java - TestNG - selenium 脚本中的测试执行顺序

java - Spring Boot 2 从配置列表实例化 Bean

java - Spring Cloud Gateway 引导失败

angular - Windows cmd 在 ngserve --o 命令后关闭

angular - 需要进行多次HTTP调用并合并结果

java - 无法使用 Spring Social 创建 LinkedIn Controller bean

java - 如何确定正在运行的 JVM 上的 MaxDirectMemorySize?

java - spring boot应用配置问题

angular - Jest 26 & Angular - 错误地报告了错误行号