I write the below code for send pdf file as a response, but I stuck at one point it will give an error "Failed to load PDF document."
Code is :
def downloadResumeFile(downloadFilePath: String, response: HttpServletResponse): ResponseEntity[String] = {
val filename = "somefile.pdf"
val file = new File(filename)
println(file.exists())
val fis = new FileInputStream(file)
var data = new Array[Byte](file.length.asInstanceOf[Int])
fis.read(data)
val bos = new ByteArrayOutputStream()
data = bos.toByteArray
response.setContentType("application/pdf; charset=UTF-8")
response.setHeader("Content-Disposition", s"attachment;filename="+downloadFilePath)
response.setCharacterEncoding("UTF-8")
val servletOutputStream = new PrintWriter(response.getOutputStream)
servletOutputStream.println(data)
fis.close()
bos.flush()
bos.close()
servletOutputStream.flush()
servletOutputStream.close()
ResponseEntity.ok("File downloaded")
}
Can anyone help me get out of this question?
A PrintWriter
is useful to write text, but PDFs are binary data.
val out = response.getOutputStream
java.nio.file.Files.copy(file.toPath, out)
out.flush()