#!/usr/bin/perl -w

#
# ascii2pdf - create simple pdf file from simple text file.
# Uses the PDF::Create perl module.
#
# Version 0.9.1
#
# Released under the GNU GPL.  A text version of the GPL should have come
# with this program in the file "COPYING".
# Copyright 2000 Michael Arndt
#

use PDF::Create;
use Getopt::Std;
use strict;

#
# vars
#
my ($prog,$output,$input,$pdf,$font,$orientation,$font_size,$root,$f1,$page);
my ($xbase,$ybase,$lmargin,$tmargin,$xpos,$ypos);
use vars qw($opt_l $opt_f $opt_p $opt_s $opt_t);

#
# defaults
#
$orientation = "portrait";
$font = "Courier";
$font_size = 10;
$lmargin = 10;
$tmargin = 30;
$prog = $0;
$prog =~ s,.*/,,g;

#
# get setup params
#
&help unless getopts("lf:p:s:t:");
$orientation = "landscape" if ($opt_l);
$font = $opt_f if ($opt_f);
$font_size = $opt_p if ($opt_p);
$lmargin = $opt_s if ($opt_s);
$tmargin = $opt_t if ($opt_t);
$input = shift;
if (! $input) {
	print STDERR "$prog: no input file given\n\n";
	&help;
}
if ( ! -f "$input" ) {
	print STDERR "$prog: no such file: $input\n\n";
	&help;
}
if ($input =~ /(.*?)\.txt/) {
	$output = $1 . ".pdf";
} else {
	$output = $input . ".pdf";
}

#
# translate file
#
&start();
$xpos = $lmargin;
$ypos = $ybase - $tmargin;
open(F, "<$input") or die "$prog: Could not open $input: $!\n";
while (<F>) {
	chomp;
	# ( or ) chars screw up the PDF encoding, we need to escape them
	s/\(/\\(/g;
	s/\)/\\)/g;
	if ($ypos <= $font_size) {
		&new_page;
		$ypos = $ybase - $tmargin;
		&print_string($_);
		$ypos = $ypos - $font_size;
	} elsif (/(.*?)\cL(.*)/) {
		&print_string($1) if ($1);
		&new_page;
		$ypos = $ybase - $tmargin;
		if ($2) {
			&print_string($2);
			$ypos = $ypos - $font_size;
		}	
	} else {
		&print_string($_);
		$ypos = $ypos - $font_size;
	}
}
close(F);
$pdf->close;

#
# subroutine to start the document
#
sub start {
	$pdf = new PDF::Create('filename' => $output,
                           'Title'    => 'test title',
                           ); 
	if ($orientation eq "portrait") {
		$root = $pdf->new_page('MediaBox' => [ 0, 0, 612, 792 ]);
		$xbase = 612;
		$ybase = 792;
	} else {
		$root = $pdf->new_page('MediaBox' => [ 0, 0, 792, 612 ]);
		$xbase = 792;
		$ybase = 612;
	}
	$f1 = $pdf->font('BaseFont' => $font);
	$page = $root->new_page;
	return 1;	
}

#
# subroutine to print a string in right spot on the page
# 
sub print_string {
	my ($string) = @_;
	$page->string($f1, $font_size, $xpos, $ypos, "$string");
	return 1;
}

#
# subroutine to start a new page
#
sub new_page {
	$page = $root->new_page;
	return 1;
}

#
# subroutine to print help page
#
sub help {
	print <<HELP;
Usage: $prog [options] file.txt
Where [options] are:
  -l for landscape
  -f <font> is Courier or Helvetica (default: Courier)
  -p <point size> is the point size (default: 10)
  -s <side margin> is # pixels for the left margin (default: 10)
  -t <top margin> is # pixels for the top margin (default: 30)

HELP
	exit;
}
