我希望我的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文档保存在我的磁盘上。我希望在浏览器中得到相同的结果:在浏览器中打开相同的文档。救命啊!
1条答案
按热度按时间zbq4xfa01#
让您的PDF图书返回原始
Array[Byte]
而不是String
:返回200 OK,body为pdf,content-type为set: