将 pdf 文件作为 bytearray 发送作为响应时在 scala 中遇到错误 "Failed to load PDF document." (scala)

Facing Error "Failed to load PDF document." in scala when send pdf file as bytearray in response (scala)

我写了下面的代码来发送 pdf 文件作为响应,但我卡在了某一点它会报错 "Failed to load PDF document."

代码是:

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

  }

谁能帮我解决这个问题?

A PrintWriter 写文本很有用,但 PDF 是二进制数据。

val out = response.getOutputStream
java.nio.file.Files.copy(file.toPath, out)
out.flush()