Search code examples
clojureopenpdf

Load a font in OpenPDF using Clojure


I'm trying out OpenPDF in Clojure. I manage to make a simple document, but there are font problems.

Here's some failing code:

(ns invoice.download.pdf
  (:require
   [clojure.java.io :as io])
  (:import [com.lowagie.text Font FontFactory Paragraph]
           [com.lowagie.text.pdf BaseFont]))

(defn- add-invoice [document]
  (let [font  (-> (io/resource "fonts/Helvetica.ttf")
                  (.toString)
                  (BaseFont/createFont BaseFont/IDENTITY_H BaseFont/NOT_EMBEDDED)
                  (Font. 12))]
    (.add document (Paragraph. "Invoice" font))))

Something crashes when setting font size, but no exception is thrown. It seems no font is created, even though that part of the code executes fine apart from setting font size.


Solution

  • You can use clj-pdf which wraps open-pdf, I believe using custom-ttf-fonts should work:

    (:use clj-pdf.core)
    (pdf
      [{:font {:encoding :unicode
               :ttf-name "fonts/proxima_nova_extrabold.ttf"}}
       [:phrase "Testing 123"]
       [:phrase "some text"]
       [:phrase "some more text"]
       [:paragraph "yet more text"]]
      "doc.pdf")