Project

General

Profile

« Previous | Next » 

Revision 775dcb4b

Added by Benjamin Dauvergne almost 12 years ago

remove dependency on fdfgen

View differences:

calebasse/pdftk.py
2 2
import subprocess
3 3
import tempfile
4 4

  
5
from fdfgen import forge_fdf
6

  
7 5
class PdfTk(object):
8 6
    def __init__(self, pdftk_path=None, prefix='tmp'):
9 7
        self._pdftk_path = pdftk_path
......
29 27
        args = [input_file, 'background', background_file, 'output', output_file, 'compress']
30 28
        return self.do(args, wait=wait)
31 29

  
32
    def form_fill(self, pdf_file, fields, output_file, flatten=False, wait=True, delete=False):
33
        string_fields = []
34
        other_fields = []
35
        # separate string from booleans
36
        for k, v in fields.iteritems():
37
            if isinstance(k, basestring):
38
                string_fields.append((k, v))
39
            else:
40
                other_fields.append((k[0], k[1] if isinstance(v, bool) else v))
41
        with tempfile.NamedTemporaryFile(delete=wait, prefix=self.prefix,
42
                suffix='.fdf') as temp_fdf:
43
            try:
44
                fdf = forge_fdf("", string_fields, other_fields, [], [])
45
                temp_fdf.write(fdf)
46
                temp_fdf.flush()
47
                args = [pdf_file, 'fill_form', temp_fdf.name, 'output', output_file]
48
                if flatten:
49
                    args.append('flatten')
50
                result = self.do(args, wait=wait)
51
                temp_fdf.close()
52
                if wait:
53
                    return result
54
                else:
55
                    return result, temp_fdf.name
56
            except:
57
                if delete:
58
                    try:
59
                        os.unlink(temp_fdf.name)
60
                    except:
61
                        pass
62
                raise
63 30

  
64 31
if __name__ == '__main__':
65 32
    import sys
......
67 34
    pdftk = PdfTk()
68 35
    if sys.argv[1] == 'concat':
69 36
        pdftk.concat(sys.argv[2].split(','), sys.argv[3])
70
    elif sys.argv[1] == 'fill':
71
        fields = sys.argv[3].split(',')
72
        fields = zip(fields[0::2], fields[1::2])
73
        pdftk.form_fill(sys.argv[2], dict(fields), sys.argv[4])
37
    elif sys.argv[1] == 'background':
38
        pdftk.background(*sys.argv[2:5])
74 39
    else:
75 40
        raise RuntimeError('Unknown command %s', sys.argv)

Also available in: Unified diff