sandal / prawn

Fast, Nimble PDF Writer for Ruby

This URL has Read+Write access

sandal (author)
Sat Jun 20 06:52:55 -0700 2009
commit  29ff7a2b4c495964fff7bd0f5fa138de12878dc1
tree    7c88acdcec8d5926eb4ed0b03f9a67602ca0dae6
parent  f67b351a490fe61a0e8c0ab243922e2f2b8a01a0
prawn / examples / general / measurement_units.rb
100644 53 lines (41 sloc) 2.169 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# encoding: utf-8
#
# Generates a ruler and also demonstrates prawn/measurement_extensions.
# It's better to run this example and examine its output than to worry about
# its particular implementation, though some might find that interesting as
# well.
#
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..', 'lib'))
require "prawn/core"
 
require "prawn/measurement_extensions"
 
# this makes the following units available (Millimeters, Centimeters, Decimeters, Meters, Inches, Foot, Yards, Points)
# Methodname is the common abbravation for the unit (mm, cm, dm, m, in, ft, yd, pt)
# Usage: '10.mm'.
# This converts 10mm to PDF points, which Prawn uses internally.
 
pdf = Prawn::Document.new(
:page_size => "A4",
:left_margin => 10.mm, # different
:right_margin => 1.cm, # units
:top_margin => 0.1.dm, # work
:bottom_margin => 0.01.m) # well
 
pdf.font_size = 6
pdf.line_width = 0.05
 
units_long = %w[Millimeters Centimeters Decimeters Inches Foot Points]
units = %w[mm cm dm in ft pt]
offset_multiplier = 2.cm
temp = "Units\n"
 
units.each_with_index do |unit, unit_index| #iterate through all units that make sense to display on a sheet of paper
  one_unit_in_pt = eval "1.#{unit}" # calc the width of one unit
  temp << "1#{unit} => #{one_unit_in_pt}pt\n" #puts converted unit in points
  
  offset = offset_multiplier * unit_index
  pdf.text units[unit_index], :at => [offset + 0.5.mm, pdf.bounds.top - 2.mm]
  
  pdf.stroke_line(offset, pdf.bounds.top, offset, pdf.bounds.bottom)
  
  0.upto(((pdf.bounds.height - 5.mm) / one_unit_in_pt).to_i) do |i| # checks, how many strokes can be drawn
    pdf.stroke_line(offset, i * one_unit_in_pt, (i % 5 == 0 ? 6.mm : 3.mm) + offset, i * one_unit_in_pt) # every fifth stroke is twice as large like on a real ruler
    pdf.text "#{i}#{unit}", :at => [7.mm + offset, i * one_unit_in_pt] unless unit == "mm" && i % 5 != 0 || unit == "pt" && i % 10 != 0 # avoid text too close to each other
  end
end
 
pdf.text_box temp,
  :width => 5.cm, :height => pdf.font.height * units_long.length,
  :at => [offset_multiplier * units_long.length, pdf.bounds.top]
 
pdf.render_file "measurement_units.pdf"