Vala Poppler Sample
/* Using Poppler for PDF rendering in Vala sample code */
using GLib;
public class PopplerSample : GLib.Object {
private Gtk.Window win;
// To store the document and the current page
private Poppler.Document document;
private int index = 0;
private string _file_uri;
public string file_uri {
construct {
// When constructing, turn the file name into a uri
this._file_uri = "file://%s".printf (value);
}
get {
return this._file_uri;
}
}
// To create an application object with the name of the file to display
public PopplerSample (string file_name) {
this.file_uri = file_name;
}
construct {
this.document = new Poppler.Document.from_file (this.file_uri, "");
// Render the first page
var page = this.document.get_page (this.index);
var pixbuf = new Gdk.Pixbuf (Gdk.Colorspace.RGB, false, 8, 800, 600);
page.render_to_pixbuf (0, 0, 800, 600, 1.0, 0, pixbuf);
// Create a window to show an image, and set that image to show the buffer just rendered
this.win = new Gtk.Window (Gtk.WindowType.TOPLEVEL);
var image = new Gtk.Image.from_pixbuf (pixbuf);
this.win.add (image);
this.win.key_press_event += next_cb;
this.win.destroy += Gtk.main_quit;
}
private bool next_cb (Gtk.Window w, Gdk.EventKey e) {
// If the key pressed was q, quit, else show the next page
if (e.str == "q") {
Gtk.main_quit ();
}
var image = (Gtk.Image) this.win.get_child ();
var pixbuf = image.get_pixbuf ();
// Render the next page, or the first if we were at the last
this.index = (++this.index) % this.document.get_n_pages ();
var page = this.document.get_page (this.index);
page.render_to_pixbuf (0, 0, 800, 600, 1.0, 0, pixbuf);
image.set_from_pixbuf (pixbuf);
return false;
}
public void run () {
this.win.show_all ();
Gtk.main ();
}
public static void main (string[] args) {
if (args.length != 2) {
stderr.printf ("Usage: %s /full/path/to/some.pdf\n", args[0]);
return;
}
Gtk.init (ref args);
var app = new PopplerSample (args[1]);
app.run ();
}
}
Compile and Run
$ valac --pkg poppler-glib --pkg gtk+-2.0 -o popplersample PopplerSample.vala
$ ./popplersample /full/path/to/some.pdf