-1

I have a Jhipster application that generate PDF with iText library, this PDF is saved in the computer in the route that I indicated. I would like that when generating the pdf, a dialog box will appear to download the pdf. I am indifferent if the pdf is saved in the project folder or not saved in any place.

I have seen many posts giving possible answers on this page and on the internet, but many are already obsolete and others have not worked for me.

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));
    }

EDIT

entity.component.ts

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

entity.service.ts

    downloadFile(): Observable<any> {
        return this.http.get(SERVER_API_URL + 'api/downloadFile');
    }
Cruasant
  • 33
  • 9
  • Instead of writing to a file, write the the output stream of the HttpServletResponse. Make sure to set the correct content type before writing. – JB Nizet Apr 09 '19 at 16:14
  • How could I do that? Is my first time working with Files and I am lost. – Cruasant Apr 09 '19 at 16:19
  • There is no file involved. Add the HttpServletResponse to the arguments of your response, set its content type, get its OuptutStream, write the PDF to the output stream. Of course, your method can't return a User: either it returns a PDF document, or it returns a JSON document for your user. It can't return both. – JB Nizet Apr 09 '19 at 16:22

1 Answers1

0

Use this to download the file:

@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);
    }

And this to generate the file:

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;
    }
}

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

download a file from Spring boot rest service

  • Thank you!! That works fine if i access by http://localhost:9060/api/downloadFile but in app doesn't work and in logs all is correct (access to the method fine). Add .ts methods in post. – Cruasant Apr 09 '19 at 19:01
  • Create a resource name test, add this method in resource and in class SecurityConfiguration add this code: .antMatchers("/test/**").permitAll() To dowload acess localhost:9060/test/downloadFile – Leonardo Machado Moscardo Apr 09 '19 at 19:25