user2758176
user2758176

Reputation: 193

PDF download in new window in java

My requirement for PDF download is:

  1. When user click on "Download" link, front-end will POST a JSON data to the back-end.
  2. Back-end will process the JSON, generating a PDF file from it's parameters.
  3. In response I (back-end) need to send a download link and unique document id.
  4. Frond-end will open that link (GET) in new window which will hit the back-end and download will start.

How should I do this?

Thanks in advance.

Upvotes: 0

Views: 409

Answers (1)

André
André

Reputation: 2204

If you're using Spring you create a Controller

@Controller
@RequestMapping(value = "/report")
public class ReportController {

    @Autowired
    ReportFileStore reportFileStore;

    @RequestMapping(value = "/download/{uniqueId}", method = RequestMethod.GET)
    public void getFile(@PathVariable("uniqueId") String uniqueId, HttpServletResponse response) {
        //Find the generated PDF from somewhere, might be a disk, or RAM
        byte[] pdf = getFromStore(uniqueId);

        writeToResponse(pdf,response);
        deleteFileFromStore(uniqueId);
    }

    private byte[] getFromStore(String uniqueId){
        return reportFileStore.getFile(uniqueId);
    }
}

The method writeToResponse is a standard servlet download code, you can see a example here or here.

About the getFromStore, that is a simple method get the byte[] of the PDF generated from Jasper, when you generate you can have put method that stores the byte[] with the uniqueId.

I'd use a interface like this

public interface ReportFileStore {
     void storeFile(String uniqueId,byte[] content);
     byte[] getFile(String uniqueId);
     InputStream getFile(String uniqueId);
     void deleteFile(String uniqueId);
}

And implement it using a VFS mapped on a RAM or Disk.


Of course, on your PDF generation, you need to generate a unique ID for it, you can try using UUID. Use this UUID with the ReportFileStore to save the PDF file. It's unclear if the "need to return a download link and a unique id" can be done just returning the uniqueId, then hardcoding the download location on the front-end. If not, return a JSON mapping it.

Upvotes: 2

Related Questions