#!/usr/local/bin/ruby
#
# text2pdf.rb : Convert text files to PDF
#     original C version by Thomas Merz
#     rewritten in Ruby by TAKAHASHI Hitoshi
#

require 'pdflib'
require 'getopts'


def usage
  STDERR.print <<EOS
text2pdf - convert text files to pdf. (C) Thomas Merz 1997-2000
  rewritten in Ruby by TAKAHASHI Hitoshi 1999-2000
usage: ruby #{$0} [options] [textfile]
Available options:
-f fontname   name of font to use
-h height     page height in points
-m margin     margin size in points
-o filename   PDF output file name
-s size       font size
-w width      page width in points
EOS
  exit(1)
end


result = getopts(nil, "f:Courier", "h:#{PDF::A4_HEIGHT}",
		 "m:20", "o:", "s:12", "w:#{PDF::A4_WIDTH}")
usage unless result
usage unless pdffile = $OPT_o
fontname = $OPT_f
width = $OPT_w.to_f
height = $OPT_h.to_f
margin = $OPT_m.to_f
fontsize = $OPT_s.to_f
usage if width < 0 || height < 0 || margin < 0 || fontsize < 0


pdf = PDF.open(pdffile)
pdf.set_info(PDF::INFO_TITLE, "Converted text")
pdf.set_info(PDF::INFO_CREATOR, "text2pdf.rb")

x = margin
y = height - margin

while ARGF.gets
  if ($_[0] == ?\f)
    if (y == height - margin)
      pdf.begin_page(width, height)
    end
    pdf.end_page
    y = height - margin
    next
  end

  $_.chop!

  if (y < margin)               # page break necessary?
    y = height - margin
    pdf.end_page
  end

  if (y == height - margin)
    pdf.begin_page(width, height)
    font = pdf.findfont(fontname, PDF::ENCODING_WINANSI, false)
    pdf.setfont(font, fontsize)
    pdf.set_text_pos(x, y)
    y -= fontsize
  end

  pdf.continue_text($_)
  y -= fontsize
end

if (y != height - margin)
  pdf.end_page
end

pdf.close
