#!/usr/bin/python
# Resource-based image extractor based on PDFlib TET
#
# $Id: image_resources.py,v 1.2 2010/07/22 10:07:03 rjs Exp $
#

from sys import *
from tetlib_py import *

# global option list */
globaloptlist = "searchpath={{../data}}"

# document-specific option list */
docoptlist = ""

# page-specific option list */
pageoptlist = ""

# here you can insert basic image extract options (more below) */
baseimageoptlist = ""

if len(argv) != 2:
    raise Exception("usage: image_resources <filename>\n")

try:
    try:
        tet = TET_new()

	outfilebase = argv[1]

        TET_set_option(tet, globaloptlist)

        doc = TET_open_document(tet, argv[1], docoptlist)

        if (doc == -1):
            raise Exception("Error " + TET_get_errnum(tet) + "in " \
                + TET_get_apiname(tet) + "(): " + TET_get_errmsg(tet))

        # Images will only be merged upon opening a page.
        # In order to enumerate all merged image resources
        # we open all pages before extracting the images.
        #/

        # get number of pages in the document */
        n_pages = TET_pcos_get_number(tet, doc, "length:pages")

        # loop over pages in the document */
        for pageno in range(1, int(n_pages)+1):

            page = TET_open_page(tet, doc, pageno, pageoptlist)

            if (page == -1):
                print("Error " + TET_get_errnum(tet) + "in " \
                    + TET_get_apiname(tet) + "(): " + TET_get_errmsg(tet))
                continue                        # try next page */

            if (TET_get_errnum(tet) != 0):
                raise Exception ("\nError " + repr(TET_get_errnum(tet)) \
                    + "in " + TET_get_apiname(tet) + "() on page " + \
                    repr(pageno) + ": " + TET_get_errmsg(tet) + "\n")

            TET_close_page(tet, page)


        # get number of image resources in the document */
        n_images = TET_pcos_get_number(tet, doc, "length:images")

        # loop over image resources in the document */
        for imageid in range(0, int(n_images)):

	    # examine image type
	    mergetype = TET_pcos_get_number(tet, doc,
			"images[%d]/mergetype" % imageid)

            # skip images which have been consumed by merging
	    if (mergetype == 0 or mergetype == 1):
                # Print the following information for each image:
                # - page and image number
                # - pCOS id (required for indexing the images[] array)
                # - physical size of the placed image on the page
                # - pixel size of the underlying PDF image
                # - number of components, bits per component, and colorspace
		# - mergetype if different from "normal", i.e. "artificial"
		#   (=merged) or "consumed"
                #
                width = TET_pcos_get_number(tet, doc, \
				"images[%d]/Width" % imageid)
                height = TET_pcos_get_number(tet, doc, \
				"images[%d]/Height" % imageid)
                bpc = TET_pcos_get_number(tet, doc, \
				"images[%d]/bpc" % imageid)
                cs = TET_pcos_get_number(tet, doc, \
				"images[%d]/colorspaceid" % imageid)

                txt = "image I%d: %dx%d pixel, " % (imageid, width, height);

                if (cs != -1):
                    txt = txt + "%dx" % TET_pcos_get_number(tet, doc, \
				"colorspaces[%d]/components" % cs) \
			+ "%d bit " % bpc \
			+ "%s" % TET_pcos_get_string(tet, doc, \
				"colorspaces[%d]/name" % cs)
                else:
                    # cs==-1 may happen for some JPEG 2000 images. bpc,
                    # colorspace name and number of components are not
                    # available in this case.
                    txt = txt + "JPEG2000"

                if (mergetype):
                    txt = txt + ", mergetype="
		    if (mergetype == 1):
			txt = txt + "artificial"
		    else:
			txt = txt + "consumed"

                print(txt)

		# Fetch the image data and write it to a disk file. The
		# output filenames are generated from the input filename
		# by appending page number and image number.
		#
		imageoptlist = "%s filename={%s_I%d}" % \
		    (baseimageoptlist, outfilebase, imageid)
		
		if (TET_write_image_file(tet, doc, imageid, \
					    imageoptlist) == -1):
		    print("\nError " + repr(TET_get_errnum(tet)) + "in " + \
			TET_get_apiname(tet) + "():" + TET_get_errmsg(tet))
		    continue                   # process next image */

        TET_close_document(tet, doc)

    except TETlibException:
        print("TET exception occurred:\n[%d] %s: %s" %
            ((TET_get_errnum(tet)), TET_get_apiname(tet),  TET_get_errmsg(tet)))

    except Exception, e:
        print e;

finally:
    TET_delete(tet)
