#!/usr/local/bin/ruby
#
# jtext2pdf.rb : Convert Japanese text files to PDF
#     original text2pdf.rb is written by TAKAHASHI Hitoshi
#     modified for Japanese support by yuichi TAKAHASHI, TAKAHASHI Hitoshi
#

require 'pdflib'
require 'getopts'

$KCODE = 'e'


def usage
  STDERR.print <<EOS
jtext2pdf - convert Japanese text files to pdf.
  original text2pdf.c (C) Thomas Merz 1997-2000
  rewritten in Ruby by TAKAHASHI Hitoshi 1999-2000
  modified for Japanese support by yuichi TAKAHASHI, TAKAHASHI Hitoshi 2000
usage: ruby #{$0} [options] [textfile]
Available options:
-f fontname   name of ascii font to use
-k fontname   name of Japanese 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", "k:HeiseiMin-W3", "h:#{PDF::A4_HEIGHT}",
		 "m:20", "o:", "s:12", "w:#{PDF::A4_WIDTH}")
usage unless result
usage unless pdffile = $OPT_o
afontname = $OPT_f
jfontname = $OPT_k
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, "jtext2pdf.rb"

x = margin
y = height - margin

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

  line.chomp!

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

  if y == height - margin
    pdf.begin_page width, height
    afont = pdf.findfont(afontname, PDF::ENCODING_WINANSI, false)
    jfont = pdf.findfont(jfontname, "EUC-H", false)
    pdf.set_text_pos x, y
    y -= fontsize
  end

  line.scan(/./m) do |c|
    if c.size == 1
      pdf.setfont afont, fontsize
    else
      pdf.setfont jfont, fontsize
    end
    pdf.show c
  end
  y -= fontsize
  pdf.set_text_pos x, y
end

if y != height - margin
  pdf.end_page
end

pdf.close
