Skip to content

Instantly share code, notes, and snippets.

@rootAvish
Last active February 14, 2024 00:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rootAvish/df6a52cb5c734702646b to your computer and use it in GitHub Desktop.
Save rootAvish/df6a52cb5c734702646b to your computer and use it in GitHub Desktop.
This program will create an offscreen(invisible) webkit-web-view, and take a screenshot of the loaded document, the document/URL is passed as a command line argument to the program
#include <gtk/gtk.h>
#include <webkit/webkit.h>
static void destroyWindowCb(GtkWidget* widget, GtkWidget* window);
static gboolean closeWebViewCb(WebKitWebView* webView, GtkWidget* window);
static void
webkit_render_cb(WebKitWebView *webview,
WebKitWebFrame *webframe,
gpointer data)
{
cairo_surface_t *surface = webkit_web_view_get_snapshot(webview);
cairo_surface_write_to_png(surface,"img.png");
}
int main(int argc, char* argv[])
{
// Initialize GTK+
gtk_init(&argc, &argv);
// Create an 800x600 offscreeen window that will contain the browser instance
GtkWidget *main_window = gtk_offscreen_window_new();
gtk_window_set_default_size(GTK_WINDOW(main_window), 800, 600);
// Create a browser instance
WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
// Create a scrollable area, and put the browser instance into it
GtkWidget *scrolledWindow = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledWindow),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_container_add(GTK_CONTAINER(scrolledWindow), GTK_WIDGET(webView));
// Set up callbacks so that if either the main window or the browser instance is
// closed, the program will exit
g_signal_connect(main_window, "destroy", G_CALLBACK(destroyWindowCb), NULL);
g_signal_connect(webView, "close-web-view", G_CALLBACK(closeWebViewCb), main_window);
//When the load is finished we grab a screenshot of the loaded document.
g_signal_connect(webView,"document-load-finished",G_CALLBACK(webkit_render_cb),NULL);
g_signal_connect(webView,"document-load-finished",G_CALLBACK(destroyWindowCb),NULL);
// Put the scrollable area into the main window
gtk_container_add(GTK_CONTAINER(main_window), scrolledWindow);
// Load a web page into the browser instance
webkit_web_view_load_uri(webView, argv[1]);
// Make sure that when the browser area becomes visible, it will get mouse
// and keyboard events
gtk_widget_grab_focus(GTK_WIDGET(webView));
// Make sure the main window and all its contents are visible
gtk_widget_show_all(main_window);
// Run the main GTK+ event loop
gtk_main();
return 0;
}
static void destroyWindowCb(GtkWidget* widget, GtkWidget* window)
{
gtk_main_quit();
}
static gboolean closeWebViewCb(WebKitWebView* webView, GtkWidget* window)
{
gtk_widget_destroy(window);
return TRUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment