Pdf (PDF v0.8.0)

View Source

The missing PDF library for Elixir.

Usage

Pdf.build([size: :a4, compress: true], fn pdf ->
  pdf
  |> Pdf.set_info(title: "Demo PDF")
  |> Pdf.set_font("Helvetica", 10)
  |> Pdf.text_at({200,200}, "Welcome to Pdf")
  |> Pdf.write_to("test.pdf")
end)

Page sizes

The available page sizes are:

  • :a0 - :a9
  • :b0 - :b9
  • :c5e
  • :comm10e
  • :dle
  • :executive
  • :folio
  • :ledger
  • :legal
  • :letter
  • :tabloid
  • a custom size [width, height] in Pdf points.

or you can also specify a tuple {size, :landscape}.

Summary

Types

A code specifying the shape of the endpoints for an open path that is stroked.

Specify a color by it's CMYK make-up.

Use one of the colors in the Pdf.Color module.

Most functions take a coordinates tuple, {x, y}. In Pdf these start from the bottom-left of the page.

Width and height expressed in Pdf points

The height in points

The line join style shall specify the shape to be used at the corners of paths that are stroked.

Specify a color by it's RGB make-up.

The width in points

x()

The x-coordinate

y()

The y-coordinate

Functions

Add a font to the list of available fonts.

Add an images (PNG, or JPEG only) at the given coordinates.

Add an images (PNG, or JPEG only) at the given coordinates.

Add a new page to the Pdf with the current page size.

Add a new page to the Pdf with the given page size.

Adds an autoprint action to the Pdf.

Builds a PDF document taking care of cleaning up resources on completion.

Stop the Pdf process releasing all document memory.

Convert the given value from cm to Pdf points

Create an image from binary data. Only PNG and JPEG images are supported. The image can be drawn with draw_image/3.

Gets the current cursor position, that is the vertical position.

delete(pid) deprecated

Draw an image at the given coordinates. The image should be previously created with create_image/2.

Export the Pdf to a binary representation.

Fill the current drawing with the previously set color.

Convert the given value from inches to Pdf points

Draw a line between 2 points.

Draw a line from the last position to the given coordinates.

Add a clickable link annotation to the current page.

Add a clickable link annotation to a specific page number in the document.

Convert the given value from mm to Pdf points

Move the cursor amount points down.

Move the cursor to the given coordinates.

Create a new Pdf process

Returns the current page number.

Convert the given value from picas to Pdf points

Convert the given value from pixels to Pdf points

The unit of measurement in a Pdf are points, where 1 point = 1/72 inch. This means that a standard A4 page, 8.27 inch, translates to 595 points.

Draw a rectangle from coordinates x,y (lower left corner) for a given width and height.

Remove the current page from the Pdf.

Render a table in the document at the given coordinates.

Sets the author in the PDF information section.

Sets the creator in the PDF information section.

Set the cursor position.

Set the color to use when filling.

Sets the font that will be used for all text from here on. You can either specify the font size, or a list of options

Sets the font size.

Set multiple keys in the PDF information section.

Sets the keywords in the PDF information section.

The line endings to draw, see cap_style/0.

The join style to use where lines meet, see join_style/0.

The width to use when drawing lines.

Sets the producer in the PDF information section.

Set the color to use when drawing lines.

Sets the subject in the PDF information section.

Leading is a typography term that describes the distance between each line of text. The name comes from a time when typesetting was done by hand and pieces of lead were used to separate the lines.

Sets the title in the PDF information section.

Returns a {width, height} for the current page.

Perform all the previous graphic commands.

Add a table in the document at the given coordinates.

Add a table in the document at the given coordinates. Raises an exception if the table does not fit the dimensions.

Writes the text at the given coordinates. The coordinates are the bottom left of the text baseline.

Writes the text at the given coordinates. The coordinates are the bottom left of the text.

This function draws a number of text lines starting at the given coordinates. The list can overrun the page, no errors or wrapping will occur.

Writes the text wrapped within the confines of the given dimensions. The {x,y} is the top-left of corner of the box, for this reason it is not wise to try to match it up with text_at on the same line.

This function has the same options as text_wrap/4, but also supports additional options that will be applied to the complete text.

This function has the same options as text_wrap/4, but if the text is too large for the box, a RuntimeError will be raised.

This function has the same options as text_wrap/5, but if the text is too large for the box, a RuntimeError will be raised.

Write the PDF to the given path

Types

cap_style()

@type cap_style() :: :butt | :round | :projecting_square | :square | integer()

A code specifying the shape of the endpoints for an open path that is stroked.

  • :butt (default)

    The stroke shall be squared of at the endpoint of the path.

  • :round

    A small semicircular arc with a diameter equal to the line width shall be drawn around the endpoint and shall be filled in.

  • :square | :projecting_square

    The stroke shall continue beyond the endpoint of the path for a distance equal to half the line width and shall be squared of.

cmyk()

@type cmyk() :: {float(), float(), float(), float()}

Specify a color by it's CMYK make-up.

color_name()

@type color_name() :: atom()

Use one of the colors in the Pdf.Color module.

continuation()

@type continuation() :: {:continue, Pdf.Table.t()}

coords()

@type coords() :: {x(), y()}

Most functions take a coordinates tuple, {x, y}. In Pdf these start from the bottom-left of the page.

dimension()

@type dimension() :: {width(), height()}

Width and height expressed in Pdf points

height()

@type height() :: number()

The height in points

join_style()

@type join_style() :: :miter | :round | :bevel | integer()

The line join style shall specify the shape to be used at the corners of paths that are stroked.

  • :miter

    The outer edges of the strokes for the two segments shall be extended until they meet at an angle. If the segments meet at too sharp an angle (as defined in section 8.4.3.5 of the PDF specs), a bevel join shall be used instead.

  • :round

    An arc of a circle with a diameter equal to the line width shall be drawn around the point where the two segments meet, connecting the outer edges of the strokes for the two segments. This pieslice-shae figure shall be filled in, producing a rounded corner.

  • :bevel

    The two segments shall be finished with butt caps (see cap_style/0) and the resulting notch beyond the ends of the segments shall be filled with a triangle.

rgb()

@type rgb() :: {byte(), byte(), byte()}

Specify a color by it's RGB make-up.

table()

@type table() :: Pdf.Table.t()

width()

@type width() :: number()

The width in points

x()

@type x() :: number()

The x-coordinate

y()

@type y() :: number()

The y-coordinate

Functions

add_font(pid, path)

Add a font to the list of available fonts.

Currently only Type 1 AFM/PFB fonts are supported.


fonts_dir = Application.app_dir(:my_app) |> Path.join("priv", "fonts")

pdf
|> Pdf.add_font(Path.join(fonts_dir, "DejavuSans.afm")
|> Pdf.add_font(Path.join(fonts_dir, "DejavuSans-Bold.afm")

The font can then be set with set_font/3.

You have to add_font/2 all variants you want to use, bold, italic, ...

add_image(pid, coords, image_path)

This function is deprecated. Use create_image/2 and draw_image/3 instead.

Add an images (PNG, or JPEG only) at the given coordinates.

add_image(pid, coords, image_path, opts)

Add an images (PNG, or JPEG only) at the given coordinates.

You can specify a :width and :height in the options, the image will then be scaled.

add_page(pid)

Add a new page to the Pdf with the current page size.

The new page will inherit the font from the current page, if set.

add_page(pid, size)

Add a new page to the Pdf with the given page size.

The new page will inherit the font from the current page, if set.

autoprint(pid)

Adds an autoprint action to the Pdf.

This is can be useful for generating a PDF that will automatically open the print dialog in a browser

build(opts \\ [], func)

Builds a PDF document taking care of cleaning up resources on completion.

Pdf.build([size: :a3], fn pdf ->
  pdf
  |> Pdf.set_font("Helvetica", 12)
  |> Pdf.text_at({100, 100}, "Open")
  |> Pdf.write_to("test.pdf")
end)

is equivalent to

{:ok, pdf} = Pdf.new(size: :a3)
pdf
|> Pdf.set_font("Helvetica", 12)
|> Pdf.text_at({100, 100}, "Open")
|> Pdf.write_to("test.pdf")
|> Pdf.cleanup()

cleanup(pid)

Stop the Pdf process releasing all document memory.

cm(x)

@spec cm(number()) :: integer()

Convert the given value from cm to Pdf points

create_image(pid, image_path)

Create an image from binary data. Only PNG and JPEG images are supported. The image can be drawn with draw_image/3.

cursor(pid)

@spec cursor(pid()) :: number()

Gets the current cursor position, that is the vertical position.

delete(pid)

This function is deprecated. Use cleanup/1 instead.

draw_image(pid, coords, image, opts \\ [])

Draw an image at the given coordinates. The image should be previously created with create_image/2.

The image will be drawn with its bottom left corner at the given coordinates.

Options:

  • :width (optional) the width to draw the image at
  • :height (optional) the height to draw the image at

If only width or height is provided, the image will be scaled relative to the supplied dimension. If neither is provided, the image will be drawn at its original size.

The cursor will be set to the y coordinate of the image

export(pid)

Export the Pdf to a binary representation.

This is can be used in eg Phoenix to send a PDF to the browser.

  report =
    pdf
    |> ...
    |> Pdf.export()

 conn
  |> put_resp_content_type("application/pdf")
  |> put_resp_header(
    "content-disposition",
    "attachment; filename=\"document.pdf\""
  )
  |> send_resp(200, report)

fill(pid)

@spec fill(pid()) :: pid()

Fill the current drawing with the previously set color.

inches(x)

@spec inches(number()) :: integer()

Convert the given value from inches to Pdf points

line(pid, coords, coords_to)

@spec line(pid(), coords(), coords()) :: pid()

Draw a line between 2 points.

line_append(pid, coords)

@spec line_append(pid(), coords()) :: pid()

Draw a line from the last position to the given coordinates.

  pdf
  |> Pdf.move_to({100, 100})
  |> Pdf.line_append({200, 200})

link(pid, coords, dimensions, uri)

@spec link(pid(), coords(), dimension(), binary()) :: pid()

Add a clickable link annotation to the current page.

The coordinates {x, y} are the lower-left corner of the link rectangle. The dimensions {w, h} are the width and height of the rectangle.

mm(x)

@spec mm(number()) :: integer()

Convert the given value from mm to Pdf points

move_down(pid, amount)

Move the cursor amount points down.

move_to(pid, coords)

@spec move_to(pid(), coords()) :: pid()

Move the cursor to the given coordinates.

new(opts \\ [])

@spec new(any()) :: :ignore | {:error, any()} | {:ok, pid()}

Create a new Pdf process

The following options can be given:

:sizePage size, defaults to :a4
:compressCompress the Pdf, default: true

There is no standard font selected when creating a new PDF, so set one with set_font/3 before adding text.

open(opts \\ [], func)

This function is deprecated. Use build/2 instead.

page_number(pid)

Returns the current page number.

picas(x)

@spec picas(number()) :: number()

Convert the given value from picas to Pdf points

pixels_to_points(pixels, dpi \\ 300)

@spec pixels_to_points(pixels :: number(), dpi :: number()) :: integer()

Convert the given value from pixels to Pdf points

points(x)

The unit of measurement in a Pdf are points, where 1 point = 1/72 inch. This means that a standard A4 page, 8.27 inch, translates to 595 points.

rectangle(pid, coords, dimensions)

@spec rectangle(pid(), coords(), dimension()) :: pid()

Draw a rectangle from coordinates x,y (lower left corner) for a given width and height.

remove_page(pid)

@spec remove_page(pid()) :: pid()

Remove the current page from the Pdf.

render_table(pid, coords, dimensions, table)

@spec render_table(pid(), coords(), dimension(), table()) ::
  {pid(), :complete | continuation()}

Render a table in the document at the given coordinates.

render_table!(pid, coords, dimensions, table)

restore_state(pid)

save_state(pid)

set_author(pid, author)

Sets the author in the PDF information section.

set_creator(pid, creator)

Sets the creator in the PDF information section.

set_cursor(pid, y)

@spec set_cursor(pid(), number()) :: pid()

Set the cursor position.

set_fill_color(pid, color)

@spec set_fill_color(pid(), color_name() | rgb() | cmyk()) :: pid()

Set the color to use when filling.

This takes either a Pdf.Color.color/1 atom, an RGB tuple or a CMYK tuple.

set_font(pid, font_name, opts)

@spec set_font(pid(), binary(), integer() | list()) :: pid()

Sets the font that will be used for all text from here on. You can either specify the font size, or a list of options:

OptionValueDefault
:sizeinteger10
:boldbooleanfalse
:italicbooleanfalse

set_font_size(pid, size)

Sets the font size.

The font has to have been previously set!

set_info(pid, info_list)

@spec set_info(pid(), info_list()) :: pid()

Set multiple keys in the PDF information section.

Valid keys

  • :author
  • :created
  • :creator
  • :keywords
  • :modified
  • :producer
  • :subject
  • :title

set_keywords(pid, keywords)

Sets the keywords in the PDF information section.

set_line_cap(pid, style)

@spec set_line_cap(pid(), cap_style()) :: pid()

The line endings to draw, see cap_style/0.

set_line_join(pid, style)

@spec set_line_join(pid(), join_style()) :: pid()

The join style to use where lines meet, see join_style/0.

set_line_width(pid, width)

@spec set_line_width(pid(), number()) :: pid()

The width to use when drawing lines.

set_producer(pid, producer)

Sets the producer in the PDF information section.

set_stroke_color(pid, color)

@spec set_stroke_color(pid(), color_name() | rgb() | cmyk()) :: pid()

Set the color to use when drawing lines.

This takes either a Pdf.Color.color/1 atom, an RGB tuple or a CMYK tuple.

set_subject(pid, subject)

Sets the subject in the PDF information section.

set_text_leading(pid, leading)

Leading is a typography term that describes the distance between each line of text. The name comes from a time when typesetting was done by hand and pieces of lead were used to separate the lines.

Today, leading is often used synonymously with "line height" or "line spacing."

set_title(pid, title)

Sets the title in the PDF information section.

size(pid)

Returns a {width, height} for the current page.

stroke(pid)

@spec stroke(pid()) :: pid()

Perform all the previous graphic commands.

table(pid, coords, dimensions, data, opts \\ [])

This function is deprecated. Use render_table/4 instead.

Add a table in the document at the given coordinates.

See Tables for more information on how to use tables.

table!(pid, coords, dimensions, data, opts \\ [])

This function is deprecated. Use render_table!/4 instead.

Add a table in the document at the given coordinates. Raises an exception if the table does not fit the dimensions.

See Tables for more information on how to use tables.

text_at(pid, coords, text)

Writes the text at the given coordinates. The coordinates are the bottom left of the text baseline.

The text can be either a binary or a list of binaries or annotated binaries. All text will be drawn on the same line, no wrapping will occur, it may overrun the page.

When given a list, you can supply a mix of binaries and annotated binaries. An annotated binary is a tuple {binary, options}, with the options being:

OptionValueDefault
:font_sizeintegercurrent
:boldbooleanfalse
:italicbooleanfalse
:leadingintegercurrent
:color:atomcurrent

When setting bold: true or italic: true, make sure that your current font supports these or an error will occur. If using an external font, you have to add_font/2 all variants you want to use.

text_at(pid, coords, text, opts)

Writes the text at the given coordinates. The coordinates are the bottom left of the text.

The text can be either a binary or a list of binaries or annotated binaries, see text_at/3. All text will be drawn on the same line, no wrapping will occur, it may overrun the page.

The :kerning option if set to true will apply to all rendered text. Kerning refers to the spacing between the characters of a font. Without kerning, each character takes up a block of space and the next character is printed after it. When kerning is applied to a font, the characters can vertically overlap. This does not mean that the characters actually touch, but instead it allows part of two characters to take up the same vertical space. Kerning is available in some fonts.

text_lines(pid, coords, lines, opts \\ [])

@spec text_lines(pid(), coords(), list(), keyword()) :: pid()

This function draws a number of text lines starting at the given coordinates. The list can overrun the page, no errors or wrapping will occur.

Kerning can be set, see text_at/4 for more information.

text_wrap(pid, coords, dimensions, text)

@spec text_wrap(pid(), coords(), dimension(), binary() | list()) ::
  {pid(), :complete | term()}

Writes the text wrapped within the confines of the given dimensions. The {x,y} is the top-left of corner of the box, for this reason it is not wise to try to match it up with text_at on the same line.

The y-coordinate can also be set to :cursor.

The text will break at whitespace, such as, space, soft-hyphen, hyphen, cr, lf, tab, ...

If the text is too large for the box, it may overrun its boundaries, but only horizontally.

This function will return a tuple {pid, :complete} if all text was rendered, or {pid, remaining} if not. It can subsequently be called with the remaining data, after eg starting a new page, until {pid, :complete}.

The text can be either a binary or a list of binaries or annotated binaries. The :kerning option if set will apply to all rendered text.

When given a list, you can supply a mix of binaries and annotated binaries. An annotated binary is a tuple {binary, options}, with the options being:

OptionValueDefault
:font_sizeintegercurrent
:boldbooleanfalse
:italicbooleanfalse
:leadingintegercurrent
:color:atomcurrent

When choosing :bold or :italic, make sure that your current font supports these or an error will occur. If using an external font, you have to add_font/2 all variants you want to use.

text_wrap(pid, coords, dimensions, text, opts)

@spec text_wrap(pid(), coords(), dimension(), binary() | list(), keyword()) ::
  {pid(), :complete | term()}

This function has the same options as text_wrap/4, but also supports additional options that will be applied to the complete text.

OptionValueDefault
:align:left , :center , :right:left
:kerningbooleanfalse

text_wrap!(pid, coords, dimensions, text)

@spec text_wrap!(pid(), coords(), dimension(), binary() | list()) :: pid()

This function has the same options as text_wrap/4, but if the text is too large for the box, a RuntimeError will be raised.

text_wrap!(pid, coords, dimensions, text, opts)

@spec text_wrap!(pid(), coords(), dimension(), binary() | list(), keyword()) :: pid()

This function has the same options as text_wrap/5, but if the text is too large for the box, a RuntimeError will be raised.

write_to(pid, path)

Write the PDF to the given path