[Howto] GTK+ and poppler (minimal example)

posted in: computer | 0

minimal working example, which creates a GTK-window and displays the first page of the given pdf-file.
(compile with command: gcc example.c -o example `pkg-config --cflags --libs gtk+-3.0 poppler poppler-glib`)

versions: GTK+ 3.24.23-2 and poppler-20.09.0-2

#include <gtk/gtk.h>
#include <poppler.h>


void draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data){
  PopplerDocument *doc = poppler_document_new_from_file("file:////tmp/test.pdf", NULL, NULL);
  PopplerPage *ppage = poppler_document_get_page(doc, 0);
  poppler_page_render(ppage, cr);
}



static void activate(GtkApplication* app, gpointer user_data){
  GtkWidget *window = gtk_application_window_new(app);
  gtk_window_set_default_size(GTK_WINDOW(window), 500, 750);

  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
  gtk_container_add(GTK_CONTAINER(window), box);

  GtkWidget *drawarea = gtk_drawing_area_new();
  gtk_box_pack_start(GTK_BOX(box), drawarea, TRUE, TRUE, 0);
  g_signal_connect(G_OBJECT(drawarea), "draw", G_CALLBACK(draw_event), NULL);
  
  gtk_widget_show_all(window);
}



int main (int argc, char **argv){
  GtkApplication *app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect(app, "activate", G_CALLBACK (activate), NULL);
  g_application_run(G_APPLICATION (app), argc, argv);
  g_object_unref(app);
}