summaryrefslogtreecommitdiff
path: root/test/parsepdf.c
blob: 3482af52bdf44ebc967afcdddd50bac93c4cb437 (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
/*
 * 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 <nspdf/document.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;

    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_document_destroy(doc);
    if (res != NSPDFERROR_OK) {
        printf("failed to destroy document (%d)\n", res);
        return res;
    }

    free(buffer);

    return 0;
}