如何将OpenPdf(Java库)创建的OutputStream转换为可读并可通过http响应(http4s,scala)下载的pdf文档?

g6baxovj  于 2023-10-18  发布在  Scala
关注(0)|答案(1)|浏览(130)

我希望我的http服务(Scala,http 4s,Ember)接收http请求,使用OpenPdf库创建PDF文档,并使用此PDF文档向用户的浏览器做出http响应。用户应该在浏览器中看到PDF或下载它。
我有一个GET请求的路由:

case GET -> Root / "pdf" / IntVar(book) => getBookF(book) match {

        case Some(bookF: BookF) =>
          val b = createPdfSingleBook(bookF)
          Ok(b, Header.Raw(CIString("Expires"), "0"),
            Header.Raw(CIString("Cache-Control"), "must-revalidate, post-check=0, pre-check=0"),
            Header.Raw(CIString("Pragma"), "public"), Header.Raw(CIString("Content-Length"), s"${b.length}"),
            Header.Raw(CIString("Content-Type"), "application/pdf"))

        case None => NotFound()
def createPdfSingleBook(bookF: BookF): String = {

    val monolingualBook = new Document()

    val pdfOutputFile: FileOutputStream = new FileOutputStream(s"${book.id}.pdf")
    val baos: ByteArrayOutputStream = new ByteArrayOutputStream()

    val baosWriter = PdfWriter.getInstance(monolingualBook, baos)
    val pdfWriter: PdfWriter = PdfWriter.getInstance(monolingualBook, pdfOutputFile)

    monolingualBook.open()

    //Content of a pdf-document

    val res = Base64.getEncoder.encodeToString(baos.toByteArray)

    monolingualBook.close()
    baosWriter.close()
    pdfWriter.close()

    res
  }

代码中有两个OutputStreams。FileOutputStream工作,我有一个PDF文档保存在我的磁盘上。我希望在浏览器中得到相同的结果:在浏览器中打开相同的文档。救命啊!

zbq4xfa0

zbq4xfa01#

让您的PDF图书返回原始Array[Byte]而不是String

def createPdfSingleBook(bookF: BookF): Array[Byte] = {

    val monolingualBook = new Document()

    val baos: ByteArrayOutputStream = new ByteArrayOutputStream()
    val baosWriter = PdfWriter.getInstance(monolingualBook, baos)

    monolingualBook.open()

    //Content of a pdf-document
    // Use baosWriter here....

    monolingualBook.close()
    baosWriter.close()

    baos.toByteArray
  }

返回200 OK,body为pdf,content-type为set:

val pdfData :Array[Byte] = createPdfSingleBook(...)

Ok(pdfData, Header("Content-type", "application/pdf"))

相关问题