summaryrefslogtreecommitdiff
path: root/test/parsepdf.c
blob: ad6c6c40f6667a5e59188ce7ba3aeb0449f11b33 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
 * Copyright 2018 Vincent Sanders <vince@netsurf-browser.org>
 *
 * This file is part of libnspdf.
 *
 * Licensed under the MIT License,
 *                http://www.opensource.org/licenses/mit-license.php
 */

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#include <libwapcaplet/libwapcaplet.h>

#include <nspdf/document.h>
#include <nspdf/meta.h>
#include <nspdf/page.h>

static nspdferror
read_whole_pdf(const char *fname, uint8_t **buffer, uint64_t *buffer_length)
{
    FILE *f;
    off_t len;
    uint8_t *buf;
    size_t rd;

    f = fopen(fname, "r");
    if (f == NULL) {
        perror("pdf open");
        return NSPDFERROR_NOTFOUND;
    }

    fseek(f, 0, SEEK_END);
    len = ftello(f);

    buf = malloc(len);
    fseek(f, 0, SEEK_SET);

    rd = fread(buf, len, 1, f);
    if (rd != 1) {
        perror("pdf read");
        free(buf);
        return 1;
    }

    fclose(f);

    *buffer = buf;
    *buffer_length = len;

    return NSPDFERROR_OK;
}


int main(int argc, char **argv)
{
    uint8_t *buffer;
    uint64_t buffer_length;
    struct nspdf_doc *doc;
    nspdferror res;
    struct lwc_string_s *title;
    unsigned int page_count;

    if (argc < 2) {
        fprintf(stderr, "Usage %s <filename>\n", argv[0]);
        return 1;
    }

    res = read_whole_pdf(argv[1], &buffer, &buffer_length);
    if (res != 0) {
        printf("failed to read file\n");
        return res;
    }

    res = nspdf_document_create(&doc);
    if (res != NSPDFERROR_OK) {
        printf("failed to create a document\n");
        return res;
    }

    res = nspdf_document_parse(doc, buffer, buffer_length);
    if (res != NSPDFERROR_OK) {
        printf("document parse failed (%d)\n", res);
        return res;
    }

    res = nspdf_get_title(doc, &title);
    if (res == NSPDFERROR_OK) {
        printf("Title:%s\n", lwc_string_data(title));
    }

    res = nspdf_count_pages(doc, &page_count);
    if (res != NSPDFERROR_OK) {
        printf("page count failed (%d)\n", res);
        return res;
    }
    printf("Pages:%d\n", page_count);


    res = nspdf_document_destroy(doc);
    if (res != NSPDFERROR_OK) {
        printf("failed to destroy document (%d)\n", res);
        return res;
    }

    free(buffer);

    return 0;
}