On Aug 3, 6:49 pm, Luke Renn <
luke.r...@gmail.com> wrote:
> (import 'java.io.ByteArrayOutputStream)
> (import 'java.io.ByteArrayInputStream)
> (import 'com.lowagie.text.Document)
> (import 'com.lowagie.text.DocumentException)
> (import 'com.lowagie.text.Paragraph)
> (import 'com.lowagie.text.pdf.PdfWriter)
>
> (defn gen-pdf-stream [title]
> (let [doc (new Document)
> stream (ByteArrayOutputStream.)
> writer (PdfWriter/getInstance doc stream)]
> (.open doc)
> (.add doc (Paragraph. title))
> (.close doc)
> (ByteArrayInputStream. (.toByteArray stream))))
>
> (defroutes example-app
> (GET "/pdf" [{:headers {"Content-Type" "application/pdf"}}
> (gen-pdf-stream "Lorum Ipsum")]))
>
> (run-server {:port 8080} "/*" (servlet example-app))
>
I do exactly the same thing with pdfs and zip archives created on the
fly. The only difference is, i use
(import [org.apache.commons.io.output ByteArrayOutputStream])
I do not even know why. I just read on the commons API documentation
that their implementation of ByteArrayOutputStream is supposedly "more
robust".
Having said that i have a question.
It looks to me that
(ByteArrayInputStream. (.toByteArray stream))
is a bottleneck, especialy for big multi-megabyte files.
(.toByteArray stream) copies the data into new object, doubling memory
usage, and possibly taking some time in case of big files.
Is there a library that exposes InputStream and OutputStream
interfaces on the same object, sharing the internal buffer, so no
unnecessary copying happens ?