All formats

Prawn

LanguageRuby 2.7+
LicenseRuby license, GPL-2.0 or GPL-3.0 (your choice)
Repositorygithub.com/prawnpdf/prawn
Documentationprawnpdf.org, the Prawn manual (PDF)
Depends onpdf-core, ttfunk, matrix, bigdecimal (gems); prawn-table for tables
Read / writeno / yes

Prawn generates PDFs from Ruby with a drawing and text-flow API: text with automatic wrapping and page breaks, inline formatting (<b>, <i>, <color>, <link>), embedded TrueType fonts with Unicode and kerning, PNG and JPEG images, vector graphics, bounding boxes and columns, repeating headers and footers, page numbering, outlines and encryption. Tables are in the separate prawn-table gem. Many Rails apps use it for invoices and reports.

Prawn can’t open or modify existing PDFs. Use CombinePDF or HexaPDF to merge its output with other files or stamp it onto templates.

Installation#

Shell
gem install prawn prawn-table

Basic usage: create a PDF with text#

Ruby
require "prawn"

Prawn::Document.generate("hello.pdf", page_size: "A4", info: { Title: "Hello", Author: "Me" }) do
  font_size 24
  text "Hello, PDF!", style: :bold
  move_down 10
  font_size 12
  text "Created with Prawn. " * 20, align: :justify  # wraps and breaks pages automatically
  stroke_horizontal_rule

  start_new_page
  text "Page 2"
  number_pages "Page <page> of <total>", at: [bounds.right - 100, 0], width: 100, align: :right
end

How to use a TrueType font for Unicode text#

The built-in PDF fonts cover only Windows-1252 characters. Register a TrueType family for other text:

Ruby
Prawn::Document.generate("unicode.pdf") do
  font_families.update("DejaVu" => {
    normal: "DejaVuSans.ttf", bold: "DejaVuSans-Bold.ttf", italic: "DejaVuSans-Oblique.ttf"
  })
  font "DejaVu"
  text "Zażółć gęślą jaźń · Привет"
  text "<b>bold</b>, <i>italic</i> and <color rgb='FF0000'>red</color>", inline_format: true
end

How to add a table#

Ruby
require "prawn"
require "prawn/table"

Prawn::Document.generate("invoice.pdf") do
  text "Invoice #1001", size: 20, style: :bold
  move_down 10
  table([["Item", "Qty", "Price"], ["Widget", "2", "9.99"], ["Gadget", "1", "24.50"]],
        header: true, column_widths: [200, 60, 80]) do
    row(0).font_style = :bold
    columns(1..2).align = :right
  end
end

How to add an image#

Ruby
pdf = Prawn::Document.new
pdf.text "Logo:"
pdf.image "logo.png", width: 200
pdf.render_file "image.pdf"

Prawn::Document.new { text "Hi" }.render returns the PDF as a string, e.g. for send_data in Rails.

How to encrypt a PDF#

Ruby
Prawn::Document.generate("secret.pdf") do
  text "Secret"
  encrypt_document(user_password: "user", owner_password: "owner",
                   permissions: { print_document: true, modify_contents: false })
end

Prawn writes RC4 40-bit encryption (revision 2), which is easy to break; re-encrypt with qpdf or HexaPDF if you need AES-256.

Tips#