Sha256: 981a25a7391d278567bafc54f21b5baee8c50fb5d175529cf9c14ddf4db55f2a

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

# ## Text Box Alignment
#
# The [HexaPDF::Layout::TextBox] class can be used to easily lay out text inside
# a rectangular area, with various horizontal and vertical alignment options.
#
# The text inside the box can be aligned horizontally by setting
# [HexaPDF::Layout::Style#align] and vertically by
# [HexaPDF::Layout::Style#valign]. In this example, a sample text is laid out in
# all possible combinations.
#
# Usage:
# : `ruby text_box_alignment.rb`
#

require 'hexapdf'

sample_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. at".tr("\n", ' ')

doc = HexaPDF::Document.new
canvas = doc.pages.add.canvas
canvas.font("Times", size: 10, variant: :bold)

width = 100
height = 150
y_base = 800
box = HexaPDF::Layout::TextBox.create(sample_text, width: width,
                                      height: height,
                                      font: doc.fonts.load("Times"))

[:left, :center, :right, :justify].each_with_index do |align, x_index|
  x = x_index * (width + 20) + 70
  canvas.text(align.to_s, at: [x + 40, y_base + 15])

  [:top, :center, :bottom].each_with_index do |valign, y_index|
    y = y_base - (height + 30) * y_index
    canvas.text(valign.to_s, at: [20, y - height / 2]) if x_index == 0

    box.style.align(align).valign(valign)
    box.draw(canvas, x, y, fit: true)
    canvas.stroke_color(128, 0, 0).rectangle(x, y, width, -height).stroke
  end
end

doc.write("text_box_alignment.pdf", optimize: true)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hexapdf-0.5.0 examples/text_box_alignment.rb