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
RevLine 
[564]1# -*- coding: UTF-8 -*-
[191]2#
3# pkpgcounter : a generic Page Description Language parser
4#
[564]5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
[463]6# This program is free software: you can redistribute it and/or modify
[191]7# it under the terms of the GNU General Public License as published by
[463]8# the Free Software Foundation, either version 3 of the License, or
[191]9# (at your option) any later version.
[463]10#
[191]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
[463]17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[191]18#
19# $Id$
20#
[193]21
[355]22"""This modules implements a page counter for PDF documents."""
23
[193]24import re
25
[235]26import pdlparser
[193]27
[240]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
[491]34        self.majori = int(major)
35        self.minori = int(minor)
[240]36        self.description = description
37        self.comments = []
38        self.content = []
39        self.parent = None
40        self.kids = []
41       
[220]42class Parser(pdlparser.PDLParser) :
[193]43    """A parser for PDF documents."""
[492]44    totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r"%(dpi)i" -sOutputFile="%(outfname)s" "%(infname)s"' ]
[527]45    required = [ "gs" ]
[491]46    openmode = "rU"
[555]47    format = "PDF"
[220]48    def isValid(self) :   
[387]49        """Returns True if data is PDF, else False."""
[522]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) :
[387]54            return True
[220]55        else :   
[387]56            return False
[220]57       
[193]58    def getJobSize(self) :   
59        """Counts pages in a PDF document."""
[240]60        # First we start with a generic PDF parser.
61        lastcomment = None
62        objects = {}
[241]63        inobject = 0
[243]64        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
[450]65        for line in self.infile :
[491]66            line = line.strip()   
[450]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 :
[491]76                    (major, minor) = line[result.start():result.end()].split()[:2]
[450]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
[241]84                    if inobject :
[450]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)
[491]90                        if int(minor) >= oldobject.minori :
[450]91                            objects[major] = obj
[491]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))
[450]94                        inobject = 0       
95                else :   
96                    if inobject :
97                        obj.content.append(line)
[240]98                       
99        # Now we check each PDF object we've just created.
[450]100        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/>\s]", re.I)
[193]101        pagecount = 0
[252]102        for obj in objects.values() :
103            content = "".join(obj.content)
[243]104            count = len(newpageregexp.findall(content))
[450]105            if count and (content != r"<</Type /Page>>") : # Empty pages which are not rendered ?
106                pagecount += count
[193]107        return pagecount   
Note: See TracBrowser for help on using the browser.