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

Revision 463, 4.3 kB (checked in by jerome, 15 years ago)

Licensing terms changed to GNU GPL v3.0 or higher.
Removed old PCL3/4/5 parser which for a long time now wasn't used
anymore, and for which I was not the original copyright owner.
Version number bumped to 3.00alpha to reflect licensing changes.

  • 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, 2006, 2007 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 3 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, see <http://www.gnu.org/licenses/>.
19#
20# $Id$
21#
22
23"""This modules implements a page counter for PDF documents."""
24
25import sys
26import re
27
28import pdlparser
29
30class PDFObject :
31    """A class for PDF objects."""
32    def __init__(self, major, minor, description) :
33        """Initialize the PDF object."""
34        self.major = major
35        self.minor = minor
36        self.description = description
37        self.comments = []
38        self.content = []
39        self.parent = None
40        self.kids = []
41       
42class Parser(pdlparser.PDLParser) :
43    """A parser for PDF documents."""
44    totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -' ]
45    def isValid(self) :   
46        """Returns True if data is PDF, else False."""
47        if self.firstblock.startswith("%PDF-") or \
48           self.firstblock.startswith("\033%-12345X%PDF-") or \
49           ((self.firstblock[:128].find("\033%-12345X") != -1) and (self.firstblock.upper().find("LANGUAGE=PDF") != -1)) or \
50           (self.firstblock.find("%PDF-") != -1) :
51            self.logdebug("DEBUG: Input file is in the PDF format.")
52            return True
53        else :   
54            return False
55       
56    def getJobSize(self) :   
57        """Counts pages in a PDF document."""
58        # First we start with a generic PDF parser.
59        lastcomment = None
60        objects = {}
61        inobject = 0
62        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
63        for line in self.infile :
64            line = line.strip()
65            if line.startswith("% ") :   
66                if inobject :
67                    obj.comments.append(line)
68                else :
69                    lastcomment = line[2:]
70            else :
71                # New object begins here
72                result = objre.search(line)
73                if result is not None :
74                    (major, minor) = [int(num) for num in line[result.start():result.end()].split()[:2]]
75                    obj = PDFObject(major, minor, lastcomment)
76                    obj.content.append(line[result.end():])
77                    inobject = 1
78                elif line.startswith("endobj") \
79                  or line.startswith(">> endobj") \
80                  or line.startswith(">>endobj") :
81                    # Handle previous object, if any
82                    if inobject :
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                        oldobject = objects.setdefault(major, obj)
88                        if minor >= oldobject.minor :
89                            objects[major] = obj
90                        inobject = 0       
91                else :   
92                    if inobject :
93                        obj.content.append(line)
94                       
95        # Now we check each PDF object we've just created.
96        # colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
97        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/>\s]", re.I)
98        pagecount = 0
99        for obj in objects.values() :
100            content = "".join(obj.content)
101            count = len(newpageregexp.findall(content))
102            if count and (content != r"<</Type /Page>>") : # Empty pages which are not rendered ?
103                pagecount += count
104        return pagecount   
105       
106if __name__ == "__main__" :   
107    pdlparser.test(Parser)
Note: See TracBrowser for help on using the browser.