0

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?

UNV
  • 33
  • 6
  • 4
    It looks like you load the `data` array (`fis.read(data)`) and then throw it all away (`data = bos`). – jwvh Feb 26 '20 at 11:08

1 Answers1

1

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()

cbley
  • 4,133
  • 1
  • 14
  • 29