summaryrefslogtreecommitdiffstats
path: root/examples/pdf-parse-content.cc
blob: 430c0a06399fa4c679bc8485fa833d4f707fc2d6 (plain) (blame)
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
#include <iostream>
#include <string.h>
#include <stdlib.h>

#include <qpdf/QPDF.hh>
#include <qpdf/QUtil.hh>

static char const* whoami = 0;

void usage()
{
    std::cerr << "Usage: " << whoami << " filename page-number" << std::endl
	      << "Prints a dump of the objects in the content streams"
              << " of the given page." << std::endl
              << "Pages are numbered from 1." << std::endl;
    exit(2);
}

class ParserCallbacks: public QPDFObjectHandle::ParserCallbacks
{
  public:
    virtual ~ParserCallbacks()
    {
    }

    virtual void handleObject(QPDFObjectHandle);
    virtual void handleEOF();
};

void
ParserCallbacks::handleObject(QPDFObjectHandle obj)
{
    std::cout << obj.getTypeName() << ": ";
    if (obj.isInlineImage())
    {
        std::string val = obj.getInlineImageValue();
        char buf[3];
        buf[2] = '\0';
        for (size_t i = 0; i < val.length(); ++i)
        {
            sprintf(buf, "%02x", (unsigned char)(val[i]));
            std::cout << buf;
        }
        std::cout << std::endl;
    }
    else
    {
        std::cout << obj.unparse() << std::endl;
    }
}

void
ParserCallbacks::handleEOF()
{
    std::cout << "-EOF-" << std::endl;
}

int main(int argc, char* argv[])
{
    whoami = QUtil::getWhoami(argv[0]);

    // For libtool's sake....
    if (strncmp(whoami, "lt-", 3) == 0)
    {
	whoami += 3;
    }

    if (argc != 3)
    {
	usage();
    }
    char const* filename = argv[1];
    int pageno = atoi(argv[2]);

    try
    {
	QPDF pdf;
	pdf.processFile(filename);
        std::vector<QPDFObjectHandle> pages = pdf.getAllPages();
        if ((pageno < 1) || (pageno > (int)pages.size()))
        {
            usage();
        }

        QPDFObjectHandle page = pages[pageno-1];
        QPDFObjectHandle contents = page.getKey("/Contents");
        ParserCallbacks cb;
        QPDFObjectHandle::parseContentStream(contents, &cb);
    }
    catch (std::exception& e)
    {
	std::cerr << whoami << ": " << e.what() << std::endl;
	exit(2);
    }

    return 0;
}