#!/usr/bin/python2 # -*- coding: utf-8 -*- # Copyright (C) 2015 Michael Weghorn # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import re import subprocess import sys # TODO adjust as necessary # This must be a directory to which CUPS has the permission to write. BASEPATH = '/var/spool/cups' # end of PDF file followed by start of next PDF file re_eof = re.compile("\n*%%EOF\n*%PDF-") # args: job-id user title copies options [file] arg_count = len(sys.argv) if arg_count == 1: # TODO print information as specified, s. 'man backend' exit(0) if arg_count < 6 or arg_count > 7: print("Usage: {} job-id user title copies options [file]".format( sys.argv[0])) exit(1) if arg_count == 7: filename = sys.argv[6] with open(filename) as source: content = source.read() else: content = sys.stdin.read() # extract single PDF documents from the input docs = re_eof.split(content) if "" in docs: docs.remove("") document_names = [] # write out the single PDF documents for i in range(0, len(docs)): filename = "out{}.pdf".format(i) filename = os.path.join(BASEPATH, filename) document_names.append(filename) with open(filename, "w") as outfile: file_content = docs[i] + "\n%%EOF\n" # restore PDF "header" for all PDF documents except for the first # which still has the original one if i != 0: file_content = "%PDF-" + file_content outfile.write(file_content) # merge all documents using pdftk outfile_name = os.path.join(BASEPATH, 'result.pdf') subprocess.call(["pdftk"] + document_names + ["cat", "output", outfile_name])