Created
July 7, 2014 15:36
-
-
Save yogthos/f95d944a3e0f03c67047 to your computer and use it in GitHub Desktop.
HTML to PDF example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns html-pdf | |
(:require [clojure.xml :refer [parse]] | |
[clj-pdf.core :refer [pdf]])) | |
(def tag-map | |
{:html [{}] | |
:h1 [:paragraph {:leading 20 :style :bold :size 14}] | |
:h2 [:paragraph {:leading 20 :style :bold :size 12}] | |
:h3 [:paragraph {:leading 20 :style :bold :size 10}] | |
:hr [:line] | |
:br [:spacer] | |
:img [:image] | |
:pre [:paragraph {:size 10 :family :courier}] | |
:p [:paragraph] | |
:b [:chunk {:style :bold}] | |
:em [:chunk {:style :italic}] | |
:del [:chunk {:style :strikethru}] | |
:ul [:list {:numbered false}] | |
:ol [:list {:numbered true}] | |
:li [:chunk] | |
:a [:anchor] | |
:sup [:chunk {:super true}] | |
:strong [:chunk {:style :bold}] | |
:blockquote [:paragraph {:style :italic :indent 5}]}) | |
(defn parse-html [s] | |
(-> (str s) (.getBytes) (java.io.ByteArrayInputStream.) parse)) | |
(defn set-attrs [content {:keys [href src title]}] | |
(cond | |
href (conj content {:target href}) | |
(and title src) [:paragraph {:align :center} (conj content src) title] | |
src (into content [{:align :center} src]) | |
:else content)) | |
(defn transform-node [{:keys [tag attrs content]}] | |
(-> (or (tag tag-map) [:paragraph]) | |
(set-attrs attrs) | |
(into content))) | |
(defn md-to-pdf [html out] | |
(clojure.walk/postwalk | |
(fn [n] (if (:tag n) (transform-node n) n)) | |
(parse-html html)) | |
out)) | |
;(md-to-pdf "<html><p>Hi</p></html>" "doc.pdf") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment