From 5c32c3fba16bad7884251e8a14459c398cb19dd6 Mon Sep 17 00:00:00 2001 From: gered Date: Tue, 29 Aug 2017 10:50:25 -0400 Subject: [PATCH] add more input argument flexibility to embed-image the main benefit here is now being able to accept byte arrays directly --- project.clj | 1 + src/clj_htmltopdf/core.clj | 19 +++++++++---------- src/clj_htmltopdf/utils.clj | 7 +++++++ 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/project.clj b/project.clj index 6dac5a4..516cf08 100644 --- a/project.clj +++ b/project.clj @@ -9,6 +9,7 @@ [com.openhtmltopdf/openhtmltopdf-pdfbox "0.0.1-RC11"] [com.openhtmltopdf/openhtmltopdf-rtl-support "0.0.1-RC11"] [com.openhtmltopdf/openhtmltopdf-svg-support "0.0.1-RC11"] + [commons-io/commons-io "2.5"] [hiccup "1.0.5"]] :profiles {:provided diff --git a/src/clj_htmltopdf/core.clj b/src/clj_htmltopdf/core.clj index e03e0b4..94f3415 100644 --- a/src/clj_htmltopdf/core.clj +++ b/src/clj_htmltopdf/core.clj @@ -14,27 +14,26 @@ [com.openhtmltopdf.pdfboxout PdfRendererBuilder] [com.openhtmltopdf.svgsupport BatikSVGDrawer] [com.openhtmltopdf.util XRLog] + [org.apache.commons.io IOUtils] [org.jsoup Jsoup] [org.jsoup.nodes Document])) (defn embed-image - "Reads an image file and encodes it as a base64 string suitable for use in a data url for displaying - inline images in tags or for use in CSS." - [image-file] + "Reads an image (provided as a filename, InputStream or byte array) and encodes it as a base64 string suitable for + use in a data url for displaying inline images in tags or for use in CSS." + [image] (try - (let [image-file (io/file image-file) - is (io/input-stream image-file) + (let [is (if-not (instance? InputStream image) + (io/input-stream image) + image) mime-type (URLConnection/guessContentTypeFromStream is) - image-bytes (byte-array (.length image-file))] - (with-open [is is] - (.reset is) - (.read is image-bytes)) + image-bytes (if (u/byte-array? image) image (IOUtils/toByteArray ^InputStream is))] (let [b64-str (.encodeToString (Base64/getEncoder) image-bytes)] (if (nil? mime-type) (str "data:" b64-str) (str "data:" mime-type ";base64," b64-str)))) (catch Exception ex - (throw (Exception. (str "Exception converting image to inline base64 string: " image-file) ex))))) + (throw (ex-info "Exception converting image to inline base64 string: " {:image image} ex))))) (defn- read-html-string ^String [in] diff --git a/src/clj_htmltopdf/utils.clj b/src/clj_htmltopdf/utils.clj index b5f54f3..ee50009 100644 --- a/src/clj_htmltopdf/utils.clj +++ b/src/clj_htmltopdf/utils.clj @@ -3,9 +3,16 @@ [java.io File] [java.net URL MalformedURLException])) +(def ^{:private true} bytes-class (Class/forName "[B")) + +(defn byte-array? + [x] + (boolean (and x (= (.getClass x) bytes-class)))) + (defn string->url-or-file [^String s] (try (URL. s) (catch MalformedURLException _ (File. (str "file:" s))))) +