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

Revision 364, 6.0 kB (checked in by jerome, 18 years ago)

Added support for the computation of ink coverage for the PDF format.

  • 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 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
24"""This modules implements a page counter for PDF documents."""
25
26import sys
27import popen2
28import re
29
30import pdlparser
31
32class PDFObject :
33    """A class for PDF objects."""
34    def __init__(self, major, minor, description) :
35        """Initialize the PDF object."""
36        self.major = major
37        self.minor = minor
38        self.description = description
39        self.comments = []
40        self.content = []
41        self.parent = None
42        self.kids = []
43       
44class Parser(pdlparser.PDLParser) :
45    """A parser for PDF documents."""
46    def isValid(self) :   
47        """Returns 1 if data is PDF, else 0."""
48        if self.firstblock.startswith("%PDF-") or \
49           self.firstblock.startswith("\033%-12345X%PDF-") or \
50           ((self.firstblock[:128].find("\033%-12345X") != -1) and (self.firstblock.upper().find("LANGUAGE=PDF") != -1)) or \
51           (self.firstblock.find("%PDF-") != -1) :
52            self.logdebug("DEBUG: Input file is in the PDF format.")
53            return 1
54        else :   
55            return 0
56       
57    def getJobSize(self) :   
58        """Counts pages in a PDF document."""
59        # First we start with a generic PDF parser.
60        lastcomment = None
61        objects = {}
62        inobject = 0
63        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
64        for fullline in self.infile.xreadlines() :
65            parts = [ l.strip() for l in fullline.splitlines() ]
66            for line in parts :
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) = [int(num) for num in 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 minor >= oldobject.minor :
91                                objects[major] = obj
92                            inobject = 0       
93                    else :   
94                        if inobject :
95                            obj.content.append(line)
96                       
97        # Now we check each PDF object we've just created.
98        # colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
99        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/\s]", re.I)
100        pagecount = 0
101        for obj in objects.values() :
102            content = "".join(obj.content)
103            count = len(newpageregexp.findall(content))
104            pagecount += count
105        return pagecount   
106       
107    def convertToTiffMultiPage24NC(self, fname, dpi) :
108        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
109           Writes TIFF datas to the outputfile file object.
110        """   
111        command = 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%i -sOutputFile="%s" -' % (dpi, fname)
112        child = popen2.Popen4(command)
113        try :
114            data = self.infile.read(pdlparser.MEGABYTE)   
115            while data :
116                child.tochild.write(data)
117                data = self.infile.read(pdlparser.MEGABYTE)
118            child.tochild.flush()
119            child.tochild.close()   
120        except (IOError, OSError), msg :   
121            raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg
122           
123        child.fromchild.close()
124        try :
125            child.wait()
126        except OSError, msg :   
127            raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg
128       
129def test() :       
130    """Test function."""
131    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
132        sys.argv.append("-")
133    totalsize = 0   
134    for arg in sys.argv[1:] :
135        if arg == "-" :
136            infile = sys.stdin
137            mustclose = 0
138        else :   
139            infile = open(arg, "rb")
140            mustclose = 1
141        try :
142            parser = Parser(infile, debug=1)
143            totalsize += parser.getJobSize()
144        except pdlparser.PDLParserError, msg :   
145            sys.stderr.write("ERROR: %s\n" % msg)
146            sys.stderr.flush()
147        if mustclose :   
148            infile.close()
149    print "%s" % totalsize
150   
151if __name__ == "__main__" :   
152    test()
Note: See TracBrowser for help on using the browser.