paint-brush
Generate a PDF from HTML [A How To Guide feat. Elixir]by@domino.steve
2,178 reads
2,178 reads

Generate a PDF from HTML [A How To Guide feat. Elixir]

by SteveDecember 19th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This tutorial assumes you have basic experience with the Elixir language. By the end of this article, you should have a working mix project that can generate a PDF from an HTML template and a mapping file. The resulting PDF will be sent to S3, but for now, we just want to see the result of all our hard work. We’re ready to run a code that generates a PDF using Elixir’s ‘PDFer’ and ‘Pdfer’.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Generate a PDF from HTML [A How To Guide feat. Elixir]
Steve HackerNoon profile picture

By the end of this article, you should have a working mix project that can generate a PDF from an

HTML
template and
json
payload.

This tutorial assumes you have basic experience with the Elixir language.

Generate a New Mix Project

Obviously, you can call your project w/e you want. For the sake of this article, I’ll call mine “PDFer” because it PDFs things. No other reason…

We’ll generate our project using

mix
. Running
mix new pdfer --sup
(or w/e you call your project) will produce something resembling the following output:

Once the project is created, change into the project directory (

cd pdfer
) and open it in your editor — 
code .
if you’re using VSCode (and have that configured).

Once open, you should see the following files:

Install Dependencies

We actually only need three dependencies (two depending on how you decide to do it).

elixir-pdf-generator: This will handle the actual generation of the PDF

jason: This will be used to parse our template “mapping” data.

NOTE: I’d love some insight from the Elixir community on the differences between jason and poison, and if there is a growing preference.

bbmustache: This handles merging our

json
mapping with our template file. It’s all done using mustache, so it’s super clean and simple.

Initially, I tried using the library you’re linked to from mustache’s own website, however, I wasn’t able to get it working non-empty lists and inverted-selections (something I needed).

After adding the above dependencies to your

mix.exs
, it should look something like this: 

defp deps do
  [
    {:bbmustache, github: "soranoba/bbmustache"},
    {:jason, "~> 1.1"},
    {:pdf_generator, ">=0.5.5"}
  ]
end

Install all our dependencies with

mix deps.get
and get ready to write some code…

Ready to Write Some Code!

In the Pdfer module, you’ll see a hello method. We’re going to replace this with a generate method. generate will do a couple of things:

  1. Read both the
    template
    and
    mapping
    files from disk. This step is actually optional. If you wanted to, you could simply create the variables
    template
    and
    mapping
    and set their values inline to be
    html
    and
    json
    respectively. I’m reading from disk for now simply because it’s more useful out-of-the-box if you wanted to start generating PDFs right away.
  2. bbmustache
    will take the
    template
    and
    mapping
    and “mustache” them together for us. This is actually really awesome because, otherwise, we’d have to do some messy string interpolation stuff. And frankly, it would be impossible if you were trying to use multiple templates and mappings to generate different PDFs.
  3. Generate a PDF. For now, we’ll be using
    wkhtmltopdf
    to generate our PDF, however, I’d love to explore using
    puppeteer
    and headless chrome in the future. Luckily,
    elixir-pdf-generator
    gives us that flexibility.
  4. Write the resulting PDF to disk. In the future, we could send the resulting PDF somewhere like S3, but for now, we just want to see the result of all our hard work!
defmodule Pdfer do
  @moduledoc """
  Documentation for Pdfer.
  """

  # 
  def generate(pdf_path, template_path, mapping_path) do
    mapping = Jason.decode!(read_file(mapping_path))
    template = read_file(template_path)

    template
    |> :bbmustache.render(mapping, key_type: :binary)
    |> PdfGenerator.generate_binary!()
    |> (&File.write("#{pdf_path}.pdf", &1)).()
  end

  #
  defp read_file(filepath) do
    __DIR__
    |> Path.join(filepath)
    |> File.read!()
  end
end

Last Step

Depending on if you decided to read these from disk, or just drop them into the code inline, the final pieces to this may or may not be adding the

template.html
and
mapping.json
files.

For now, we’ll just dump both of them in the file alongside our module. Create a

template.html
and
mapping.json
at
pdfer/lib/
with the following contents:

<html>
  <body>
    <h1>Hello {{ location }}</h1>
  </body>
</html>
{"location": "World"}

Generate a PDF

That’s it! We’re ready to generate a PDF. Run our code with

iex -S mix
to drop into
iex
. From there we’ll run our module, giving it three arguments. A PDF name, the template file name, and the mapping file name:

iex(1)> Pdfer.generate("test", "template.html", "mapping.json"

Almost instantly, you should see a

test.pdf
in the root of your project directory.

Conclusion

It’s pretty awesome that, with barely 20 lines of code, we’re able to generate a PDF from a dynamic template and data set.

From here you could set up an endpoint to accept a payload and generate the PDF that way. Or, as I’ll explain in another article, you could set up a sweet AWS messaging pipe that your PDFer reads from!