class

PDF::Document

Inherits Reference < Object

Represents a PDF document.

A PDF document consists of a collection of objects that describe the structure and content of the document. The main components are:

  • Catalog: The root of the document's object hierarchy
  • Pages tree: A tree structure containing all pages
  • Resources: Fonts, images, and other shared resources

Basic Usage

pdf = PDF::Document.new

pdf.page do |page|
  page.font "Helvetica", size: 12
  page.text "Hello, World!", at: {72, 720}
end

pdf.save("output.pdf")

Constants

PAGE_SIZES = { letter: {612, 792}, a4: {595, 842}, legal: {612, 1008}, tabloid: {792, 1224}, a3: {842, 1191}, a5: {420, 595}, executive: {522, 756}, }

Default page size constants (in points, 72 points = 1 inch)

Constructors

Instance methods

allocate_object_id

Allocates a new object ID.

Source
author
Source
author=(author : String | Nil)
Source
catalog

Builds and returns the catalog object.

Source
creator
Source
creator=(creator : String | Nil)
Source
finalize!

Finalizes all pages and objects for writing. Called by the writer before serialization.

Source
font(name : String) : Fonts::Base

Gets or registers a font by name.

Source
info_dict

Returns the document info dictionary, or nil if no metadata.

Source
keywords
Source
keywords=(keywords : String | Nil)
Source
load_font(path : String) : Fonts::TrueTypeFont

Loads a TrueType font from a file path.

The font will be automatically subsetted to include only the glyphs used in the document.

my_font = pdf.load_font("./fonts/OpenSans-Regular.ttf")
pdf.page do |page|
  page.font my_font, size: 12
  page.text "Hello!", at: {72, 720}
end
Source
load_font(data : Bytes, name : String = "embedded") : Fonts::TrueTypeFont

Loads a TrueType font from bytes.

Source
objects

All indirect objects in the document

Source
page(width : Number = 612, height : Number = 792, &block : Page -> ) : Page

Creates a new page and yields it for content.

pdf.page do |page|
  page.text "Hello!", at: {72, 720}
end
Source
page(size : Symbol, orientation : Symbol = :portrait, &block : Page -> ) : Page

Creates a new page with a named size.

pdf.page(size: :a4) do |page|
  page.text "A4 page", at: {72, 800}
end
Source
pages

All pages in the document

Source
pages_root

Builds and returns the pages tree root.

Source
producer
Source
producer=(producer : String)
Source
register_object(value : Objects::Base) : Objects::Indirect

Registers an indirect object and returns it.

Source
save(path : String) : Nil

Saves the document to a file.

Source
subject
Source
subject=(subject : String | Nil)
Source
title

Document metadata

Source
title=(title : String | Nil)

Document metadata

Source
to_slice

Returns the document as bytes.

Source
truetype_fonts

Gets all TrueType fonts used in this document.

Source
write(io : IO) : Nil

Writes the document to an IO.

Source