#!/usr/bin/ruby
#
# imagepdf.c
#
# Convert PNG/TIFF/GIF/JPEG images to PDF
#     original C version by Thomas Merz
#     rewritten in Ruby by TAKAHASHI Hitoshi
#

require 'pdflib'
require 'getopts'


def usage
  STDERR.print <<EOS
imagepdf: convert images to PDF. (C) Thomas Merz 1997-2000
  rewritten in Ruby by TAKAHASHI Hitoshi 2000
usage: imagepdf [options] imagefile(s)
Available options:
-c         print caption
-o <file>  output file
EOS
  exit 1
end

# Several magic numbers for image file formats

GIF_MAGIC = /^GIF/
TIFF_MAGIC_M = /^MM/
TIFF_MAGIC_I = /^II/
PNG_MAGIC = /^\x89PNG/
JPEG_MAGIC = /^\xFF\xD8/

MAGIC_LEN_MAX = 10


caption = false;

result = getopts("c", "o:")
usage unless result
unless pdffilename = $OPT_o
  STDERR << "Error: no output file given.\n"
  usage
end
caption = true if $OPT_c

if ARGV.size == 0
  STDERR << "Error: no image files given.\n"
  usage
end

pdf = PDF.open(pdffilename)
pdf.set_info(PDF::INFO_CREATOR, "pdfimage")

ARGV.each do |filename|
  STDERR << "Processing image file #{filename}...\n"

  begin
    imagefile = File.open(filename)
  rescue
    STDERR << "Error: Couldn't open image file #{filename} - skipped.\n"
    next
  end

  begin
    header = imagefile.read(MAGIC_LEN_MAX)
  rescue
    STDERR << "Error: Couldn't read from image file #{filename} - skipped.\n"
    next
  ensure
    imagefile.close    
  end

  begin
    case header
    when GIF_MAGIC
      image = pdf.open_image_file("gif", filename)
    when TIFF_MAGIC_M, TIFF_MAGIC_I
      image = pdf.open_image_file("tiff", filename)
    when PNG_MAGIC
      image = pdf.open_image_file("png", filename)
    when JPEG_MAGIC
      image = pdf.open_image_file("jpeg", filename)
    else
      raise	# unknown file type
    end
  rescue
    STDERR << "Error: Couldn't analyze image #{filename} - skipped.\n"
    next
  end

  dpi_x = pdf.get_value(PDF::PAR_RESX, image)
  dpi_y = pdf.get_value(PDF::PAR_RESY, image)

  if dpi_x > 0 && dpi_y > 0
    scale_x = 72.0 / dpi_x
    scale_y = 72.0 / dpi_y
  elsif dpi_x < 0 && dpi_y < 0
    scale_x = 1.0
    scale_y = dpi_y / dpi_x
  else
    scale_x = 1.0
    scale_y = 1.0
  end

  pdf.begin_page(pdf.get_value(PDF::PAR_IMAGEWIDTH, image) * scale_x, 
		 pdf.get_value(PDF::PAR_IMAGEHEIGHT, image) * scale_y)

  # define outline with filename
  pdf.add_bookmark(filename, 0, 0)

  pdf.scale(scale_x, scale_y)
  pdf.place_image(image, 0, 0, 1)

  pdf.end_page
end

pdf.close
exit 0
