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

Revision 555, 4.5 kB (checked in by jerome, 16 years ago)

Each parser now has a 'format' attribute containing its short name.

  • 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 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.majori = int(major)
36        self.minori = int(minor)
37        self.description = description
38        self.comments = []
39        self.content = []
40        self.parent = None
41        self.kids = []
42       
43class Parser(pdlparser.PDLParser) :
44    """A parser for PDF documents."""
45    totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r"%(dpi)i" -sOutputFile="%(outfname)s" "%(infname)s"' ]
46    required = [ "gs" ]
47    openmode = "rU"
48    format = "PDF"
49    def isValid(self) :   
50        """Returns True if data is PDF, else False."""
51        if self.firstblock.startswith("%PDF-") or \
52           self.firstblock.startswith("\033%-12345X%PDF-") or \
53           ((self.firstblock[:128].find("\033%-12345X") != -1) and (self.firstblock.upper().find("LANGUAGE=PDF") != -1)) or \
54           (self.firstblock.find("%PDF-") != -1) :
55            return True
56        else :   
57            return False
58       
59    def getJobSize(self) :   
60        """Counts pages in a PDF document."""
61        # First we start with a generic PDF parser.
62        lastcomment = None
63        objects = {}
64        inobject = 0
65        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
66        for line in self.infile :
67            line = line.strip()   
68            if line.startswith("% ") :   
69                if inobject :
70                    obj.comments.append(line)
71                else :
72                    lastcomment = line[2:]
73            else :
74                # New object begins here
75                result = objre.search(line)
76                if result is not None :
77                    (major, minor) = line[result.start():result.end()].split()[:2]
78                    obj = PDFObject(major, minor, lastcomment)
79                    obj.content.append(line[result.end():])
80                    inobject = 1
81                elif line.startswith("endobj") \
82                  or line.startswith(">> endobj") \
83                  or line.startswith(">>endobj") :
84                    # Handle previous object, if any
85                    if inobject :
86                        # only overwrite older versions of this object
87                        # same minor seems to be possible, so the latest one
88                        # found in the file will be the one we keep.
89                        # if we want the first one, just use > instead of >=
90                        oldobject = objects.setdefault(major, obj)
91                        if int(minor) >= oldobject.minori :
92                            objects[major] = obj
93                            # self.logdebug("Object(%i, %i) overwritten with Object(%i, %i)" % (oldobject.majori, oldobject.minori, obj.majori, obj.minori))
94                        # self.logdebug("Object(%i, %i)" % (obj.majori, obj.minori))
95                        inobject = 0       
96                else :   
97                    if inobject :
98                        obj.content.append(line)
99                       
100        # Now we check each PDF object we've just created.
101        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/>\s]", re.I)
102        pagecount = 0
103        for obj in objects.values() :
104            content = "".join(obj.content)
105            count = len(newpageregexp.findall(content))
106            if count and (content != r"<</Type /Page>>") : # Empty pages which are not rendered ?
107                pagecount += count
108        return pagecount   
Note: See TracBrowser for help on using the browser.