我想使用webkit,gtk3和cairo将网页保存到pdf中。
<小时/> 有效:可见部分(在窗口中可见)被正确打印到pdf
#include <gtk/gtk.h>
#include <webkit/webkit.h>
#include <cairo-pdf.h>
static void save_as_pdf (GtkWidget *widget, const char *filename)
{
GtkAllocation allocation;
printf("Saving PDF to file %s\n", filename);
gtk_widget_get_allocation(GTK_WIDGET(widget), &allocation);
printf("height: %d width: %d\n", allocation.height, allocation.width);
cairo_surface_t *surface = cairo_pdf_surface_create( filename, allocation.width, allocation.height);
cairo_t *cr = cairo_create(surface);
gtk_widget_draw(widget, cr);
cairo_destroy(cr);
cairo_surface_destroy(surface);
}
static void notifyProgressCb(WebKitWebView* webView, GParamSpec* pspec, GtkWidget* window)
{
float progress = webkit_web_view_get_progress(webView);
printf("\x1b[1G\t\x1b[1G%f", progress * 100); fflush(stdout);
if (progress == 1.0)
save_as_pdf(window, "test.pdf");
}
int main (int argc, char *argv[])
{
GtkWidget *window;
WebKitWebView *webView;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 1024, 768);
webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
gtk_container_set_resize_mode(GTK_CONTAINER(webView), GTK_RESIZE_PARENT);
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(webView));
g_signal_connect(webView, "notify::progress", G_CALLBACK(notifyProgressCb), webView);
webkit_web_view_load_uri(webView, "http://www.heise.de");
g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_widget_show_all (window);
gtk_main();
return 0;
}
编译:
gcc
pkg-config --cflags --libs gtk+-3.0
pkg-config --libs --cflags webkitgtk-3.0
yourfile.c
答案 0 :(得分:0)
据说cairo_create()方法只绘制WebView小部件的一部分,该部分在窗口内可见。在这种情况下,我会完全绕过WebkitGtk对象并包含一些下载网页的代码,呈现它并将输出保存到PDF文件中;例如,HTML2PDF。它可能是一种肮脏的低级方法,但它更强大,更容易实现。
答案 1 :(得分:0)