我如何下载生成的PDF而不将其存储在服务器上?

时间:2019-04-09 16:03:33

标签: java spring-boot itext jhipster

我有一个Jhipster应用程序,该应用程序使用iText库生成PDF,该PDF文件按照我指定的路径保存在计算机中。 我希望在生成pdf时出现一个对话框来下载pdf。 pdf是保存在项目文件夹中还是未保存在任何地方,我都没关系。

我已经在此页面和互联网上看到很多帖子给出了可能的答案,但是很多帖子已经过时,还有一些帖子对我没有帮助。

  

生成PDF

public void generatePDF(User u) {

        String dest = "D:/PDF/result.pdf";
        String src = "D:/PDF/template.pdf";

        try {
            PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
            Map<String, PdfFormField> fields = form.getFormFields();

            fields.get("name").setValue(u.getFirstName());
            fields.get("surname").setValue(u.getLastName());
            fields.get("email").setValue(u.getEmail());

            pdf.close();

        } catch (IOException e) {
            log.debug(e.getMessage());
        }
    }
  

UserResource

    @GetMapping("/print-user/{id}")
    @Timed
    public ResponseEntity<User> printUserTemplate(@PathVariable Long id) {
        User user = userRepository.findOne(id);
        userService.generatePDF(user);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(user));
    }

编辑

  

entity.component.ts

    downloadFile() {
        this.entityService.downloadFile().subscribe();
    }
  

entity.service.ts

    downloadFile(): Observable<any> {
        return this.http.get(SERVER_API_URL + 'api/downloadFile');
    }

1 个答案:

答案 0 :(得分:0)

使用此下载文件:

@GetMapping("/downloadFile")
    public ResponseEntity<Resource> downloadFile(HttpServletRequest request) {
        // Load file as Resource
        Resource resource = testService.loadFileAsResource();

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            log.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(
            HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").body(resource);
    }

然后生成文件:

public Resource loadFileAsResource() {
    try {
        Path path = Paths.get("D:\\PDF\\template.pdf");
        Path filePath = path.normalize();

        Resource resource = new UrlResource(filePath.toUri());
        if (resource.exists()) {
            return resource;
        } else {
            return null;
        }
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        return null;
    }
}

参考: https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/

download a file from Spring boot rest service