From a4f43aea0f0af03190e95a431a96722325d8ee9e Mon Sep 17 00:00:00 2001 From: Johannes Schauer Date: Sat, 10 Oct 2015 00:55:44 +0200 Subject: import new upstream version 0.2 --- .gitignore | 52 +++ .travis.yml | 17 + LICENSE.txt | 45 +- MANIFEST.in | 2 + README.rst | 745 ++++++++++++++++++++++++++++++++++ README.txt | 3 - examples/4up.py | 66 ++- examples/alter.py | 1 - examples/booklet.py | 60 +-- examples/cat.py | 35 ++ examples/extract.py | 27 ++ examples/find_pdfrw.py | 33 -- examples/metadata.py | 39 -- examples/poster.py | 70 ++-- examples/print_two.py | 44 +- examples/rl1/4up.py | 1 - examples/rl1/booklet.py | 3 +- examples/rl1/find_pdfrw.py | 33 -- examples/rl1/platypus_pdf_template.py | 30 +- examples/rl1/subset.py | 7 +- examples/rl2/copy.py | 2 +- examples/rl2/decodegraphics.py | 114 ++++-- examples/rl2/find_pdfrw.py | 33 -- examples/rotate.py | 4 +- examples/subset.py | 1 - examples/unspread.py | 32 ++ examples/watermark.py | 123 +----- pdfrw/__init__.py | 22 +- pdfrw/buildxobj.py | 201 ++++++--- pdfrw/compress.py | 13 +- pdfrw/errors.py | 15 +- pdfrw/findobjs.py | 138 +++++++ pdfrw/objects/__init__.py | 19 +- pdfrw/objects/pdfarray.py | 28 +- pdfrw/objects/pdfdict.py | 84 ++-- pdfrw/objects/pdfindirect.py | 6 +- pdfrw/objects/pdfname.py | 83 +++- pdfrw/objects/pdfobject.py | 5 +- pdfrw/objects/pdfstring.py | 31 +- pdfrw/pagemerge.py | 242 +++++++++++ pdfrw/pdfreader.py | 388 ++++++++++++------ pdfrw/pdfwriter.py | 176 +++++--- pdfrw/py23_diffs.py | 46 +++ pdfrw/tokens.py | 92 +++-- pdfrw/toreportlab.py | 19 +- pdfrw/uncompress.py | 90 +++- releasing.txt | 10 + setup.cfg | 5 + setup.py | 38 +- tests/checkdiffs.py | 81 ++++ tests/expected.py | 41 ++ tests/expected.txt | 140 +++++++ tests/myprofile.py | 5 + tests/test_examples.py | 195 +++++++++ tests/test_pdfstring.py | 6 +- tests/test_roundtrip.py | 132 ++++++ 56 files changed, 3109 insertions(+), 864 deletions(-) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 MANIFEST.in create mode 100644 README.rst delete mode 100644 README.txt create mode 100755 examples/cat.py create mode 100755 examples/extract.py delete mode 100644 examples/find_pdfrw.py delete mode 100755 examples/metadata.py delete mode 100644 examples/rl1/find_pdfrw.py delete mode 100644 examples/rl2/find_pdfrw.py create mode 100755 examples/unspread.py create mode 100644 pdfrw/findobjs.py create mode 100644 pdfrw/pagemerge.py create mode 100644 pdfrw/py23_diffs.py create mode 100644 releasing.txt create mode 100644 setup.cfg create mode 100755 tests/checkdiffs.py create mode 100644 tests/expected.py create mode 100644 tests/expected.txt create mode 100644 tests/myprofile.py create mode 100755 tests/test_examples.py create mode 100755 tests/test_roundtrip.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6260e55 --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# Development artifacts +diffs.txt +examples/*.pdf +examples/rl*/*.pdf +tests/*.pdf +examples/pdfrw +examples/rl*/pdfrw +tests/pdfrw +tests/static_pdfs +tests/ramdisk +tests/saved_results +wiki/ + + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# Distribution / packaging +.Python +env/ +bin/ +build/ +develop-eggs/ +dist/ +eggs/ +lib/ +lib64/ +lib64 +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg +pyvenv.cfg +pip-selfcheck.json + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml + +# Sphinx documentation +docs/_build/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..caa88f5 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,17 @@ +language: python +python: + - "2.6" + - "2.7" + - "3.3" + - "3.4" + - "nightly" +# command to install dependencies +before_install: + - "git clone https://github.com/pmaupin/static_pdfs tests/static_pdfs" +install: + - "pip install ." + - "pip install reportlab || true" + - "pip install zlib || true" + - "pip install unittest2 || true" +# command to run tests +script: "cd tests; /usr/bin/env PYTHONPATH=. py.test" diff --git a/LICENSE.txt b/LICENSE.txt index 7439b9c..8d3c13d 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,20 @@ -pdfrw (pdfrw.googlecode.com) +pdfrw (github.com/pmaupin/pdfrw) -Copyright (c) 2006-2012 Patrick Maupin +The majority of pdfrw was written by Patrick Maupin and is licensed +under the MIT license (reproduced below). Other contributors include +Attila Tajti and Nerijus Mika. It appears that some of the decompression +code was based on the decompressor from PyPDF2, which was written by +Mathieu Fenniak and licensed under the BSD license (also reproduced below). + +Please add any missing authors here: + +Copyright (c) 2006-2015 Patrick Maupin. All rights reserved. +Copyright (c) 2006 Mathieu Fenniak. All rights reserved. +Copyright (c) 2010 Attila Tajti. All rights reserved. +Copyright (c) 2012 Nerijus Mika. All rights reserved. + + +MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,3 +33,30 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +BSD License: + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..f90ac68 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include *.txt *.in *.rst +recursive-include examples *.txt *.py diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..2c91345 --- /dev/null +++ b/README.rst @@ -0,0 +1,745 @@ +============= +pdfrw 0.2b1 +============= + +:Author: Patrick Maupin + +.. contents:: + :backlinks: none + +.. sectnum:: + +Introduction +============ + +**pdfrw** is a Python library and utility that reads and writes PDF files: + +* Version 0.2 is tested and works on Python 2.6, 2.7, 3.3, and 3.4. +* Operations include subsetting, merging, rotating, modifying metadata, etc. +* The fastest pure Python PDF parser available +* Has been used for years by a printer in pre-press production +* Can be used with rst2pdf to faithfully reproduce vector images +* Can be used either standalone, or in conjunction with `reportlab`__ + to reuse existing PDFs in new ones +* Permissively licensed + +__ http://www.reportlab.org/ + + +pdfrw will faithfully reproduce vector formats without +rasterization, so the rst2pdf package has used pdfrw +for PDF and SVG images by default since March 2010. + +pdfrw can also be used in conjunction with reportlab, in order +to re-use portions of existing PDFs in new PDFs created with +reportlab. + + +Examples +========= + +The library comes with several examples that show operation both with +and without reportlab. + + +All examples +------------------ + +The examples directory has a few scripts which use the library. +Note that if these examples do not work with your PDF, you should +try to use pdftk to uncompress and/or unencrypt them first. + +* `4up.py`__ will shrink pages down and place 4 of them on + each output page. +* `alter.py`__ shows an example of modifying metadata, without + altering the structure of the PDF. +* `booklet.py`__ shows an example of creating a 2-up output + suitable for printing and folding (e.g on tabloid size paper). +* `cat.py`__ shows an example of concatenating multiple PDFs together. +* `extract.py`__ will extract images and Form XObjects (embedded pages) + from existing PDFs to make them easier to use and refer to from + new PDFs (e.g. with reportlab or rst2pdf). +* `poster.py`__ increases the size of a PDF so it can be printed + as a poster. +* `print_two.py`__ Allows creation of 8.5 X 5.5" booklets by slicing + 8.5 X 11" paper apart after printing. +* `rotate.py`__ Rotates all or selected pages in a PDF. +* `subset.py`__ Creates a new PDF with only a subset of pages from the + original. +* `unspread.py`__ Takes a 2-up PDF, and splits out pages. +* `watermark.py`__ Adds a watermark PDF image over or under all the pages + of a PDF. +* `rl1/4up.py`__ Another 4up example, using reportlab canvas for output. +* `rl1/booklet.py`__ Another booklet example, using reportlab canvas for + output. +* `rl1/subset.py`__ Another subsetting example, using reportlab canvas for + output. +* `rl1/platypus_pdf_template.py`__ Aother watermarking example, using + reportlab canvas and generated output for the document. Contributed + by user asannes. +* `rl2`__ Experimental code for parsing graphics. Needs work. + +__ https://github.com/pmaupin/pdfrw/tree/master/examples/4up.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/alter.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/booklet.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/cat.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/extract.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/poster.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/print_two.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rotate.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/subset.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/unspread.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/watermark.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rl1/4up.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rl1/booklet.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rl1/subset.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rl1/platypus_pdf_template.py +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rl2/ + +Notes on selected examples +------------------------------------ + +Reorganizing pages and placing them two-up +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A printer with a fancy printer and/or a full-up copy of Acrobat can +easily turn your small PDF into a little booklet (for example, print 4 +letter-sized pages on a single 11" x 17"). + +But that assumes several things, including that the personnel know how +to operate the hardware and software. `booklet.py`__ lets you turn your PDF +into a preformatted booklet, to give them fewer chances to mess it up. + +__ https://github.com/pmaupin/pdfrw/tree/master/examples/booklet.py + +Adding or modifying metadata +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The `cat.py`__ example will accept multiple input files on the command +line, concatenate them and output them to output.pdf, after adding some +nonsensical metadata to the output PDF file. + +__ https://github.com/pmaupin/pdfrw/tree/master/examples/cat.py + +The `alter.py`__ example alters a single metadata item in a PDF, +and writes the result to a new PDF. + +__ https://github.com/pmaupin/pdfrw/tree/master/examples/alter.py + + +One difference is that, since **cat** is creating a new PDF structure, +and **alter** is attempting to modify an existing PDF structure, the +PDF produced by alter (and also by watermark.py) *should* be +more faithful to the original (except for the desired changes). + +For example, the alter.py navigation should be left intact, whereas with +cat.py it will be stripped. + + +Rotating and doubling +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you ever want to print something that is like a small booklet, but +needs to be spiral bound, you either have to do some fancy rearranging, +or just waste half your paper. + +The `print_two.py`__ example program will, for example, make two side-by-side +copies each page of of your PDF on a each output sheet. + +__ https://github.com/pmaupin/pdfrw/tree/master/examples/print_two.py + +But, every other page is flipped, so that you can print double-sided and +the pages will line up properly and be pre-collated. + +Graphics stream parsing proof of concept +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The `copy.py`__ script shows a simple example of reading in a PDF, and +using the decodegraphics.py module to try to write the same information +out to a new PDF through a reportlab canvas. (If you know about reportlab, +you know that if you can faithfully render a PDF to a reportlab canvas, you +can do pretty much anything else with that PDF you want.) This kind of +low level manipulation should be done only if you really need to. +decodegraphics is really more than a proof of concept than anything +else. For most cases, just use the Form XObject capability, as shown in +the examples/rl1/booklet.py demo. + +__ https://github.com/pmaupin/pdfrw/tree/master/examples/rl2/copy.py + +pdfrw philosophy +================== + +Core library +------------- + +The philosophy of the library portion of pdfrw is to provide intuitive +functions to read, manipulate, and write PDF files. There should be +minimal leakage between abstraction layers, although getting useful +work done makes "pure" functionality separation difficult. + +A key concept supported by the library is the use of Form XObjects, +which allow easy embedding of pieces of one PDF into another. + +Addition of core support to the library is typically done carefully +and thoughtfully, so as not to clutter it up with too many special +cases. + +There are a lot of incorrectly formatted PDFs floating around; support +for these is added in some cases. The decision is often based on what +acroread and okular do with the PDFs; if they can display them properly, +then eventually pdfrw should, too, if it is not too difficult or costly. + +Contributions are welcome; one user has contributed some decompression +filters and the ability to process PDF 1.5 stream objects. Additional +functionality that would obviously be useful includes additional +decompression filters, the ability to process password-protected PDFs, +and the ability to output linearized PDFs. + +Examples +-------- + +The philosophy of the examples is to provide small, easily-understood +examples that showcase pdfrw functionality. + + +PDF files and Python +====================== + +Introduction +------------ + +In general, PDF files conceptually map quite well to Python. The major +objects to think about are: + +- **strings**. Most things are strings. These also often decompose + naturally into +- **lists of tokens**. Tokens can be combined to create higher-level + objects like +- **arrays** and +- **dictionaries** and +- **Contents streams** (which can be more streams of tokens) + +Difficulties +------------ + +The apparent primary difficulty in mapping PDF files to Python is the +PDF file concept of "indirect objects." Indirect objects provide +the efficiency of allowing a single piece of data to be referred to +from more than one containing object, but probably more importantly, +indirect objects provide a way to get around the chicken and egg +problem of circular object references when mapping arbitrary data +structures to files. To flatten out a circular reference, an indirect +object is *referred to* instead of being *directly included* in another +object. PDF files have a global mechanism for locating indirect objects, +and they all have two reference numbers (a reference number and a +"generation" number, in case you wanted to append to the PDF file +rather than just rewriting the whole thing). + +pdfrw automatically handles indirect references on reading in a PDF +file. When pdfrw encounters an indirect PDF file object, the +corresponding Python object it creates will have an 'indirect' attribute +with a value of True. When writing a PDF file, if you have created +arbitrary data, you just need to make sure that circular references are +broken up by putting an attribute named 'indirect' which evaluates to +True on at least one object in every cycle. + +Another PDF file concept that doesn't quite map to regular Python is a +"stream". Streams are dictionaries which each have an associated +unformatted data block. pdfrw handles streams by placing a special +attribute on a subclassed dictionary. + +Usage Model +----------- + +The usage model for pdfrw treats most objects as strings (it takes their +string representation when writing them to a file). The two main +exceptions are the PdfArray object and the PdfDict object. + +PdfArray is a subclass of list with two special features. First, +an 'indirect' attribute allows a PdfArray to be written out as +an indirect PDF object. Second, pdfrw reads files lazily, so +PdfArray knows about, and resolves references to other indirect +objects on an as-needed basis. + +PdfDict is a subclass of dict that also has an indirect attribute +and lazy reference resolution as well. (And the subclassed +IndirectPdfDict has indirect automatically set True). + +But PdfDict also has an optional associated stream. The stream object +defaults to None, but if you assign a stream to the dict, it will +automatically set the PDF /Length attribute for the dictionary. + +Finally, since PdfDict instances are indexed by PdfName objects (which +always start with a /) and since most (all?) standard Adobe PdfName +objects use names formatted like "/CamelCase", it makes sense to allow +access to dictionary elements via object attribute accesses as well as +object index accesses. So usage of PdfDict objects is normally via +attribute access, although non-standard names (though still with a +leading slash) can be accessed via dictionary index lookup. + +Reading PDFs +~~~~~~~~~~~~~~~ + +The PdfReader object is a subclass of PdfDict, which allows easy access +to an entire document:: + + >>> from pdfrw import PdfReader + >>> x = PdfReader('source.pdf') + >>> x.keys() + ['/Info', '/Size', '/Root'] + >>> x.Info + {'/Producer': '(cairo 1.8.6 (http://cairographics.org))', + '/Creator': '(cairo 1.8.6 (http://cairographics.org))'} + >>> x.Root.keys() + ['/Type', '/Pages'] + +Info, Size, and Root are retrieved from the trailer of the PDF file. + +In addition to the tree structure, pdfrw creates a special attribute +named *pages*, that is a list of all the pages in the document. pdfrw +creates the *pages* attribute as a simplification for the user, because +the PDF format allows arbitrarily complicated nested dictionaries to +describe the page order. Each entry in the *pages* list is the PdfDict +object for one of the pages in the file, in order. + +:: + + >>> len(x.pages) + 1 + >>> x.pages[0] + {'/Parent': {'/Kids': [{...}], '/Type': '/Pages', '/Count': '1'}, + '/Contents': {'/Length': '11260', '/Filter': None}, + '/Resources': ... (Lots more stuff snipped) + >>> x.pages[0].Contents + {'/Length': '11260', '/Filter': None} + >>> x.pages[0].Contents.stream + 'q\n1 1 1 rg /a0 gs\n0 0 0 RG 0.657436 + w\n0 J\n0 j\n[] 0.0 d\n4 M q' ... (Lots more stuff snipped) + +Writing PDFs +~~~~~~~~~~~~~~~ + +As you can see, it is quite easy to dig down into a PDF document. But +what about when it's time to write it out? + +:: + + >>> from pdfrw import PdfWriter + >>> y = PdfWriter() + >>> y.addpage(x.pages[0]) + >>> y.write('result.pdf') + +That's all it takes to create a new PDF. You may still need to read the +`Adobe PDF reference manual`__ to figure out what needs to go *into* +the PDF, but at least you don't have to sweat actually building it +and getting the file offsets right. + +__ http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf + +Manipulating PDFs in memory +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For the most part, pdfrw tries to be agnostic about the contents of +PDF files, and support them as containers, but to do useful work, +something a little higher-level is required, so pdfrw works to +understand a bit about the contents of the containers. For example: + +- PDF pages. pdfrw knows enough to find the pages in PDF files you read + in, and to write a set of pages back out to a new PDF file. +- Form XObjects. pdfrw can take any page or rectangle on a page, and + convert it to a Form XObject, suitable for use inside another PDF + file. It knows enough about these to perform scaling, rotation, + and positioning. +- reportlab objects. pdfrw can recursively create a set of reportlab + objects from its internal object format. This allows, for example, + Form XObjects to be used inside reportlab, so that you can reuse + content from an existing PDF file when building a new PDF with + reportlab. + +There are several examples that demonstrate these features in +the example code directory. + +Missing features +~~~~~~~~~~~~~~~~~~~~~~~ + +Even as a pure PDF container library, pdfrw comes up a bit short. It +does not currently support: + +- Most compression/decompression filters +- encryption + +`pdftk`__ is a wonderful command-line +tool that can convert your PDFs to remove encryption and compression. +However, in most cases, you can do a lot of useful work with PDFs +without actually removing compression, because only certain elements +inside PDFs are actually compressed. + +__ https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/ + +Library internals +================== + +Introduction +------------ + +**pdfrw** currently consists of 19 modules organized into a main +package and one sub-package. + +The `__init.py__`__ module does the usual thing of importing a few +major attributes from some of the submodules, and the `errors.py`__ +module supports logging and exception generation. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/__init__.py +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/errors.py + + +PDF object model support +-------------------------- + +The `objects`__ sub-package contains one module for each of the +internal representations of the kinds of basic objects that exist +in a PDF file, with the `objects/__init__.py`__ module in that +package simply gathering them up and making them available to the +main pdfrw package. + +One feature that all the PDF object classes have in common is the +inclusion of an 'indirect' attribute. If 'indirect' exists and evaluates +to True, then when the object is written out, it is written out as an +indirect object. That is to say, it is addressable in the PDF file, and +could be referenced by any number (including zero) of container objects. +This indirect object capability saves space in PDF files by allowing +objects such as fonts to be referenced from multiple pages, and also +allows PDF files to contain internal circular references. This latter +capability is used, for example, when each page object has a "parent" +object in its dictionary. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/ +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/__init__.py + +Ordinary objects +~~~~~~~~~~~~~~~~ + +The `objects/pdfobject.py`__ module contains the PdfObject class, which is +a subclass of str, and is the catch-all object for any PDF file elements +that are not explicitly represented by other objects, as described below. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/pdfobject.py + +Name objects +~~~~~~~~~~~~ + +The `objects/pdfname.py`__ module contains the PdfName singleton object, +which will convert a string into a PDF name by prepending a slash. It can +be used either by calling it or getting an attribute, e.g.:: + + PdfName.Rotate == PdfName('Rotate') == PdfObject('/Rotate') + +In the example above, there is a slight difference between the objects +returned from PdfName, and the object returned from PdfObject. The +PdfName objects are actually objects of class "BasePdfName". This +is important, because only these may be used as keys in PdfDict objects. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/pdfname.py + +String objects +~~~~~~~~~~~~~~ + +The `objects/pdfstring.py`__ +module contains the PdfString class, which is a subclass of str that is +used to represent encoded strings in a PDF file. The class has encode +and decode methods for the strings. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/pdfstring.py + + +Array objects +~~~~~~~~~~~~~ + +The `objects/pdfarray.py`__ +module contains the PdfArray class, which is a subclass of list that is +used to represent arrays in a PDF file. A regular list could be used +instead, but use of the PdfArray class allows for an indirect attribute +to be set, and also allows for proxying of unresolved indirect objects +(that haven't been read in yet) in a manner that is transparent to pdfrw +clients. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/pdfarray.py + +Dict objects +~~~~~~~~~~~~ + +The `objects/pdfdict.py`__ +module contains the PdfDict class, which is a subclass of dict that is +used to represent dictionaries in a PDF file. A regular dict could be +used instead, but the PdfDict class matches the requirements of PDF +files more closely: + +* Transparent (from the library client's viewpoint) proxying + of unresolved indirect objects +* Return of None for non-existent keys (like dict.get) +* Mapping of attribute accesses to the dict itself + (pdfdict.Foo == pdfdict[NameObject('Foo')]) +* Automatic management of following stream and /Length attributes + for content dictionaries +* Indirect attribute +* Other attributes may be set for private internal use of the + library and/or its clients. +* Support for searching parent dictionaries for PDF "inheritable" + attributes. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/pdfdict.py + +If a PdfDict has an associated data stream in the PDF file, the stream +is accessed via the 'stream' (all lower-case) attribute. Setting the +stream attribute on the PdfDict will automatically set the /Length attribute +as well. If that is not what is desired (for example if the the stream +is compressed), then _stream (same name with an underscore) may be used +to associate the stream with the PdfDict without setting the length. + +To set private attributes (that will not be written out to a new PDF +file) on a dictionary, use the 'private' attribute:: + + mydict.private.foo = 1 + +Once the attribute is set, it may be accessed directly as an attribute +of the dictionary:: + + foo = mydict.foo + +Some attributes of PDF pages are "inheritable." That is, they may +belong to a parent dictionary (or a parent of a parent dictionary, etc.) +The "inheritable" attribute allows for easy discovery of these:: + + mediabox = mypage.inheritable.MediaBox + + +Proxy objects +~~~~~~~~~~~~~ + +The `objects/pdfindirect.py`__ +module contains the PdfIndirect class, which is a non-transparent proxy +object for PDF objects that have not yet been read in and resolved from +a file. Although these are non-transparent inside the library, client code +should never see one of these -- they exist inside the PdfArray and PdfDict +container types, but are resolved before being returned to a client of +those types. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/objects/pdfindirect.py + + +File reading, tokenization and parsing +-------------------------------------- + +`pdfreader.py`__ +contains the PdfReader class, which can read a PDF file (or be passed a +file object or already read string) and parse it. It uses the PdfTokens +class in `tokens.py`__ for low-level tokenization. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/pdfreader.py +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/tokens.py + + +The PdfReader class does not, in general, parse into containers (e.g. +inside the content streams). There is a proof of concept for doing that +inside the examples/rl2 subdirectory, but that is slow and not well-developed, +and not useful for most applications. + +An instance of the PdfReader class is an instance of a PdfDict -- the +trailer dictionary of the PDF file, to be exact. It will have a private +attribute set on it that is named 'pages' that is a list containing all +the pages in the file. + +When instantiating a PdfReader object, there are options available +for decompressing all the objects in the file. pdfrw does not currently +have very many options for decompression, so this is not all that useful, +except in the specific case of compressed object streams. + +Also, there are no options for decryption yet. If you have PDF files +that are encrypted or heavily compressed, you may find that using another +program like pdftk on them can make them readable by pdfrw. + +In general, the objects are read from the file lazily, but this is not +currently true with compressed object streams -- all of these are decompressed +and read in when the PdfReader is instantiated. + + +File output +----------- + +`pdfwriter.py`__ +contains the PdfWriter class, which can create and output a PDF file. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/pdfwriter.py + +There are a few options available when creating and using this class. + +In the simplest case, an instance of PdfWriter is instantiated, and +then pages are added to it from one or more source files (or created +programmatically), and then the write method is called to dump the +results out to a file. + +If you have a source PDF and do not want to disturb the structure +of it too badly, then you may pass its trailer directly to PdfWriter +rather than letting PdfWriter construct one for you. There is an +example of this (alter.py) in the examples directory. + + +Advanced features +----------------- + +`buildxobj.py`__ +contains functions to build Form XObjects out of pages or rectangles on +pages. These may be reused in new PDFs essentially as if they were images. + +buildxobj is careful to cache any page used so that it only appears in +the output once. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/buildxobj.py + + +`toreportlab.py`__ +provides the makerl function, which will translate pdfrw objects into a +format which can be used with `reportlab `__. +It is normally used in conjunction with buildxobj, to be able to reuse +parts of existing PDFs when using reportlab. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/toreportlab.py + + +`pagemerge.py`__ builds on the foundation laid by buildxobj. It +contains classes to create a new page (or overlay an existing page) +using one or more rectangles from other pages. There are examples +showing its use for watermarking, scaling, 4-up output, splitting +each page in 2, etc. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/pagemerge.py + +`findobjs.py`__ contains code that can find specific kinds of objects +inside a PDF file. The extract.py example uses this module to create +a new PDF that places each image and Form XObject from a source PDF onto +its own page, e.g. for easy reuse with some of the other examples or +with reportlab. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/findobjs.py + + +Miscellaneous +---------------- + +`compress.py`__ and `uncompress.py`__ +contains compression and decompression functions. Very few filters are +currently supported, so an external tool like pdftk might be good if you +require the ability to decompress (or, for that matter, decrypt) PDF +files. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/compress.py +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/uncompress.py + + +`py23_diffs.py`__ contains code to help manage the differences between +Python 2 and Python 3. + +__ https://github.com/pmaupin/pdfrw/tree/master/pdfrw/py23_diffs.py + +Testing +=============== + +The tests associated with pdfrw require a large number of PDFs, +which are not distributed with the library. + +To run the tests: + +* Download or clone the full package from github.com/pmaupin/pdfrw +* cd into the tests directory, and then clone the package + github.com/pmaupin/static_pdfs into a subdirectory (also named + static_pdfs). +* Now the tests may be run from that directory using unittest, or + py.test, or nose. +* travisci is used at github, and runs the tests with py.test + +Other libraries +===================== + +Pure Python +----------- + +- `reportlab `__ + + reportlab is must-have software if you want to programmatically + generate arbitrary PDFs. + +- `pyPdf `__ + + pyPdf is, in some ways, very full-featured. It can do decompression + and decryption and seems to know a lot about items inside at least + some kinds of PDF files. In comparison, pdfrw knows less about + specific PDF file features (such as metadata), but focuses on trying + to have a more Pythonic API for mapping the PDF file container + syntax to Python, and (IMO) has a simpler and better PDF file + parser. The Form XObject capability of pdfrw means that, in many + cases, it does not actually need to decompress objects -- they + can be left compressed. + +- `pdftools `__ + + pdftools feels large and I fell asleep trying to figure out how it + all fit together, but many others have done useful things with it. + +- `pagecatcher `__ + + My understanding is that pagecatcher would have done exactly what I + wanted when I built pdfrw. But I was on a zero budget, so I've never + had the pleasure of experiencing pagecatcher. I do, however, use and + like `reportlab `__ (open source, from + the people who make pagecatcher) so I'm sure pagecatcher is great, + better documented and much more full-featured than pdfrw. + +- `pdfminer `__ + + This looks like a useful, actively-developed program. It is quite + large, but then, it is trying to actively comprehend a full PDF + document. From the website: + + "PDFMiner is a suite of programs that help extracting and analyzing + text data of PDF documents. Unlike other PDF-related tools, it + allows to obtain the exact location of texts in a page, as well as + other extra information such as font information or ruled lines. It + includes a PDF converter that can transform PDF files into other + text formats (such as HTML). It has an extensible PDF parser that + can be used for other purposes instead of text analysis." + +non-pure-Python libraries +------------------------- + +- `pyPoppler `__ can read PDF + files. +- `pycairo `__ can write PDF + files. + +Other tools +----------- + +- `pdftk `__ is a wonderful command + line tool for basic PDF manipulation. It complements pdfrw extremely + well, supporting many operations such as decryption and decompression + that pdfrw cannot do. + +Release information +======================= + +Revisions: + +0.2 -- Released 21 June, 2015. Supports Python 2.6, 2.7, 3.3, and 3.4. + + - Several bugs have been fixed + - New regression test functionally tests core with dozens of + PDFs, and also tests examples. + - Core has been ported and tested on Python3 by round-tripping + several difficult files and observing binary matching results + across the different Python versions. + - Still only minimal support for compression and no support + for encryption or newer PDF features. (pdftk is useful + to put PDFs in a form that pdfrw can use.) + +0.1 -- Released to PyPI in 2012. Supports Python 2.5 - 2.7 + diff --git a/README.txt b/README.txt deleted file mode 100644 index 843347f..0000000 --- a/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -pdfrw reads and writes PDF files. - -More info at http://code.google.com/p/pdfrw diff --git a/examples/4up.py b/examples/4up.py index 491af14..ad2bd3b 100755 --- a/examples/4up.py +++ b/examples/4up.py @@ -1,51 +1,33 @@ #!/usr/bin/env python ''' -usage: 4up.py my.pdf firstpage lastpage - -Creates 4up.my.pdf +usage: 4up.py my.pdf +Creates 4up.my.pdf with a single output page for every +4 input pages. ''' import sys import os -import find_pdfrw -from pdfrw import PdfReader, PdfWriter, PdfDict, PdfName, PdfArray -from pdfrw.buildxobj import pagexobj - -def get4(allpages): - # Pull a maximum of 4 pages off the list - pages = [pagexobj(x) for x in allpages[:4]] - del allpages[:4] - - x_max = max(page.BBox[2] for page in pages) - y_max = max(page.BBox[3] for page in pages) - - stream = [] - xobjdict = PdfDict() - for index, page in enumerate(pages): - x = x_max * (index & 1) / 2.0 - y = y_max * (index <= 1) / 2.0 - index = '/P%s' % index - stream.append('q 0.5 0 0 0.5 %s %s cm %s Do Q\n' % (x, y, index)) - xobjdict[index] = page - - return PdfDict( - Type = PdfName.Page, - Contents = PdfDict(stream=''.join(stream)), - MediaBox = PdfArray([0, 0, x_max, y_max]), - Resources = PdfDict(XObject = xobjdict), - ) - -def go(inpfn, outfn): - pages = PdfReader(inpfn).pages - writer = PdfWriter() - while pages: - writer.addpage(get4(pages)) - writer.write(outfn) - -if __name__ == '__main__': - inpfn, = sys.argv[1:] - outfn = '4up.' + os.path.basename(inpfn) - go(inpfn, outfn) +from pdfrw import PdfReader, PdfWriter, PageMerge + + +def get4(srcpages): + scale = 0.5 + srcpages = PageMerge() + srcpages + x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:]) + for i, page in enumerate(srcpages): + page.scale(scale) + page.x = x_increment if i & 1 else 0 + page.y = 0 if i & 2 else y_increment + return srcpages.render() + + +inpfn, = sys.argv[1:] +outfn = '4up.' + os.path.basename(inpfn) +pages = PdfReader(inpfn).pages +writer = PdfWriter() +for index in range(0, len(pages), 4): + writer.addpage(get4(pages[index:index + 4])) +writer.write(outfn) diff --git a/examples/alter.py b/examples/alter.py index 1c6d4e1..45b9c76 100755 --- a/examples/alter.py +++ b/examples/alter.py @@ -12,7 +12,6 @@ Demonstrates making a slight alteration to a preexisting PDF file. import sys import os -import find_pdfrw from pdfrw import PdfReader, PdfWriter inpfn, = sys.argv[1:] diff --git a/examples/booklet.py b/examples/booklet.py index 0b3be74..4758b08 100755 --- a/examples/booklet.py +++ b/examples/booklet.py @@ -5,61 +5,35 @@ usage: booklet.py my.pdf Creates booklet.my.pdf -Pages organized in a form suitable for booklet printing. - +Pages organized in a form suitable for booklet printing, e.g. +to print 4 8.5x11 pages using a single 11x17 sheet (double-sided). ''' import sys import os -import find_pdfrw -from pdfrw import PdfReader, PdfWriter, PdfDict, PdfArray, PdfName, IndirectPdfDict -from pdfrw.buildxobj import pagexobj - -def fixpage(*pages): - pages = [pagexobj(x) for x in pages] +from pdfrw import PdfReader, PdfWriter, PageMerge - class PageStuff(tuple): - pass - x = y = 0 - for i, page in enumerate(pages): - index = '/P%s' % i - shift_right = x and '1 0 0 1 %s 0 cm ' % x or '' - stuff = PageStuff((index, page)) - stuff.stream = 'q %s%s Do Q\n' % (shift_right, index) - x += page.BBox[2] - y = max(y, page.BBox[3]) - pages[i] = stuff - - # Multiple copies of first page used as a placeholder to - # get blank page on back. - for p1, p2 in zip(pages, pages[1:]): - if p1[1] is p2[1]: - pages.remove(p1) +def fixpage(*pages): + result = PageMerge() + (x for x in pages if x is not None) + result[-1].x += result[0].w + return result.render() - return IndirectPdfDict( - Type = PdfName.Page, - Contents = PdfDict(stream=''.join(page.stream for page in pages)), - MediaBox = PdfArray([0, 0, x, y]), - Resources = PdfDict( - XObject = PdfDict(pages), - ), - ) inpfn, = sys.argv[1:] outfn = 'booklet.' + os.path.basename(inpfn) -pages = PdfReader(inpfn).pages +ipages = PdfReader(inpfn).pages -# Use page1 as a marker to print a blank at the end -if len(pages) & 1: - pages.append(pages[0]) +# Make sure we have an even number +if len(ipages) & 1: + ipages.append(None) -bigpages = [] -while len(pages) > 2: - bigpages.append(fixpage(pages.pop(), pages.pop(0))) - bigpages.append(fixpage(pages.pop(0), pages.pop())) +opages = [] +while len(ipages) > 2: + opages.append(fixpage(ipages.pop(), ipages.pop(0))) + opages.append(fixpage(ipages.pop(0), ipages.pop())) -bigpages += pages +opages += ipages -PdfWriter().addpages(bigpages).write(outfn) +PdfWriter().addpages(opages).write(outfn) diff --git a/examples/cat.py b/examples/cat.py new file mode 100755 index 0000000..86cf643 --- /dev/null +++ b/examples/cat.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +''' +usage: cat.py [ ...] + +Creates cat. + +This file demonstrates two features: + +1) Concatenating multiple input PDFs. + +2) adding metadata to the PDF. + +''' + +import sys +import os + +from pdfrw import PdfReader, PdfWriter, IndirectPdfDict + +inputs = sys.argv[1:] +assert inputs +outfn = 'cat.' + os.path.basename(inputs[0]) + +writer = PdfWriter() +for inpfn in inputs: + writer.addpages(PdfReader(inpfn).pages) + +writer.trailer.Info = IndirectPdfDict( + Title='your title goes here', + Author='your name goes here', + Subject='what is it all about?', + Creator='some script goes here', +) +writer.write(outfn) diff --git a/examples/extract.py b/examples/extract.py new file mode 100755 index 0000000..3756b4f --- /dev/null +++ b/examples/extract.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +''' +usage: extract.py + +Locates Form XObjects and Image XObjects within the PDF, +and creates a new PDF containing these -- one per page. + +Resulting file will be named extract. + +''' + +import sys +import os + +from pdfrw import PdfReader, PdfWriter +from pdfrw.findobjs import page_per_xobj + + +inpfn, = sys.argv[1:] +outfn = 'extract.' + os.path.basename(inpfn) +pages = list(page_per_xobj(PdfReader(inpfn).pages, margin=0.5*72)) +if not pages: + raise IndexError("No XObjects found") +writer = PdfWriter() +writer.addpages(pages) +writer.write(outfn) diff --git a/examples/find_pdfrw.py b/examples/find_pdfrw.py deleted file mode 100644 index f69d412..0000000 --- a/examples/find_pdfrw.py +++ /dev/null @@ -1,33 +0,0 @@ -''' - find_xxx.py -- Find the place in the tree where xxx lives. - - Ways to use: - 1) Make a copy, change 'xxx' in package to be your name; or - 2) Under Linux, just ln -s to where this is in the right tree - - Created by Pat Maupin, who doesn't consider it big enough to be worth copyrighting -''' - -import sys -import os - -myname = __name__[5:] # remove 'find_' -myname = os.path.join(myname, '__init__.py') - -def trypath(newpath): - path = None - while path != newpath: - path = newpath - if os.path.exists(os.path.join(path, myname)): - return path - newpath = os.path.dirname(path) - -root = trypath(__file__) or trypath(os.path.realpath(__file__)) - -if root is None: - print - print 'Warning: %s: Could not find path to development package %s' % (__file__, myname) - print ' The import will either fail or will use system-installed libraries' - print -elif root not in sys.path: - sys.path.append(root) diff --git a/examples/metadata.py b/examples/metadata.py deleted file mode 100755 index 9c69108..0000000 --- a/examples/metadata.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python - -''' -usage: metadata.py [ ...] - -Creates output.pdf - -This file demonstrates two features: - -1) Concatenating multiple input PDFs. - -2) adding metadata to the PDF. - -If you do not need to add metadata, look at subset.py, which -has a simpler interface to PdfWriter. - -''' - -import sys -import os - -import find_pdfrw -from pdfrw import PdfReader, PdfWriter, IndirectPdfDict - -inputs = sys.argv[1:] -assert inputs -outfn = 'output.pdf' - -writer = PdfWriter() -for inpfn in inputs: - writer.addpages(PdfReader(inpfn.pages) - -writer.trailer.Info = IndirectPdfDict( - Title = 'your title goes here', - Author = 'your name goes here', - Subject = 'what is it all about?', - Creator = 'some script goes here', -) -writer.write(outfn) diff --git a/examples/poster.py b/examples/poster.py index ee58282..7f1c1c2 100755 --- a/examples/poster.py +++ b/examples/poster.py @@ -7,51 +7,37 @@ Shows how to change the size on a PDF. Motivation: -My daughter needed to create a 48" x 36" poster, but her Mac version of Powerpoint -only wanted to output 8.5" x 11" for some reason. +My daughter needed to create a 48" x 36" poster, but her Mac +version of Powerpoint only wanted to output 8.5" x 11" for +some reason. + +So she did an 8.5x11" output with 0.5" margin all around +(actual size of useful area 7.5x10") and we scaled it +up by 4.8. + +We also copy the Info dict to the new PDF. ''' import sys import os -import find_pdfrw -from pdfrw import PdfReader, PdfWriter, PdfDict, PdfName, PdfArray, IndirectPdfDict -from pdfrw.buildxobj import pagexobj - -def adjust(page): - page = pagexobj(page) - assert page.BBox == [0, 0, 11 * 72, int(8.5 * 72)], page.BBox - margin = 72 // 2 - old_x, old_y = page.BBox[2] - 2 * margin, page.BBox[3] - 2 * margin - - new_x, new_y = 48 * 72, 36 * 72 - ratio = 1.0 * new_x / old_x - assert ratio == 1.0 * new_y / old_y - - index = '/BasePage' - x = -margin * ratio - y = -margin * ratio - stream = 'q %0.2f 0 0 %0.2f %s %s cm %s Do Q\n' % (ratio, ratio, x, y, index) - xobjdict = PdfDict() - xobjdict[index] = page - - return PdfDict( - Type = PdfName.Page, - Contents = PdfDict(stream=stream), - MediaBox = PdfArray([0, 0, new_x, new_y]), - Resources = PdfDict(XObject = xobjdict), - ) - -def go(inpfn, outfn): - reader = PdfReader(inpfn) - page, = reader.pages - writer = PdfWriter() - writer.addpage(adjust(page)) - writer.trailer.Info = IndirectPdfDict(reader.Info) - writer.write(outfn) - -if __name__ == '__main__': - inpfn, = sys.argv[1:] - outfn = 'poster.' + os.path.basename(inpfn) - go(inpfn, outfn) +from pdfrw import PdfReader, PdfWriter, PageMerge, IndirectPdfDict + + +def adjust(page, margin=36, scale=4.8): + info = PageMerge().add(page) + x1, y1, x2, y2 = info.xobj_box + viewrect = (margin, margin, x2 - x1 - 2 * margin, y2 - y1 - 2 * margin) + page = PageMerge().add(page, viewrect=viewrect) + page[0].scale(scale) + return page.render() + + +inpfn, = sys.argv[1:] +outfn = 'poster.' + os.path.basename(inpfn) +reader = PdfReader(inpfn) +writer = PdfWriter() +writer.addpage(adjust(reader.pages[0])) +writer.trailer.Info = IndirectPdfDict(reader.Info or {}) +writer.write(outfn) diff --git a/examples/print_two.py b/examples/print_two.py index d168f68..c54eaee 100755 --- a/examples/print_two.py +++ b/examples/print_two.py @@ -7,52 +7,26 @@ Creates print_two.my.pdf This is only useful when you can cut down sheets of paper to make two small documents. Works for double-sided only right now. - ''' import sys import os -import find_pdfrw -from pdfrw import PdfReader, PdfWriter, PdfArray, IndirectPdfDict +from pdfrw import PdfReader, PdfWriter, PageMerge + def fixpage(page, count=[0]): count[0] += 1 - evenpage = not (count[0] & 1) - - # For demo purposes, just go with the MediaBox and toast the others - box = [float(x) for x in page.MediaBox] - assert box[0] == box[1] == 0, "demo won't work on this PDF" - - for key, value in sorted(page.iteritems()): - if 'box' in key.lower(): - del page[key] - - startsize = tuple(box[2:]) - finalsize = box[3], 2 * box[2] - page.MediaBox = PdfArray((0, 0) + finalsize) - page.Rotate = (int(page.Rotate or 0) + 90) % 360 - - contents = page.Contents - if contents is None: - return page - contents = isinstance(contents, dict) and [contents] or contents - - prefix = '0 1 -1 0 %s %s cm\n' % (finalsize[0], 0) - if evenpage: - prefix = '1 0 0 1 %s %s cm\n' % (0, finalsize[1]/2) + prefix - first_prefix = 'q\n-1 0 0 -1 %s %s cm\n' % finalsize + prefix - second_prefix = '\nQ\n' + prefix - first_prefix = IndirectPdfDict(stream=first_prefix) - second_prefix = IndirectPdfDict(stream=second_prefix) - contents = PdfArray(([second_prefix] + contents) * 2) - contents[0] = first_prefix - page.Contents = contents - return page + oddpage = (count[0] & 1) + + result = PageMerge() + for rotation in (180 + 180 * oddpage, 180 * oddpage): + result.add(page, rotate=rotation) + result[1].x = result[0].w + return result.render() inpfn, = sys.argv[1:] outfn = 'print_two.' + os.path.basename(inpfn) pages = PdfReader(inpfn).pages - PdfWriter().addpages(fixpage(x) for x in pages).write(outfn) diff --git a/examples/rl1/4up.py b/examples/rl1/4up.py index 385103a..49f766e 100755 --- a/examples/rl1/4up.py +++ b/examples/rl1/4up.py @@ -15,7 +15,6 @@ import os from reportlab.pdfgen.canvas import Canvas -import find_pdfrw from pdfrw import PdfReader from pdfrw.buildxobj import pagexobj from pdfrw.toreportlab import makerl diff --git a/examples/rl1/booklet.py b/examples/rl1/booklet.py index 23f8a72..e7764a0 100755 --- a/examples/rl1/booklet.py +++ b/examples/rl1/booklet.py @@ -15,7 +15,6 @@ import os from reportlab.pdfgen.canvas import Canvas -import find_pdfrw from pdfrw import PdfReader from pdfrw.buildxobj import pagexobj from pdfrw.toreportlab import makerl @@ -43,7 +42,7 @@ def make_pdf(outfn, xobjpairs): x += xobj.BBox[2] y = max(y, xobj.BBox[3]) - canvas.setPageSize((x,y)) + canvas.setPageSize((x, y)) # Handle blank back page if len(xobjlist) > 1 and xobjlist[0] == xobjlist[-1]: diff --git a/examples/rl1/find_pdfrw.py b/examples/rl1/find_pdfrw.py deleted file mode 100644 index f69d412..0000000 --- a/examples/rl1/find_pdfrw.py +++ /dev/null @@ -1,33 +0,0 @@ -''' - find_xxx.py -- Find the place in the tree where xxx lives. - - Ways to use: - 1) Make a copy, change 'xxx' in package to be your name; or - 2) Under Linux, just ln -s to where this is in the right tree - - Created by Pat Maupin, who doesn't consider it big enough to be worth copyrighting -''' - -import sys -import os - -myname = __name__[5:] # remove 'find_' -myname = os.path.join(myname, '__init__.py') - -def trypath(newpath): - path = None - while path != newpath: - path = newpath - if os.path.exists(os.path.join(path, myname)): - return path - newpath = os.path.dirname(path) - -root = trypath(__file__) or trypath(os.path.realpath(__file__)) - -if root is None: - print - print 'Warning: %s: Could not find path to development package %s' % (__file__, myname) - print ' The import will either fail or will use system-installed libraries' - print -elif root not in sys.path: - sys.path.append(root) diff --git a/examples/rl1/platypus_pdf_template.py b/examples/rl1/platypus_pdf_template.py index 8c85794..7e4769a 100755 --- a/examples/rl1/platypus_pdf_template.py +++ b/examples/rl1/platypus_pdf_template.py @@ -1,17 +1,18 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ -usage: platypus_pdf_template.py output.pdf pdf_file_to_use_as_template.pdf +usage: platypus_pdf_template.py source.pdf -Example of using pdfrw to use a pdf (page one) as the background for all -other pages together with platypus. +Creates platypus.source.pdf -There is a table of contents in this example for completeness sake. +Example of using pdfrw to use page 1 of a source PDF as the background +for other pages programmatically generated with Platypus. Contributed by user asannes """ import sys +import os from reportlab.platypus import PageTemplate, BaseDocTemplate, Frame from reportlab.platypus import NextPageTemplate, Paragraph, PageBreak @@ -21,7 +22,6 @@ from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from reportlab.graphics import renderPDF -import find_pdfrw from pdfrw import PdfReader from pdfrw.buildxobj import pagexobj from pdfrw.toreportlab import makerl @@ -29,6 +29,7 @@ from pdfrw.toreportlab import makerl PAGE_WIDTH = defaultPageSize[0] PAGE_HEIGHT = defaultPageSize[1] + class MyTemplate(PageTemplate): """The kernel of this example, where we use pdfrw to fill in the background of a page before writing to it. This could be used to fill @@ -57,6 +58,7 @@ class MyTemplate(PageTemplate): canvas.doForm(rl_obj) canvas.restoreState() + class MyDocTemplate(BaseDocTemplate): """Used to apply heading to table of contents.""" @@ -70,20 +72,22 @@ class MyDocTemplate(BaseDocTemplate): self.canv.bookmarkPage(key) self.notify('TOCEntry', [1, text, self.page, key]) + def create_toc(): """Creates the table of contents""" table_of_contents = TableOfContents() table_of_contents.dotsMinLevel = 0 - header1 = ParagraphStyle(name = 'Heading1', fontSize = 16, leading = 16) - header2 = ParagraphStyle(name = 'Heading2', fontSize = 14, leading = 14) + header1 = ParagraphStyle(name='Heading1', fontSize=16, leading=16) + header2 = ParagraphStyle(name='Heading2', fontSize=14, leading=14) table_of_contents.levelStyles = [header1, header2] return [table_of_contents, PageBreak()] + def create_pdf(filename, pdf_template_filename): """Create the pdf, with all the contents""" - pdf_report = open(filename, "w") + pdf_report = open(filename, "wb") document = MyDocTemplate(pdf_report) - templates = [ MyTemplate(pdf_template_filename, name='background') ] + templates = [MyTemplate(pdf_template_filename, name='background')] document.addPageTemplates(templates) styles = getSampleStyleSheet() @@ -99,8 +103,6 @@ def create_pdf(filename, pdf_template_filename): if __name__ == '__main__': - try: - output, template = sys.argv[1:] - create_pdf(output, template) - except ValueError: - print "Usage: %s