Skip to content

Instantly share code, notes, and snippets.

Created October 7, 2013 12:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
(ns try-itext-compojure.handler
(:require [ring.util.response :as response]
[compojure.core :refer [defroutes GET]]
[compojure.handler :as handler]
[compojure.route :as route]
[korma.db :refer [defdb sqlite3]]
[korma.core :as korma])
(:import [com.itextpdf.text
Document PageSize Paragraph Font]
PdfWriter BaseFont PdfPTable PdfPCell]
[ ByteArrayOutputStream ByteArrayInputStream]))
(defdb db (sqlite3
{:db "db/try-itext.sqlite3"}))
(korma/defentity employees)
(def font (Font. (BaseFont/createFont
(defn cell [content]
(PdfPCell. (Paragraph. content font)))
(defn add-row [table c1 c2]
(doto table
(.addCell (cell c1))
(.addCell (cell c2))))
(defn get-table []
(let [table (PdfPTable. 2)]
(add-row table "ID" "名前")
(doseq [row (korma/select employees)]
(add-row table (str (:id row)) (:name row)))
(defn get-pdf-data []
(let [out (ByteArrayOutputStream.)]
(with-open [pdf-doc (Document. PageSize/A4 50 50 50 40)]
(doto pdf-doc
(PdfWriter/getInstance out)
(.add (get-table))))
(.toByteArray out)))
;バイト列をHTTP Responseに書き込み
(defn write-response [bytes]
(let [in (ByteArrayInputStream. bytes)]
(-> (response/response in)
(response/header "Content-Disposition" "filename=test.pdf")
(response/header "Content-Length" (count bytes))
(response/content-type "application/pdf"))))
(defroutes app-routes
(GET "/" [] (write-response (get-pdf-data)))
(route/resources "/")
(route/not-found "Not Found"))
(def app
(handler/site app-routes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment