From 8d4f373257c9f287794e895afa88cdf9e0755328 Mon Sep 17 00:00:00 2001 From: Andrew Bruce Date: Mon, 14 Oct 2024 16:45:44 +0100 Subject: [PATCH] Raise exception when font not set --- lib/mudbrick.ex | 51 ++++++++++++++++++++----------------- lib/mudbrick/font.ex | 4 +++ test/mudbrick/font_test.exs | 24 +++++++++++++++++ 3 files changed, 56 insertions(+), 23 deletions(-) diff --git a/lib/mudbrick.ex b/lib/mudbrick.ex index c0186e8..4869629 100644 --- a/lib/mudbrick.ex +++ b/lib/mudbrick.ex @@ -1,6 +1,7 @@ defmodule Mudbrick do alias Mudbrick.ContentStream alias Mudbrick.Document + alias Mudbrick.Font alias Mudbrick.Page @dpi 72 @@ -57,7 +58,7 @@ defmodule Mudbrick do ) :error -> - raise Mudbrick.Font.Unregistered, "Unregistered font: #{user_identifier}" + raise Font.Unregistered, "Unregistered font: #{user_identifier}" end end @@ -72,29 +73,33 @@ defmodule Mudbrick do &match?(%ContentStream.Tf{}, &1) ) - [first_part | parts] = String.split(text, "\n") + if latest_font_setting == nil do + raise Font.NotSet, "No font chosen" + else + [first_part | parts] = String.split(text, "\n") - context - |> ContentStream.add( - ContentStream.TL, - leading: latest_font_setting.size * 1.2 - ) - |> ContentStream.add( - ContentStream.Tj, - font: latest_font_setting.font, - text: first_part - ) - |> then(fn context -> - for part <- parts, reduce: context do - acc -> - ContentStream.add( - acc, - ContentStream.Apostrophe, - font: latest_font_setting.font, - text: part - ) - end - end) + context + |> ContentStream.add( + ContentStream.TL, + leading: latest_font_setting.size * 1.2 + ) + |> ContentStream.add( + ContentStream.Tj, + font: latest_font_setting.font, + text: first_part + ) + |> then(fn context -> + for part <- parts, reduce: context do + acc -> + ContentStream.add( + acc, + ContentStream.Apostrophe, + font: latest_font_setting.font, + text: part + ) + end + end) + end end def render({doc, _page}) do diff --git a/lib/mudbrick/font.ex b/lib/mudbrick/font.ex index 014996f..74371a9 100644 --- a/lib/mudbrick/font.ex +++ b/lib/mudbrick/font.ex @@ -15,6 +15,10 @@ defmodule Mudbrick.Font do :parsed ] + defmodule NotSet do + defexception [:message] + end + defmodule Unregistered do defexception [:message] end diff --git a/test/mudbrick/font_test.exs b/test/mudbrick/font_test.exs index c9f4192..a1c264d 100644 --- a/test/mudbrick/font_test.exs +++ b/test/mudbrick/font_test.exs @@ -87,6 +87,30 @@ defmodule Mudbrick.FontTest do assert Document.object_with_ref(doc, file.ref) end + test "forgetting to set the font is an error" do + import Mudbrick + + chain = + new() + |> page( + fonts: %{ + helvetica: [ + name: :Helvetica, + type: :TrueType, + encoding: :PDFDocEncoding + ] + } + ) + |> contents() + + e = + assert_raise Font.NotSet, fn -> + chain |> text("hi there") + end + + assert e.message == "No font chosen" + end + test "asking for an unregistered font is an error" do import Mudbrick