Vala Poppler Sample

/* Using Poppler for PDF rendering in Vala sample code */

using Gtk;

public class PopplerSample : Window {

    // To store the document and the current page
    private Poppler.Document document;
    private Image image;
    private int index = 0;

    // To create an application object with the name of the file to display
    public PopplerSample (string file_name) {
        try {
            this.document = new Poppler.Document.from_file (Filename.to_uri (file_name), "");
        } catch (Error e) {
            error ("%s", e.message);
        }

        // Create an image and render first page to image
        var pixbuf = new Gdk.Pixbuf (Gdk.Colorspace.RGB, false, 8, 800, 600);
        this.image = new Image.from_pixbuf (pixbuf);
        render_page ();

        add (this.image);

        this.key_press_event += on_key_pressed;
        this.destroy += Gtk.main_quit;
    }

    private bool on_key_pressed (PopplerSample source, Gdk.EventKey key) {
        // If the key pressed was q, quit, else show the next page
        if (key.str == "q") {
            Gtk.main_quit ();
        }

        // Render the next page, or the first if we were at the last
        this.index++;
        this.index %= this.document.get_n_pages ();
        render_page ();

        return false;
    }

    private void render_page () {
        var pixbuf = this.image.get_pixbuf ();
        var page = this.document.get_page (this.index);
        page.render_to_pixbuf (0, 0, 800, 600, 1.0, 0, pixbuf);
        this.image.set_from_pixbuf (pixbuf);
    }

    public static int main (string[] args) {
        if (args.length != 2) {
            stderr.printf ("Usage: %s /full/path/to/some.pdf\n", args[0]);
            return 1;
        }

        Gtk.init (ref args);

        var sample = new PopplerSample (args[1]);
        sample.show_all ();

        Gtk.main ();
        return 0;
    }
}

Compile and Run

$ valac --pkg poppler-glib --pkg gtk+-2.0 -o popplersample PopplerSample.vala
$ ./popplersample /full/path/to/some.pdf

Vala/PopplerSample (last edited 2008-12-20 16:34:11 by Frederik)