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

Revision 564, 4.4 kB (checked in by jerome, 16 years ago)

Changed copyright years.
Removed unnecessary shebang lines.
Changed default encoding to UTF-8 from ISO-8859-15 (only
ascii is used anyway).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Id Rev
Line 
1# -*- coding: UTF-8 -*-
2#
3# pkpgcounter : a generic Page Description Language parser
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21
22"""This modules implements a page counter for PDF documents."""
23
24import re
25
26import pdlparser
27
28class PDFObject :
29    """A class for PDF objects."""
30    def __init__(self, major, minor, description) :
31        """Initialize the PDF object."""
32        self.major = major
33        self.minor = minor
34        self.majori = int(major)
35        self.minori = int(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="%(outfname)s" "%(infname)s"' ]
45    required = [ "gs" ]
46    openmode = "rU"
47    format = "PDF"
48    def isValid(self) :   
49        """Returns True if data is PDF, else False."""
50        if self.firstblock.startswith("%PDF-") or \
51           self.firstblock.startswith("\033%-12345X%PDF-") or \
52           ((self.firstblock[:128].find("\033%-12345X") != -1) and (self.firstblock.upper().find("LANGUAGE=PDF") != -1)) or \
53           (self.firstblock.find("%PDF-") != -1) :
54            return True
55        else :   
56            return False
57       
58    def getJobSize(self) :   
59        """Counts pages in a PDF document."""
60        # First we start with a generic PDF parser.
61        lastcomment = None
62        objects = {}
63        inobject = 0
64        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
65        for line in self.infile :
66            line = line.strip()   
67            if line.startswith("% ") :   
68                if inobject :
69                    obj.comments.append(line)
70                else :
71                    lastcomment = line[2:]
72            else :
73                # New object begins here
74                result = objre.search(line)
75                if result is not None :
76                    (major, minor) = line[result.start():result.end()].split()[:2]
77                    obj = PDFObject(major, minor, lastcomment)
78                    obj.content.append(line[result.end():])
79                    inobject = 1
80                elif line.startswith("endobj") \
81                  or line.startswith(">> endobj") \
82                  or line.startswith(">>endobj") :
83                    # Handle previous object, if any
84                    if inobject :
85                        # only overwrite older versions of this object
86                        # same minor seems to be possible, so the latest one
87                        # found in the file will be the one we keep.
88                        # if we want the first one, just use > instead of >=
89                        oldobject = objects.setdefault(major, obj)
90                        if int(minor) >= oldobject.minori :
91                            objects[major] = obj
92                            # self.logdebug("Object(%i, %i) overwritten with Object(%i, %i)" % (oldobject.majori, oldobject.minori, obj.majori, obj.minori))
93                        # self.logdebug("Object(%i, %i)" % (obj.majori, obj.minori))
94                        inobject = 0       
95                else :   
96                    if inobject :
97                        obj.content.append(line)
98                       
99        # Now we check each PDF object we've just created.
100        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/>\s]", re.I)
101        pagecount = 0
102        for obj in objects.values() :
103            content = "".join(obj.content)
104            count = len(newpageregexp.findall(content))
105            if count and (content != r"<</Type /Page>>") : # Empty pages which are not rendered ?
106                pagecount += count
107        return pagecount   
Note: See TracBrowser for help on using the browser.