1#!/usr/bin/env python
2# Copyright 2014 The PDFium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Expands a hand-written PDF testcase (template) into a valid PDF file.
7
8There are several places in a PDF file where byte-offsets are required. This
9script replaces {{name}}-style variables in the input with calculated results
10
11  {{header}}     - expands to the header comment required for PDF files.
12  {{xref}}       - expands to a generated xref table, noting the offset.
13  {{startxref}   - expands to a startxref directive followed by correct offset.
14  {{object x y}} - expands to |x y obj| declaration, noting the offset."""
15
16import optparse
17import os
18import re
19import sys
20
21class TemplateProcessor:
22  HEADER_TOKEN =  '{{header}}'
23  HEADER_REPLACEMENT = '%PDF-1.7\n%\xa0\xf2\xa4\xf4'
24
25  XREF_TOKEN = '{{xref}}'
26  XREF_REPLACEMENT = 'xref\n%d %d\n'
27
28  # XREF rows must be exactly 20 bytes - space required.
29  XREF_REPLACEMENT_N = '%010d %05d n \n'
30  XREF_REPLACEMENT_F = '0000000000 65535 f \n'
31
32  STARTXREF_TOKEN= '{{startxref}}'
33  STARTXREF_REPLACEMENT = 'startxref\n%d'
34
35  OBJECT_PATTERN = r'\{\{object\s+(\d+)\s+(\d+)\}\}'
36  OBJECT_REPLACEMENT = r'\1 \2 obj'
37
38  def __init__(self):
39    self.offset = 0
40    self.xref_offset = 0
41    self.max_object_number = 0
42    self.objects = { }
43
44  def insert_xref_entry(self, object_number, generation_number):
45    self.objects[object_number] = (self.offset, generation_number)
46    self.max_object_number = max(self.max_object_number, object_number)
47
48  def generate_xref_table(self):
49    result = self.XREF_REPLACEMENT % (0, self.max_object_number + 1)
50    for i in range(0, self.max_object_number + 1):
51      if i in self.objects:
52        result += self.XREF_REPLACEMENT_N % self.objects[i]
53      else:
54        result += self.XREF_REPLACEMENT_F
55    return result
56
57  def process_line(self, line):
58    if self.HEADER_TOKEN in line:
59      line = line.replace(self.HEADER_TOKEN, self.HEADER_REPLACEMENT)
60    if self.XREF_TOKEN in line:
61      self.xref_offset = self.offset
62      line = self.generate_xref_table()
63    if self.STARTXREF_TOKEN in line:
64      replacement = self.STARTXREF_REPLACEMENT % self.xref_offset
65      line = line.replace(self.STARTXREF_TOKEN, replacement)
66    match = re.match(self.OBJECT_PATTERN, line)
67    if match:
68      self.insert_xref_entry(int(match.group(1)), int(match.group(2)))
69      line = re.sub(self.OBJECT_PATTERN, self.OBJECT_REPLACEMENT, line)
70    self.offset += len(line)
71    return line
72
73
74def expand_file(input_path, output_path):
75  processor = TemplateProcessor()
76  try:
77    with open(input_path, 'r') as infile:
78      with open(output_path, 'w') as outfile:
79        for line in infile:
80           outfile.write(processor.process_line(line))
81  except IOError:
82    print >> sys.stderr, 'failed to process %s' % input_path
83
84
85def main():
86  parser = optparse.OptionParser()
87  parser.add_option('--output-dir', default='')
88  options, args = parser.parse_args()
89  for testcase_path in args:
90    testcase_filename = os.path.basename(testcase_path)
91    testcase_root, _ = os.path.splitext(testcase_filename)
92    output_dir = os.path.dirname(testcase_path)
93    if options.output_dir:
94      output_dir = options.output_dir
95    output_path = os.path.join(output_dir, testcase_root + '.pdf')
96    expand_file(testcase_path, output_path)
97  return 0
98
99
100if __name__ == '__main__':
101  sys.exit(main())
102