root / pkpgcounter / trunk / pkpgpdls / pdf.py @ 241

Revision 241, 5.0 kB (checked in by jerome, 19 years ago)

Fix for the fix !

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Id Rev
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# pkpgcounter : a generic Page Description Language parser
5#
6# (c) 2003, 2004, 2005 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23
24import sys
25import re
26
27import pdlparser
28
29class PDFObject :
30    """A class for PDF objects."""
31    def __init__(self, major, minor, description) :
32        """Initialize the PDF object."""
33        self.major = major
34        self.minor = minor
35        self.description = description
36        self.comments = []
37        self.content = []
38        self.parent = None
39        self.kids = []
40       
41class Parser(pdlparser.PDLParser) :
42    """A parser for PDF documents."""
43    def isValid(self) :   
44        """Returns 1 if data is PDF, else 0."""
45        if self.firstblock.startswith("%PDF-") or \
46           self.firstblock.startswith("\033%-12345X%PDF-") or \
47           ((self.firstblock[:128].find("\033%-12345X") != -1) and (self.firstblock.upper().find("LANGUAGE=PDF") != -1)) or \
48           (self.firstblock.find("%PDF-") != -1) :
49            if self.debug : 
50                sys.stderr.write("DEBUG: Input file is in the PDF format.\n")
51            return 1
52        else :   
53            return 0
54       
55    def getJobSize(self) :   
56        """Counts pages in a PDF document."""
57        # First we start with a generic PDF parser.
58        lastcomment = None
59        objects = {}
60        inobject = 0
61        for fullline in self.infile.xreadlines() :
62            parts = [ l.strip() for l in fullline.splitlines() ]
63            for line in parts :
64                if line.startswith("% ") :   
65                    if inobject :
66                        obj.comments.append(line)
67                    else :
68                        lastcomment = line[2:]
69                elif line.endswith(" obj") :
70                    # New object begins here
71                    (n0, n1, dummy) = line.split()
72                    (major, minor) = map(int, (n0, n1))
73                    obj = PDFObject(major, minor, lastcomment)
74                    inobject = 1
75                elif line.startswith("endobj") :   
76                    try :       
77                        # try to find a different version of this object
78                        oldobject = objects[major]
79                    except KeyError :   
80                        # not found, so we add it
81                        objects[major] = obj
82                    else :   
83                        # only overwrite older versions of this object
84                        # same minor seems to be possible, so the latest one
85                        # found in the file will be the one we keep.
86                        # if we want the first one, just use > instead of >=
87                        if minor >= oldobject.minor :
88                            objects[major] = obj
89                    inobject = 0       
90                else :   
91                    if inobject :
92                        obj.content.append(line)
93                       
94        # Now we check each PDF object we've just created.
95        self.iscolor = None
96        newpageregexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]", re.I)
97        colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
98        pagecount = 0
99        for object in objects.values() :
100            content = "".join(object.content)
101            pagecount += len(newpageregexp.findall(content))
102            if colorregexp.match(content) :
103                self.iscolor = 1
104                if self.debug :
105                    sys.stderr.write("ColorSpace : %s\n" % content)
106        return pagecount   
107       
108def test() :       
109    """Test function."""
110    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
111        sys.argv.append("-")
112    totalsize = 0   
113    for arg in sys.argv[1:] :
114        if arg == "-" :
115            infile = sys.stdin
116            mustclose = 0
117        else :   
118            infile = open(arg, "rb")
119            mustclose = 1
120        try :
121            parser = Parser(infile, debug=1)
122            totalsize += parser.getJobSize()
123        except pdlparser.PDLParserError, msg :   
124            sys.stderr.write("ERROR: %s\n" % msg)
125            sys.stderr.flush()
126        if mustclose :   
127            infile.close()
128    print "%s" % totalsize
129   
130if __name__ == "__main__" :   
131    test()
Note: See TracBrowser for help on using the browser.