3 # pdfstrip.py - strip objects from PDF files by specifying objects IDs
5 # Copyright (C) 2016 Antonio Ospite <ao2@ao2.it>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 from pdfrw import PdfReader, PdfWriter
25 from pdfrw.objects.pdfindirect import PdfIndirect
28 # pylint: disable=invalid-name
29 logger = logging.getLogger(__name__)
30 console_handler = logging.StreamHandler()
31 formatter = logging.Formatter('[%(levelname)s] %(funcName)s:%(lineno)d %(message)s')
32 console_handler.setFormatter(formatter)
33 logger.addHandler(console_handler)
34 logger.propagate = False
37 def strip_objects(pdf, objects_ids):
38 for i, page in enumerate(pdf.pages):
39 logger.debug("Page %d", i + 1)
41 # Map all the objects in the page using the objects id as the key and
42 # the resource name as the value.
43 name_map = {indirect_obj.indirect[0]: name for name, indirect_obj in page.Resources.XObject.items()}
44 logger.debug("name_map: %s", name_map)
46 logger.debug("Before %s", page.Resources.XObject.keys())
48 for obj in objects_ids:
50 del page.Resources.XObject[name_map[obj]]
52 logger.debug("After %s\n", page.Resources.XObject.keys())
57 def validate_objects_ids(objects_ids_string):
59 objects_ids = [int(obj) for obj in objects_ids_string.split(',')]
60 except (IndexError, ValueError):
61 raise argparse.ArgumentTypeError("%s contains an invalid value" % objects_ids_string)
67 parser = argparse.ArgumentParser()
69 parser.add_argument("input_filename",
70 help="the input PDF file (better if uncompressed)")
71 parser.add_argument("output_filename",
72 help="the output PDF file")
73 parser.add_argument("objects_ids",
74 type=validate_objects_ids,
75 help="a comma-separated list of objects IDs")
76 parser.add_argument("-d", "--debug", action="store_true",
77 help="enable debug output")
78 args = parser.parse_args()
81 logger.setLevel(logging.DEBUG)
83 pdf_data = PdfReader(args.input_filename)
85 pdf_data = strip_objects(pdf_data, args.objects_ids)
87 PdfWriter().write(args.output_filename, pdf_data)
92 if __name__ == '__main__':