#!/usr/bin/env python

# doc2pdf.py
# Copyright (c) 2004, Apple Computer, Inc., all rights reserved.

from CoreGraphics import *
from fnmatch import fnmatch
import os, sys, getopt

def usage():
  print '''
usage: docs2pdf.py [OPTION] DOCUMENT[S] OUTPUT.PDF

Example: docs2pdf.py title.html *.tiff index.rtf report.pdf

Convert any of several document types to PDF:
	Text: .txt .? .??
	RTF:  .rtf
	HTML: .htm .html .php
	Word: .doc .xml  .wordml
        Image: .tif .tiff .png .jpg .jpeg

Options:
  -f, --font-size=SIZE
'''

def isText(ext):
  for pattern in (".txt", ".?", ".??", ".rtf", ".htm*", ".php", ".doc", "*ml"):
    if fnmatch(ext, pattern):
      return 1
  return 0

def drawDocument(input_files, font_size, output_file):
  '''Convert input files into PDF, using font_size'''

  pageRect = CGRectMake(0, 0, 612, 792)
  c = CGPDFContextCreateWithFilename(output_file, pageRect)

  for input_file in input_files:

    (root, ext) = os.path.splitext(input_file)

    if (isText(ext)):
      text = CGDataProviderCreateWithFilename(input_file)
      if not text:
        return "Error: document '%s' not found"%(input_file)

      c.beginPage(pageRect)

      if fnmatch(ext,".txt") or fnmatch(ext,".?") or fnmatch(ext,".??"):
        tr = c.drawPlainTextInRect(text, pageRect, font_size)
      elif fnmatch(ext,".rtf"):
        tr = c.drawRTFTextInRect(text, pageRect, font_size)
      elif fnmatch(ext,".htm*") or fnmatch(ext,".php"):
        tr = c.drawHTMLTextInRect(text, pageRect, font_size)
      elif fnmatch(ext,".doc"):
        tr = c.drawDocFormatTextInRect(text, pageRect, font_size)
      elif fnmatch(ext,"*ml"):
        tr = c.drawWordMLFormatTextInRect(text, pageRect, font_size)
      else:
        return "Error: unknown type '%s' for '%s'"%(ext, input_file)
    else:
      c.beginPage(pageRect)
      i = CGImageImport(CGDataProviderCreateWithFilename(input_file))
      c.drawImage(pageRect.inset(0, 0), i)
      
    c.endPage()

  c.finish()


def main():
  '''Parse font_size option, then convert each argument'''
  try:
    opts,args = getopt.getopt(sys.argv[1:], 'f:', ['font-size='])
  except getopt.GetoptError:
    usage()
    sys.exit(1)

  font_size = 12.0
  for(o,a) in opts:
    if o in('-f', '--font-size'):
      font_size = float(a)

  if len(args) < 1:
    usage()
    exit()

  drawDocument(args[0:-1], font_size, args[-1])

# Run as main

if __name__ == '__main__':
  main()
