#!/usr/bin/env ruby
#
# PDFlib client: fill Blocks with PPS to create a business card
# Required software: PDFlib Personalization Server (PPS)
#

require 'PDFlib'

# This is where font/image/PDF input files live. Adjust as necessary.
# Note that this directory must also contain font files

infile = "boilerplate.pdf"
searchpath = "../data"
# By default annotations are also imported. In some cases this
# requires the Noto fonts for creating annotation appearance streams.
fontpath =  "../../resource/font"

dataset = {
  "name" =>                   "Victor Kraxi",
  "business.title" =>         "Chief Paper Officer",
  "business.address.line1" => "17, Aviation Road",
  "business.address.city" =>  "Paperfield",
  "business.telephone.voice"=>"phone +1 234 567-89",
  "business.telephone.fax" => "fax +1 234 567-98",
  "business.email" =>         "victor@kraxi.com",
  "business.homepage" =>      "www.kraxi.com"
}

begin
  p = PDFlib.new

  # This means we must check return values of load_font() etc.
  # Set the search path for fonts and PDF files 
  p.set_option("errorpolicy=return SearchPath={{" + searchpath +"}}")
  p.set_option("SearchPath={{" + fontpath +"}}")

  if (p.begin_document("businesscard.pdf", "") == -1)
      raise "Error: " + p.get_errmsg()
  end

  p.set_info("Creator", "businesscard")
  p.set_info("Author", "Thomas Merz")
  p.set_info("Title", "PDFlib Block processing sample")

  blockcontainer = p.open_pdi_document(infile, "")
  if (blockcontainer == -1)
    raise "Error: " + p.get_errmsg()
  end

  # Loop over all pages of the input document
  pagecount = p.pcos_get_number(blockcontainer, "length:pages");
  1.step(pagecount, 1) do |pageno|
    page = p.open_pdi_page(blockcontainer, pageno, "")
    if (page == -1)
      raise "Error: " + p.get_errmsg()
    end

    p.begin_page_ext(20, 20, "");              # dummy page size

    # This will adjust the page size to the size of the input page
    p.fit_pdi_page(page, 0, 0, "adjustpage")

    # Fill all text Blocks with dynamic data
    dataset.each { |key, value|
      if (p.fill_textblock(page, key, value,
    "") == -1)
        print "Warning: " + p.get_errmsg
      end
    }

    p.end_page_ext("")
    p.close_pdi_page(page)
  end

  p.end_document("")
  p.close_pdi_document(blockcontainer)

rescue  PDFlibException => pe
  print "PDFlib exception occurred in businesscard sample:\n"
  print "[" + pe.get_errnum.to_s + "] " + pe.get_apiname + \
		  ": " + pe.get_errmsg + "\n"
rescue  Exception => e
  print e.backtrace.join("\n") + "\n" + e.to_s
ensure
  p.delete() if p
end

# vim: sw=2
