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

Revision 363, 9.3 kB (checked in by jerome, 18 years ago)

Initial support for the computation of ink coverage for PostScript?
input files.

  • 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 PostScript documents."""
25
26import sys
27import os
28import tempfile
29import popen2
30
31import pdlparser
32import inkcoverage
33
34class Parser(pdlparser.PDLParser) :
35    """A parser for PostScript documents."""
36    def isValid(self) :   
37        """Returns 1 if data is PostScript, else 0."""
38        if self.firstblock.startswith("%!") or \
39           self.firstblock.startswith("\004%!") or \
40           self.firstblock.startswith("\033%-12345X%!PS") or \
41           ((self.firstblock[:128].find("\033%-12345X") != -1) and \
42             ((self.firstblock.find("LANGUAGE=POSTSCRIPT") != -1) or \
43              (self.firstblock.find("LANGUAGE = POSTSCRIPT") != -1) or \
44              (self.firstblock.find("LANGUAGE = Postscript") != -1))) or \
45              (self.firstblock.find("%!PS-Adobe") != -1) :
46            self.logdebug("DEBUG: Input file is in the PostScript format.")
47            return 1
48        else :   
49            return 0
50       
51    def throughGhostScript(self) :
52        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
53        self.logdebug("Internal parser sucks, using GhostScript instead...")
54        self.infile.seek(0)
55        command = 'gs -sDEVICE=bbox -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
56        child = popen2.Popen4(command)
57        try :
58            data = self.infile.read(pdlparser.MEGABYTE)   
59            while data :
60                child.tochild.write(data)
61                data = self.infile.read(pdlparser.MEGABYTE)
62            child.tochild.flush()
63            child.tochild.close()   
64        except (IOError, OSError), msg :   
65            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
66           
67        pagecount = 0
68        try :
69            pagecount = int(child.fromchild.readline().strip())
70        except (IOError, OSError, AttributeError, ValueError), msg :
71            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
72        child.fromchild.close()
73       
74        try :
75            child.wait()
76        except OSError, msg :   
77            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
78        self.logdebug("GhostScript said : %s pages" % pagecount)   
79        return pagecount * self.copies
80       
81    def natively(self) :
82        """Count pages in a DSC compliant PostScript document."""
83        self.infile.seek(0)
84        pagecount = 0
85        self.pages = { 0 : { "copies" : 1 } }
86        oldpagenum = None
87        previousline = ""
88        notrust = 0
89        prescribe = 0 # Kyocera's Prescribe commands
90        acrobatmarker = 0
91        for line in self.infile.xreadlines() : 
92            if (not prescribe) and line.startswith(r"%%BeginResource: procset pdf") \
93               and not acrobatmarker :
94                notrust = 1 # Let this stuff be managed by GhostScript, but we still extract number of copies
95            elif line.startswith(r"%ADOPrintSettings: L") :
96                acrobatmarker = 1
97            elif line.startswith("!R!") :
98                prescribe = 1
99            elif line.startswith(r"%%Page: ") or line.startswith(r"(%%[Page: ") :
100                proceed = 1
101                try :
102                    newpagenum = int(line.split(']')[0].split()[1])
103                except :   
104                    notinteger = 1 # It seems that sometimes it's not an integer but an EPS file name
105                else :   
106                    notinteger = 0
107                    if newpagenum == oldpagenum :
108                        proceed = 0
109                    else :
110                        oldpagenum = newpagenum
111                if proceed and not notinteger :       
112                    pagecount += 1
113                    self.pages[pagecount] = { "copies" : self.pages[pagecount-1]["copies"] }
114            elif line.startswith(r"%%Requirements: numcopies(") :   
115                try :
116                    number = int(line.strip().split('(')[1].split(')')[0])
117                except :     
118                    pass
119                else :   
120                    if number > self.pages[pagecount]["copies"] :
121                        self.pages[pagecount]["copies"] = number
122            elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") :
123                # handle # of copies set by some Windows printer driver
124                try :
125                    number = int(line.strip().split()[2])
126                except :     
127                    pass
128                else :   
129                    if number > self.pages[pagecount]["copies"] :
130                        self.pages[pagecount]["copies"] = number
131            elif line.startswith("1 dict dup /NumCopies ") :
132                # handle # of copies set by mozilla/kprinter
133                try :
134                    number = int(line.strip().split()[4])
135                except :     
136                    pass
137                else :   
138                    if number > self.pages[pagecount]["copies"] :
139                        self.pages[pagecount]["copies"] = number
140            elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") :
141                try :
142                    number = int(previousline.strip()[2:])
143                except :
144                    pass
145                else :
146                    if number > self.pages[pagecount]["copies"] :
147                        self.pages[pagecount]["copies"] = number
148            elif line.startswith("/#copies ") :
149                try :
150                    number = int(line.strip().split()[1])
151                except :     
152                    pass
153                else :   
154                    if number > self.pages[pagecount]["copies"] :
155                        self.pages[pagecount]["copies"] = number
156            previousline = line
157           
158        # extract max number of copies to please the ghostscript parser, just   
159        # in case we will use it later
160        self.copies = max([ v["copies"] for (k, v) in self.pages.items() ])
161       
162        # now apply the number of copies to each page
163        for pnum in range(1, pagecount + 1) :
164            page = self.pages.get(pnum, self.pages.get(1, { "copies" : 1 }))
165            copies = page["copies"]
166            pagecount += (copies - 1)
167            self.logdebug("%s * page #%s" % (copies, pnum))
168        self.logdebug("Internal parser said : %s pages" % pagecount)
169       
170        if notrust :   
171            pagecount = 0 # Let gs do counting
172        return pagecount
173       
174    def getJobSize(self) :   
175        """Count pages in PostScript document."""
176        self.copies = 1
177        return self.natively() or self.throughGhostScript()
178       
179    def convertToTiffMultiPage24NC(self, fname, dpi) :
180        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
181           Writes TIFF datas to the outputfile file object.
182        """   
183        command = 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%i -sOutputFile="%s" -' % (dpi, fname)
184        child = popen2.Popen4(command)
185        try :
186            data = self.infile.read(pdlparser.MEGABYTE)   
187            while data :
188                child.tochild.write(data)
189                data = self.infile.read(pdlparser.MEGABYTE)
190            child.tochild.flush()
191            child.tochild.close()   
192        except (IOError, OSError), msg :   
193            raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg
194           
195        child.fromchild.close()
196        try :
197            child.wait()
198        except OSError, msg :   
199            raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg
200       
201def test() :       
202    """Test function."""
203    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
204        sys.argv.append("-")
205    totalsize = 0   
206    for arg in sys.argv[1:] :
207        if arg == "-" :
208            infile = sys.stdin
209            mustclose = 0
210        else :   
211            infile = open(arg, "rb")
212            mustclose = 1
213        try :
214            parser = Parser(infile, debug=1)
215            totalsize += parser.getJobSize()
216        except pdlparser.PDLParserError, msg :   
217            sys.stderr.write("ERROR: %s\n" % msg)
218            sys.stderr.flush()
219        if mustclose :   
220            infile.close()
221    print "%s" % totalsize
222   
223if __name__ == "__main__" :   
224    test()
Note: See TracBrowser for help on using the browser.