summaryrefslogtreecommitdiffstats
path: root/pdftops-cairo.c
blob: 4447d71ea520d71a922c4a61ef4932479008b2ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* gcc -o pdftops pdftops-cairo.c `pkg-config --cflags --libs cairo poppler-glib` */

#include <poppler.h>
#include <cairo.h>
#include <cairo-ps.h>

int main(int argc, char *argv[])
{
    PopplerDocument *document;
    PopplerPage *page;
    double width, height;
    GError *error;
    const char *filename;
    gchar *absolute, *uri;
    int num_pages, i;
    cairo_surface_t *surface;
    cairo_t *cr;
    cairo_status_t status;

    if (argc != 2) {
        printf ("Usage: pdftops-cairo input_file.pdf\n");
        return 0;
    }

    filename = argv[1];
    g_type_init ();
    error = NULL;

    if (g_path_is_absolute(filename)) {
        absolute = g_strdup (filename);
    } else {
        gchar *dir = g_get_current_dir ();
        absolute = g_build_filename (dir, filename, (gchar *) 0);
        free (dir);
    }

    uri = g_filename_to_uri (absolute, NULL, &error);
    free (absolute);
    if (uri == NULL) {
        printf("poppler fail: %s\n", error->message);
        return 1;
    }

    document = poppler_document_new_from_file (uri, NULL, &error);
    if (document == NULL) {
        printf("poppler fail: %s\n", error->message);
        return 1;
    }

    num_pages = poppler_document_get_n_pages (document);

    /* Page size does not matter here as the size is changed before
     * each page */
    surface = cairo_ps_surface_create ("/dev/stdout", 595, 842);
    cr = cairo_create (surface);
    for (i = 0; i < num_pages; i++) {
        page = poppler_document_get_page (document, i);
        if (page == NULL) {
            printf("poppler fail: page not found\n");
            return 1;
        }
        poppler_page_get_size (page, &width, &height);
        cairo_ps_surface_set_size (surface, width, height);
        cairo_save (cr);
        poppler_page_render_for_printing (page, cr);
        cairo_restore (cr);
        cairo_surface_show_page (surface);
        g_object_unref (page);
    }
    status = cairo_status(cr);
    if (status)
        printf("%s\n", cairo_status_to_string (status));
    cairo_destroy (cr);
    cairo_surface_finish (surface);
    status = cairo_surface_status(surface);
    if (status)
        printf("%s\n", cairo_status_to_string (status));
    cairo_surface_destroy (surface);

    g_object_unref (document);

    return 0;
}