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

Revision 243, 5.2 kB (checked in by jerome, 19 years ago)

Fixed the different PDF problems reported.

  • 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        # objre = re.compile(r"\s*(\d+)\s+(\d+)\s+obj[<\s/]*")
62        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
63        for fullline in self.infile.xreadlines() :
64            parts = [ l.strip() for l in fullline.splitlines() ]
65            for line in parts :
66                if line.startswith("% ") :   
67                    if inobject :
68                        obj.comments.append(line)
69                    else :
70                        lastcomment = line[2:]
71                else :
72                    # New object begins here
73                    result = objre.search(line)
74                    if result is not None :
75                        (major, minor) = map(int, line[result.start():result.end()].split()[:2])
76                        obj = PDFObject(major, minor, lastcomment)
77                        obj.content.append(line[result.end():])
78                        inobject = 1
79                    elif line.startswith("endobj") \
80                      or line.startswith(">> endobj") \
81                      or line.startswith(">>endobj") :
82                        # Handle previous object, if any
83                        if inobject :
84                            # only overwrite older versions of this object
85                            # same minor seems to be possible, so the latest one
86                            # found in the file will be the one we keep.
87                            # if we want the first one, just use > instead of >=
88                            oldobject = objects.setdefault(major, obj)
89                            if minor >= oldobject.minor :
90                                objects[major] = obj
91                            inobject = 0       
92                    else :   
93                        if inobject :
94                            obj.content.append(line)
95                       
96        # Now we check each PDF object we've just created.
97        self.iscolor = None
98        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/\s]", re.I)
99        colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
100        pagecount = 0
101        for object in objects.values() :
102            content = "".join(object.content)
103            count = len(newpageregexp.findall(content))
104            pagecount += count
105            if colorregexp.match(content) :
106                self.iscolor = 1
107                if self.debug :
108                    sys.stderr.write("ColorSpace : %s\n" % content)
109        return pagecount   
110       
111def test() :       
112    """Test function."""
113    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
114        sys.argv.append("-")
115    totalsize = 0   
116    for arg in sys.argv[1:] :
117        if arg == "-" :
118            infile = sys.stdin
119            mustclose = 0
120        else :   
121            infile = open(arg, "rb")
122            mustclose = 1
123        try :
124            parser = Parser(infile, debug=1)
125            totalsize += parser.getJobSize()
126        except pdlparser.PDLParserError, msg :   
127            sys.stderr.write("ERROR: %s\n" % msg)
128            sys.stderr.flush()
129        if mustclose :   
130            infile.close()
131    print "%s" % totalsize
132   
133if __name__ == "__main__" :   
134    test()
Note: See TracBrowser for help on using the browser.