usr bin env python pdf2ps py filter for using pdf2ps gs toolkit instea

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python
# pdf2ps.py
# filter for using pdf2ps (gs toolkit) instead of pdftops (xpdf toolkit) in CUPS
#
# Copyright (C) 2008 Yury Yurevich <the.pythy@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
"""
Wrapper script for pdf2ps (gs-common package)
"""
import os
import sys
import tempfile
import subprocess
pdf2ps = "/usr/bin/pdf2ps"
def parse_args(args):
if len(args) < 5:
raise ValueError("Wrong number of arguments %d instead of 5" % len(args))
job_id, username, title, copies, options, pdf_file = args
return job_id, username, title, copies, options, pdf_file
def get_input_file(pdf_file):
if pdf_file:
return pdf_file, False
# read from stdin to temp file
fd, t_pdf_file = tempfile.mkstemp('.pdf')
buf = sys.stdin.read(1024)
while buf:
os.write(fd, buf)
buf = sys.stdin.read(1024)
os.close(fd)
return t_pdf_file, True
def call_pdf2ps(input_file, output_file):
return subprocess.call([pdf2ps, input_file, output_file])
def write_to_stdout(fd):
buf = os.read(fd, 1024)
while buf:
sys.stdout.write(buf)
buf = os.read(fd, 1024)
sys.stdout.flush()
os.close(fd)
def convert(args):
files_to_delete = []
job_id, username, title, copies, options, _pdf = parse_args(args)
pdf_file, need_delete = get_input_file(_pdf)
if need_delete:
files_to_delete.append(pdf_file)
fd, ps_file = tempfile.mkstemp('.ps')
returncode = call_pdf2ps(pdf_file, ps_file)
if returncode == 0:
files_to_delete.append(ps_file)
write_to_stdout(fd)
for f in files_to_delete:
os.unlink(f)
if returncode != 0:
raise RuntimeError("pdf2ps returns non-zero code %d" % returncode)
def main(args):
try:
convert(args)
except ValueError, e:
sys.stderr.write("Usage: pdf2ps <job_id> <username> <title> <copies> <options> [pdf_file]\n")
sys.stderr.write("Err: %s\n" % e)
sys.exit(2)
except RuntimeError, e:
sys.stderr.write("Err: %s\n" % e)
sys.exit(1)
if __name__ == "__main__":
main(sys.argv[1:])