root / pkpgcounter / trunk / pkpgpdls / postscript.py @ 248

Revision 248, 6.5 kB (checked in by jerome, 19 years ago)

Fixed PCLXL computation of number of copies for each page.
Now uses a similar routine in the PostScript? parser.
Added detection of a special number of copies setting for some PS drivers.

  • 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 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
24import sys
25import popen2
26
27import pdlparser
28
29class Parser(pdlparser.PDLParser) :
30    """A parser for PostScript documents."""
31    def isValid(self) :   
32        """Returns 1 if data is PostScript, else 0."""
33        if self.firstblock.startswith("%!") or \
34           self.firstblock.startswith("\004%!") or \
35           self.firstblock.startswith("\033%-12345X%!PS") or \
36           ((self.firstblock[:128].find("\033%-12345X") != -1) and \
37             ((self.firstblock.find("LANGUAGE=POSTSCRIPT") != -1) or \
38              (self.firstblock.find("LANGUAGE = POSTSCRIPT") != -1) or \
39              (self.firstblock.find("LANGUAGE = Postscript") != -1))) or \
40              (self.firstblock.find("%!PS-Adobe") != -1) :
41            if self.debug : 
42                sys.stderr.write("DEBUG: Input file is in the PostScript format.\n")
43            return 1
44        else :   
45            return 0
46       
47    def throughGhostScript(self) :
48        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
49        if self.debug :
50            sys.stderr.write("Internal parser sucks, using GhostScript instead...\n")
51        self.infile.seek(0)
52        command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
53        child = popen2.Popen4(command)
54        try :
55            data = self.infile.read(pdlparser.MEGABYTE)   
56            while data :
57                child.tochild.write(data)
58                data = self.infile.read(pdlparser.MEGABYTE)
59            child.tochild.flush()
60            child.tochild.close()   
61        except (IOError, OSError), msg :   
62            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
63           
64        pagecount = 0
65        try :
66            pagecount = int(child.fromchild.readline().strip())
67        except (IOError, OSError, AttributeError, ValueError), msg :
68            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
69        child.fromchild.close()
70       
71        try :
72            child.wait()
73        except OSError, msg :   
74            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
75        return pagecount * self.copies
76       
77    def natively(self) :
78        """Count pages in a DSC compliant PostScript document."""
79        self.infile.seek(0)
80        pagecount = 0
81        pages = {}
82        pages[0] = { "copies" : 1 }
83        for line in self.infile.xreadlines() : 
84            if line.startswith(r"%%Page: ") :
85                pagecount += 1
86                pages[pagecount] = { "copies" : 1 }
87            elif line.startswith(r"%%Requirements: numcopies(") :   
88                try :
89                    number = int(line.strip().split('(')[1].split(')')[0])
90                except :     
91                    pass
92                else :   
93                    if number > pages[pagecount]["copies"] :
94                        pages[pagecount]["copies"] = number
95            elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") :
96                # handle # of copies set by some Windows printer driver
97                try :
98                    number = int(line.strip().split()[2])
99                except :     
100                    pass
101                else :   
102                    if number > pages[pagecount]["copies"] :
103                        pages[pagecount]["copies"] = number
104            elif line.startswith("1 dict dup /NumCopies ") :
105                # handle # of copies set by mozilla/kprinter
106                try :
107                    number = int(line.strip().split()[4])
108                except :     
109                    pass
110                else :   
111                    if number > pages[pagecount]["copies"] :
112                        pages[pagecount]["copies"] = number
113            elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") :
114                try :
115                    number = int(previousline.strip()[2:])
116                except :
117                    pass
118                else :
119                    if number > pages[pagecount]["copies"] :
120                        pages[pagecount]["copies"] = number
121            previousline = line
122           
123        # extract max number of copies to please the ghostscript parser, just   
124        # in case we will use it later
125        self.copies = max([ v["copies"] for (k, v) in pages.items() ])
126       
127        # now apply the number of copies to each page
128        for pnum in range(1, pagecount + 1) :
129            page = pages.get(pnum, pages.get(1, { "copies" : 1 }))
130            copies = page["copies"]
131            pagecount += (copies - 1)
132            if self.debug :
133                sys.stderr.write("%s * page #%s\n" % (copies, pnum))
134        return pagecount
135       
136    def getJobSize(self) :   
137        """Count pages in PostScript document."""
138        self.copies = 1
139        return self.natively() or self.throughGhostScript()
140       
141def test() :       
142    """Test function."""
143    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
144        sys.argv.append("-")
145    totalsize = 0   
146    for arg in sys.argv[1:] :
147        if arg == "-" :
148            infile = sys.stdin
149            mustclose = 0
150        else :   
151            infile = open(arg, "rb")
152            mustclose = 1
153        try :
154            parser = Parser(infile, debug=1)
155            totalsize += parser.getJobSize()
156        except pdlparser.PDLParserError, msg :   
157            sys.stderr.write("ERROR: %s\n" % msg)
158            sys.stderr.flush()
159        if mustclose :   
160            infile.close()
161    print "%s" % totalsize
162   
163if __name__ == "__main__" :   
164    test()
Note: See TracBrowser for help on using the browser.