【问题标题】:create pdf using reactor flux and openpdf使用反应堆通量和 openpdf 创建 pdf
【发布时间】:2020-02-04 05:20:57
【问题描述】:

我正在尝试使用 libre/openpdf (https://github.com/LibrePDF/OpenPDF) 和 spring 的路由器功能在内存中创建一个 pdf。

我有一个包含 pdf 内容的 com.lowagie.text.Element Flux。

使用的com.lowagie.text.pdf.PdfWriter 采用com.lowagie.text.DocumentOutputStream。将Elements 添加到Document,并将数据写入OutputStream

我需要将Outputstream 中的输出写入org.springframework.web.reactive.function.server.ServerResponse 的正文。

我尝试使用以下方法解决此问题:

//inside the routerfunctionhandler

val content: Flux<Element> = ...
val byteArrayOutputStream = ByteArrayOutputStream()
val document = Document()
PdfWriter.getInstance(document, byteArrayOutputStream)
document.open()

content.doOnNext { element ->
    document.add(element)
}
    .ignoreElements()
    .block()
document.close()
byteArrayOutputStream.toByteArray().toMono()
    .let { 
        ok().body(it.subscribeOn(Schedulers.elastic())) 
    }

上述方法有效,但在弹性线程内有一个丑陋的块,不保证清理资源。

有没有一种简单的方法可以将OutputStream 的输出转换为DataBuffers 的通量?

【问题讨论】:

    标签: spring-webflux project-reactor openpdf


    【解决方案1】:

    试试then(...)-Operator,因为它让第一个单声道完成,然后播放另一个单声道。

    ...
    content.doOnNext { element ->
        document.add(element)
    }
    // .ignoreElements() // necessary?
    .doFinally(signal -> document.close())
    .then(byteArrayOutputStream.toByteArray().toMono())
    ...
    

    我认为它应该在没有.ignoreElements() 的情况下工作。

    【讨论】:

    • 好的,确实,我使用Mono.using 的变体实现了这一点,以确保文档已关闭,并结合then 从 outputStream 返回字节数组。
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2017-10-17
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多