#!/usr/local/bin/ruby
#
#
# ./textboxfit.rb

require "ClibPDF"

textdata = "We the People of the United States, in Order to form a more perfect Union," +
  " establish Justice, insure domestic Tranquility, provide for the common" +
  " defence, promote the general Welfare, and secure the Blessings of Liberty to" +
  " ourselves and our Posterity, do ordain and establish this Constitution for the" +
  " United States of America.\n\n"

fontsize = 14.0
angle = 0.0
x = 1.0; y = 7.0
w = 3.0; h = 2.0

tbA = [ClibPDF::TBOX_JUSTIFY, 0, 0.0, 0]

pdf = ClibPDF::PDF.open(0)
pdf.enableCompression(ClibPDF::YES)
pdf.init()
pdf.pageInit(1, ClibPDF::PORTRAIT, ClibPDF::LETTER, ClibPDF::LETTER)

textbuf = textdata
pdf.setrgbcolor(0.5, 0.5, 1.0)
pdf.rect(x, y, w, h)
pdf.stroke
pdf.setgray(0.0)

pdf.beginText(0)
pdf.setFont("Helvetica", "MacRomanEncoding", fontsize)
fontsizeused = pdf.textBoxFit(x, y, w, h, angle, fontsize, 0.5, -1.2, tbA, textbuf)
strbuf = sprintf("Font size: asked=%g,  used=%g", fontsize, fontsizeused)
pdf.setrgbcolor(1.0, 0.0, 0.0)
pdf.textAligned(x, y - 0.03, angle, ClibPDF::TEXTPOS_UL, strbuf)
pdf.endText

angle = 25.0
x = 5.0; y = 7.0
w = 1.5; h = 1.5
pdf.setrgbcolor(0.5, 0.5, 1.0)
pdf.rectRotated(x, y, w, h, angle)
pdf.moveto(x, y)
pdf.lineto(x + w, y)
pdf.arc(x, y, 0.35, 0.0, angle, 1)
pdf.stroke
pdf.setgray(0.0)

pdf.beginText(0)
pdf.setFont("Helvetica", "MacRomanEncoding", fontsize)
fontsizeused = pdf.textBoxFit(x, y, w, h, angle, fontsize, 0.5, -1.2, tbA, textbuf)

strbuf = sprintf("Font size: asked=%g,  used=%g", fontsize, fontsizeused)
pdf.setrgbcolor(1.0, 0.0, 0.0)
pdf.textAligned(x, y-0.05, 0.0, ClibPDF::TEXTPOS_UL, strbuf)
pdf.setrgbcolor(0.0, 0.0, 1.0)
pdf.setFont("Helvetica-BoldOblique", "MacRomanEncoding", 8.0)
pdf.text(x + 0.37, y + 0.05, 0.0, "angle")
pdf.textAligned(x - 0.05, y, 0.0, ClibPDF::TEXTPOS_MR, "(xl, yl)")
xr = 0.75; yr = -0.025
xr, yr = ClibPDF.rotate_xyCoordinate(xr, yr, angle)
pdf.textAligned(x + xr, y + yr, angle, ClibPDF::TEXTPOS_UM, "width")
xr = 0.75; yr = 0.05
xr, yr = ClibPDF.rotate_xyCoordinate(xr, yr, angle + 90.0)
pdf.textAligned(x + xr, y + yr, angle + 90.0, ClibPDF::TEXTPOS_LM, "height")
pdf.endText

pdf.finalizeAll
pdf.savePDFmemoryStreamToFile("textboxfit.pdf")

#pdf.launchPreview()
pdf.close
