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

Revision 321, 9.6 kB (checked in by jerome, 18 years ago)

Launches gs less often when acroread is used to print.
v1.78 is out.

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