'Download pdf from restful web services

I am writing a rest service which will download the pdf when user access this service on users machine. below is the code of my controller class.

When I tried to access below url in browser, it is downloading .JSON file and not PDF file.

URL:- http://localhost:8080/test-service/downloadPDF?userId=abcd&requestingLocation=6&orderId=06006030

I have tried to use same code which was mentioned in below sites. It seems the straight forward code but not sure why it is not working. http://www.java2novice.com/restful-web-services/jax-rs-download-file/ https://www.javatpoint.com/jax-rs-file-download-example

Below is method in controller.

    @GET
    @RequestMapping(value = "/downloadPDF")
    @Produces("application/pdf")
    public @ResponseBody Response downloadDocument(@RequestParam("userId") String userId,@RequestParam("requestingLocation") String requestinglocation,@RequestParam("orderId") String orderId) {
            String path = "C:\\opt\\autobol\\logs\\autobol\\test2.pdf";
        File file = new File(path);  
            ResponseBuilder response = Response.ok((Object) file);  
            response.header("Content-Disposition","attachment; filename=\"javatpoint_pdf.pdf\"");  
            return response.build(); 

        }

It should download pdf file

below is the content of downloaded file (file name downloadPDF.json):

{  
   "entity":"C:\\opt\\autobol\\logs\\autobol\\test2.pdf",
   "status":200,
   "metadata":{  
      "Content-Disposition":[  
         "attachment; filename=\"javatpoint_pdf.pdf\""
      ]
   },
   "annotations":null,
   "entityClass":"java.io.File",
   "genericType":null,
   "length":-1,
   "language":null,
   "location":null,
   "lastModified":null,
   "date":null,
   "closed":false,
   "cookies":{  

   },
   "statusInfo":"OK",
   "stringHeaders":{  
      "Content-Disposition":[  
         "attachment; filename=\"javatpoint_pdf.pdf\""
      ]
   },
   "links":[  

   ],
   "entityTag":null,
   "allowedMethods":[  

   ],
   "mediaType":null,
   "headers":{  
      "Content-Disposition":[  
         "attachment; filename=\"javatpoint_pdf.pdf\""
      ]
   }
}

in downloadPDF.json file



Solution 1:[1]

Try this

            HttpResponse response = HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strPath));
            response.TransmitFile(strPath); //File
            response.Flush();
            response.End();
            Response.ContentType = ContentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strPath));
            Response.WriteFile(strPath);
            Response.End();

Solution 2:[2]

Here is a spring boot example. you can refer this example https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html and attach the below class in the project

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import java.io.File;
import java.nio.file.Files;
@Controller
public class DemoController {

    @RequestMapping(value="/getpdf", method=RequestMethod.GET)
    public ResponseEntity<byte[]> getPDF() {
        File file = new File("sample.pdf"); // change to relative path
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        String filename = "output.pdf";
        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = null;
        try {
            response = new org.springframework.http.ResponseEntity<>(Files.readAllBytes(file.toPath()), headers, org.springframework.http.HttpStatus.OK);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}

Solution 3:[3]

Try this using Spring RestController

@PostMapping(value = "/slip", headers = "Accept=application/json",
            produces = "application/pdf")
    public ResponseEntity<Resource> generateSalarySlip(HttpServletRequest request,
                                                       @RequestBody   Locale locale) {
...
...
File file = new File(fileName);
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.parseMediaType("application/pdf"));

            header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=salaryslip.pdf");
            header.add("Cache-Control", "no-cache, no-store, must-revalidate");
            header.add("Pragma", "no-cache");
            header.add("Expires", "0");
         
InputStream targetStream = new FileInputStream(file);
        Resource resource = new InputStreamResource(targetStream)
            return ResponseEntity.ok()
                    .headers(header)
                    .contentLength(file.length())
                                    .contentType(MediaType.parseMediaType("application/pdf"))
                    .body(resource);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caner
Solution 2 Raj
Solution 3