#!/usr/bin/env python # pdf2ps.py # filter for using pdf2ps (gs toolkit) instead of pdftops (xpdf toolkit) in CUPS # # Copyright (C) 2008 Yury Yurevich # # 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 <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:])