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

问题描述 投票:-1回答:1

我有一个使用iText库生成PDF的Jhipster应用程序,这个PDF按照我指示的路径保存在计算机中。我希望在生成pdf时,会出现一个对话框来下载pdf。如果pdf保存在项目文件夹中或者没有保存在任何地方,我就无动于衷。

我看过很多帖子在这个页面和互联网上给出了可能的答案,但是很多帖子已经过时了,而其他一些帖子对我来说并不适用。

generatePDF

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');
    }
java spring-boot itext jhipster
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.