package com.pdflib.cookbook.pcos.interactive;

import com.pdflib.pCOS;
import com.pdflib.pCOSException;
import com.pdflib.cookbook.pcos.pcos_cookbook_example;

/**
 * Retrieve the contents of all annotations.
 * <p>
 * Required software: pCOS interface 3 (pCOS 2.x, PDFlib 7.x, TET 2.2,
 * PLOP 3.x)<br>
 * Required data: PDF document
 * 
 * @version $Id: annotations.java,v 1.5 2007/09/20 14:54:36 stm Exp $
 */
public class annotations extends pcos_cookbook_example {

    /* This is where the data files are. Adjust as necessary. */
    private final static String SEARCH_PATH = "../input";

    public void example_code(pCOS p, String filename) throws pCOSException,
        Exception {
        /* Open the PDF document */
        int doc = p.open_document(filename, "");
        if (doc == -1)
            throw new Exception("Error: " + p.get_errmsg());

        System.out.println("File name: " + p.get_string(doc, "filename"));

        int pagecount = (int) p.get_number(doc, "length:pages");

        for (int page = 0; page < pagecount; page++) {
            String annotation_key = "pages[" + page + "]/Annots";

            String objtype = p.get_string(doc, "type:" + annotation_key);
            if (!objtype.equals("null")) {
                System.out.println("Page " + (page + 1));
                
                int anncount = (int) p.get_number(doc,
                                    "length:" + annotation_key);

                for (int ann = 0; ann < anncount; ann++) {
                    objtype = p.get_string(doc,
                        "type:" + annotation_key + "[" + ann + "]/Contents");
                    String subtype = p.get_string(doc,
                        annotation_key + "[" + ann + "]/Subtype");
                    System.out.print("  Subtype " + subtype + ", ");
                    
                    if (objtype.equals("string")) {
                        String contents = p.get_string(doc,
                            annotation_key + "[" + ann + "]/Contents");
                        System.out.println("contents = '" + contents + "'");
                    }
                    else {
                        System.out.println("no contents found for annotation "
                            + ann);
                    }
                }
            }
        }

        p.close_document(doc);
    }

    public annotations(String[] argv, String readable_name, String search_path,
        String full_rcs_file_name, String revision) {
        super(argv, readable_name, search_path, full_rcs_file_name, revision);
    }

    public static void main(String argv[]) {
        annotations example = new annotations(argv, "Annotations", SEARCH_PATH,
            "$RCSfile: annotations.java,v $", "$Revision: 1.5 $");
        example.execute();
    }
}
