0

I am using following code to download PDF from html contain my working fine but file is getting downloaded twice I tried to modify renderer behavior but still haven't got anything.

public Response downloadResumePdf(@PathParam("userId") String userId) throws IOException, DocumentException {
     String homePath = System.getProperty("user.home");
        String filePath = homePath + "/Downloads/Resume" + LocalDateTime.now().toLocalDate() + ".pdf";
        org.xhtmlrenderer.pdf.ITextRenderer renderer = new ITextRenderer();
        String yourXhtmlContentAsString = "<h1>hi </h1>";
        renderer.setDocumentFromString(yourXhtmlContentAsString);
        renderer.layout();
        java.io.FileOutputStream fos = new java.io.FileOutputStream(filePath);
        renderer.createPDF(fos);
        fos.close();
        File file = new File(filePath);
        return Response
          .ok((Object) file)
          .header("Content-Disposition", "attachment; filename=\"Resume" + LocalDateTime.now().toLocalDate() + ".pdf\"")
          .build();
7
  • I cannot reproduce this issue, it only downloads once for me. Are you calling this endpoint twice somewhere which makes it download twice?
    – Mark
    Jan 16, 2019 at 11:38
  • @Mark in downloads folder same file is created twice
    – Tejal
    Jan 16, 2019 at 11:40
  • How is the same file created twice? Do they have different filenames?
    – Mark
    Jan 16, 2019 at 11:41
  • @Mark I am using above mentioned code only
    – Tejal
    Jan 16, 2019 at 11:43
  • You're loading a file called Resume2019-01-16.pdf from your downloads folder to serve on your API, then you run your API locally and it will download to Resume2019-01-16 (1).pdf, is this the 'downloading twice' you mention? That there are now two files in the downloads folder? Or is it creating Resume2019-01-16 (1).pdfand Resume2019-01-16 (2).pdf when you go to that endpoint?
    – Mark
    Jan 16, 2019 at 11:45

3 Answers 3

1

The reason for the duplication, as mentioned in Mark's answer, is because you are creating a "temporary" file when you create and write to the FileOutputStream.

The solution: you do not need to create a temporary file to handle the Download. Instead of creating a FileOutputStream, just use StreamingOutput and pass the StreamingOutput's OutputStream to the ITextRenderer#createPDF(OutputStream) method.

@GET
@Produces("application/pdf")
public Response getResumePdf(@PathParam("userId") String userId) {

    StreamingOutput entity = new StreamingOutput() {
        @Override
        public void write(OutputStream output) {
            try {
                ITextRenderer renderer = new ITextRenderer();
                String yourXhtmlContentAsString = "<h1>hi </h1>";
                renderer.setDocumentFromString(yourXhtmlContentAsString);
                renderer.layout();
                renderer.createPDF(output);
                output.flush();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    return Response.ok(entity)
         .header(...)
         .build();
}
0
1

The issue

In your code you're generating a file which then will be served on your API. This file is created with new java.io.FileOutputStream(filePath) and is called Resume2019-01-16.pdf located in the Downloads folder.

Since you're running your API locally, when you go to your endpoint the browser will download the file you're serving to your Downloads folder. Since Resume2019-01-16.pdf already exists there the browser will name it Resume2019-01-16 (1).pdf.

Hence it looks like two files are being downloaded, but one is being generated by your code and the other one is actually downloaded.

Fix

Change the folder for the files you're serving and only the files that are actually downloaded will appear in your Downloads eg:

String filePath = homePath + "/Documents/Resume" + LocalDateTime.now().toLocalDate() + ".pdf";

Alternatively use some method to store your file in memory instead of creating a physical file and serve that instead.

1
  • one is being generated by your code and the other one is actually downloaded.this the problem which I don't want I only want one file creation
    – Tejal
    Jan 16, 2019 at 12:21
0

You shold use StreamingOutput instead of using File.

String homePath = System.getProperty("user.home");
    String filePath = homePath + "/Downloads/Resume" + LocalDateTime.now().toLocalDate() + ".pdf";

    org.xhtmlrenderer.pdf.ITextRenderer renderer = new ITextRenderer();

    String yourXhtmlContentAsString = "<h1>hi </h1>";
    renderer.setDocumentFromString(yourXhtmlContentAsString);
    renderer.layout();

    java.io.FileOutputStream fos = new java.io.FileOutputStream(filePath);
    renderer.createPDF(fos);
    //fos.close();
    final File file = new File(filePath);

    StreamingOutput fileStream =  new StreamingOutput()
    {
        @Override
        public void write(java.io.OutputStream output) throws IOException, WebApplicationException
        {
            try
            {

                byte[] data = Files.readAllBytes(file.toPath());
                output.write(data);
                output.flush();
            }
            catch (Exception e)
            {
                throw new WebApplicationException("File Not Found. !!");
            }
        }
    };

   return Response
       .ok( fileStream, MediaType.APPLICATION_OCTET_STREAM)
       .header("Content-Disposition", "attachment; filename=\"Resume" + LocalDateTime.now().toLocalDate() + ".pdf\"")
       .build();
2
  • I tried above mentioned code still file is getting created twice
    – Tejal
    Jan 16, 2019 at 12:17
  • This is a poor implementation of the StreamingOutput and defeats the purpose of what it is for. You are reading the entire file into memory with Files.readAllBytes(). Jan 16, 2019 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.