Git Product home page Git Product logo

pdfrw's Introduction

pdfrw 0.4

Author: Patrick Maupin

1   Introduction

pdfrw is a Python library and utility that reads and writes PDF files:

  • Version 0.4 is tested and works on Python 2.6, 2.7, 3.3, 3.4, 3.5, and 3.6
  • 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

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.

2   Examples

The library comes with several examples that show operation both with and without reportlab.

2.1   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 Another watermarking example, using reportlab canvas and generated output for the document. Contributed by user asannes.
  • rl2 Experimental code for parsing graphics. Needs work.
  • subset_booklets.py shows an example of creating a full printable pdf version in a more professional and pratical way ( take a look at http://www.wikihow.com/Bind-a-Book )

2.2   Notes on selected examples

2.2.1   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.

2.2.2   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.

The alter.py example alters a single metadata item in a PDF, and writes the result to a new PDF.

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.

2.2.3   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.

But, every other page is flipped, so that you can print double-sided and the pages will line up properly and be pre-collated.

2.2.4   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.

3   pdfrw philosophy

3.1   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.

3.2   Examples

The philosophy of the examples is to provide small, easily-understood examples that showcase pdfrw functionality.

4   PDF files and Python

4.1   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)

4.2   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.

4.3   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.

4.3.1   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)

4.3.2   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.

4.3.3   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.

4.3.4   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.

5   Library internals

5.1   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.

5.2   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.

5.2.1   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.

5.2.2   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.

5.2.3   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.

5.2.4   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.

5.2.5   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.

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

5.2.6   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.

5.3   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.

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.

5.4   File output

pdfwriter.py contains the PdfWriter class, which can create and output a PDF file.

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.

5.5   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.

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.

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.

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.

5.6   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.

py23_diffs.py contains code to help manage the differences between Python 2 and Python 3.

6   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 tests directory using unittest, or py.test, or nose.
  • travisci is used at github, and runs the tests with py.test

To run a single test-case:

7   Other libraries

7.1   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."

7.2   non-pure-Python libraries

  • pyPoppler can read PDF files.
  • pycairo can write PDF files.
  • PyMuPDF high performance rendering of PDF, (Open)XPS, CBZ and EPUB

7.3   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.
  • MuPDF is a free top performance PDF, (Open)XPS, CBZ and EPUB rendering library that also comes with some command line tools. One of those, mutool, has big overlaps with pdftk's - except it is up to 10 times faster.

8   Release information

Revisions:

0.4 -- Released 18 September, 2017

  • Python 3.6 added to test matrix
  • Proper unicode support for text strings in PDFs added
  • buildxobj fixes allow better support creating form XObjects out of compressed pages in some cases
  • Compression fixes for Python 3+
  • New subset_booklets.py example
  • Bug with non-compressed indices into compressed object streams fixed
  • Bug with distinguishing compressed object stream first objects fixed
  • Better error reporting added for some invalid PDFs (e.g. when reading past the end of file)
  • Better scrubbing of old bookmark information when writing PDFs, to remove dangling references
  • Refactoring of pdfwriter, including updating API, to allow future enhancements for things like incremental writing
  • Minor tokenizer speedup
  • Some flate decompressor bugs fixed
  • Compression and decompression tests added
  • Tests for new unicode handling added
  • PdfReader.readpages() recursion error (issue #92) fixed.
  • Initial crypt filter support added

0.3 -- Released 19 October, 2016.

  • Python 3.5 added to test matrix
  • Better support under Python 3.x for in-memory PDF file-like objects
  • Some pagemerge and Unicode patches added
  • Changes to logging allow better coexistence with other packages
  • Fix for "from pdfrw import *"
  • New fancy_watermark.py example shows off capabilities of pagemerge.py
  • metadata.py example renamed to cat.py

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

pdfrw's People

Contributors

abrasive avatar aquavitae avatar b4stien avatar edwardbetts avatar jondel avatar jonls avatar jorjmckie avatar lambdafu avatar mazulo avatar metalshark avatar ndevenish avatar pmaupin avatar takluyver avatar tjwei avatar wuhaochen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdfrw's Issues

Xobjects with compression parameters not supported

Was getting this when trying to merge this pdf:
http://demo.visualid.com/_mediafiles/demo/_tmp/3GoeKXdVeEk7.pdf
Int this pdf:
https://s3-eu-west-1.amazonaws.com/visualid-mediafiles/demo/20170131/AC1E00B70333d13AF9qXE39A3E9A/9sd9DGiaS4X4.pdf

FlateDecode needs to decompress and recompress
Here is thd dict of parameters in the pdf...
[{'/Length': '3134', '/Filter': '/FlateDecode'}, {'/Length':
'3172',
'/Filter': '/FlateDecode'}, {'/Length': '3597', '/Filter':
'/FlateDecode'},
{'/Length': '3580', '/Filter': '/FlateDecode'}, {'/Length': '3044',
'/Filter': '/FlateDecode'}, {'/Length': '3393', '/Filter':
'/FlateDecode'},
{'/Length': '3347', '/Filter': '/FlateDecode'}, {'/Length': '3223',
'/Filter': '/FlateDecode'}]

Code fix by @pmaupin to come

Problem with "/Contents" in some pdf's

Some pdf's in /Contents have array with one object instead of object directly. 

Eg. /Contents [ 5 0 R ] instead of /Contents 5 0 R.

To fix this problem, I changed buildxobj.py pagexobj method in line 190 to:

    if isinstance(page.Contents, PdfArray):
        contents = page.Contents[0]
    else:
        contents = page.Contents

Original issue reported on code.google.com by [email protected] on 18 Oct 2012 at 10:12

how to set unicode info?

I mean use non-english chanracters, for example
writer.trailer.Info = IndirectPdfDict(
Title=u'unicode string1',
Author=u'unicode string2',
)

thanks

Any chance at memory optimizations?

Hello there,

I'm wondering if there are any plans or perhaps some hints on reducing the amount of memory (and perhaps speeding things up) required.

Quickly looking through the code there are way too many strings being used/loaded, split, concatenated, etc... Much of this can probably be improved through bytearray or memoryview to avoid excesive string copying.

How to navigate through the tree to see the PDF text content.

I am trying to navigate through the tree created by PdfReader and looking for the var that stores the text of PDF.

>>> x.pages[1].Resources
{'/Font': {'/T1_2': (14, 0), '/T1_3': (16, 0), '/T1_0': (146, 0), '/T1_1': (148, 0)}, '/ProcSet': ['/PDF', '/Text']}
>>> x.pages[1].Resources.ProcSet
['/PDF', '/Text'] 

Not sure if this is the correct way of doing it.

'int' object is not callable

attempting to run the following line of code:
pages[0].MediaBox[2:]

would result in something like:

Traceback (most recent call last):
  File "/tp/new_backend/teampatent/test/test_pdfwrap.py", line 233, in test_pdfwrap_page_sizes
    eq_([420, 595], [int(n) for n in pages[0].MediaBox[2:]])
  File "build/bdist.linux-i686/egg/pdfrw/objects/pdfarray.py", line 39, in __getslice__
    return listget(self, index)
TypeError: 'int' object is not callable

this used to work before 0.1 release


Original issue reported on code.google.com by [email protected] on 5 Mar 2013 at 1:21

Additional support needed

- More compression types
- Linearized PDFs
- Maybe more PyPDF emulation (additional dict attributes, mainly)

Original issue reported on code.google.com by pmaupin on 4 Sep 2012 at 2:09

decryption

I did read the documentation that indicates that it isn't supported. I am using pypdf2 and it does but only a few and the newer encryptions used by some government agencies, 128 AES, is not supported.

Any ideas or thoughts if this is something that you will be implementing in the future? If so do you have any timeframe in mind?

Thanks

[Feature Request] Ability to add/remove bookmarks

If this feature already exists, I'd love to know about it. If it doesn't, I'd like to put in a formal request for it. I know where the information exists (Root.Outlines), but I don't know how to modify it.

[Question] Page rescaling?

Is there any way to rescale a single page, such as the PyPDF2 library Page.scaleTo(width, height) ?

There seems to be some examples like this:

for page in output.pages:
    try:
        p = PageMerge().add(page)
        p[0].scale(0.1)
        p.render()
    except Exception as e:
        print e

which are a bit unclear, and also doesn't seem to work when iterating an opened file pages, plus some pages raise an error ( 'TypeError: 'NoneType' object has no attribute 'getitem'').
The correct way would be using the above code but add the pages to a new writer, but that would mean losing any bookmarks from the original file which is really bad.

One would expect a resize option like the one already possible for rotations, like this (don't mind the added watermark code):

for page in output.pages:
    page.Rotate = 90
    PageMerge(page).add(watermark, prepend=True).render()

Potential Parsing Error for some PDFs

What steps will reproduce the problem?
1. Using the code from the watermark.py as a sample, I attempted to Overlay the 
attached PDF Document into another PDF Document.

Minimal code reproduction example:

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from pdfrw import PdfReader
>>> from pdfrw.buildxobj import pagexobj
>>>
>>> xobj = pagexobj(PdfReader('boverlay-new.pdf').getPage(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python27\lib\site-packages\pdfrw\buildxobj.py", line 193, in pagexobj
    assert int(contents.Length) == len(contents.stream)
AttributeError: 'PdfArray' object has no attribute 'Length'

The Overlay file will open in PDF Readers (Foxit, Adobe), but pdfrw is unable 
to create a page object from the first page of the PDF.  The Overlay PDF was 
created using Adobe Indesign, and is attached.


What is the expected output? What do you see instead?
No overlay is produced, and the exception above is generated instead.


What version of the product are you using? On what operating system?
I have the latest pdfrw as retrieved from via SVN.  Windows 7, 64bit, using 
Python 2.7.3 32bit.


Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 4 Nov 2013 at 5:23

Attachments:

Code review request

Purpose of code changes on this branch:

Allow reading imperfect or just plain broken PDFs:
1. no newline after %%EOF (allowed in PDF format)
2. support single filter when specified in an array ie /Filter[/FlateDecode] 
instead of /Filter 
/FlateDecode
3. when "endstream" is not found at specified stream length, try to find it 
again using simple 
string search from start.

When reviewing my code changes, please focus on:

Make sure it does not affect handling correct PDFs.

After the review, I'll merge this branch into:
/trunk


Original issue reported on code.google.com by [email protected] on 12 Mar 2010 at 6:25

Problems using table of contents (rl) with pdfrw

I'm not sure this is actually a bug in pdfrw makerl or not, but when I try
to use table of contents together with a template with a pdfrw object in
it, it fails with:

  File "/usr/lib64/python2.6/site-packages/reportlab/pdfbase/pdfdoc.py",
line 852, in format
    raise KeyError, "forward reference to %s not resolved upon final
formatting" % repr(self.name)
KeyError: "forward reference to 'FormXob.pdfrw_3' not resolved upon final
formatting"

I have attached a small test application that draws background.pdf before
anything else and outputs output.pdf.

Original issue reported on code.google.com by [email protected] on 13 Jan 2010 at 10:26

Attachments:

watermark.py example uses -o directory incorrectly (overwrite input files)

What steps will reproduce the problem?
1. using watermark.py with -d and -o where a path is specified with -d
Watermarked files overwrite the input files

What is the expected output? What do you see instead?
watermarked files in directory specified by -o

What version of the product are you using? On what operating system?
0.1 downloaded 18-Jan-2014 as .zip file; on Windows 7 (irrelevant)

Please provide any additional information below.
Line 67
  PdfWriter().write(path.join(outdir, fname), trailer)
should be changed to
  PdfWriter().write(path.join(outdir, os.path.basename(fname)), trailer)

Original issue reported on code.google.com by [email protected] on 18 Jan 2014 at 9:45

Why merge pdf is flipped with example..

use example fancy_watemark.py or watermark.py go to run it.

But the resulting watermark are all horizontal and vertical flip.

watermark with reportlab generate.for example

c = canvas.Canvas('transafe.pdf')
c.drawString(0,0,'hello') 
c.save()

Thanks in advance
Please tell me how to change it ..

Reading a pdf from file like object or data not working in python 3 with bytesIO

I have noticed that it is possible to make a PdfReader either by specifying a filename or file-like object, or by giving the data directly with fdata argument. This is great, however, it doesn't work if I give it a BytesIO object since the various functions in the following code only work with strings. For example, fdata.startswith('%PDF-') is called rather than fdata.startswith(b'%PDF-').

I can't immediately see an elegant way to solve this. Directly converting the data with str() produces assertion errors such as 'File "/usr/lib/python3.4/site-packages/pdfrw/pdfreader.py", line 319, in findxref assert tok == 'startxref' # (We just checked this...)' with the files I have tried.

Spurious brackets in URIs.


1. Get a PDF with a URI in an annotation.
2. Run this code on it:

#!/usr/bin/env python

import sys
import os

from pdfrw import PdfReader, PdfWriter

def convert(inpfn, outfn):

  pdf = PdfReader(inpfn)

  for K in pdf.Root.Pages.Kids:
    if K.Annots is not None:
      for An in K.Annots:
        if An.A is not None:
          if An.A.URI is not None:
            An.A.URI = An.A.URI

  outdata = PdfWriter()

  outdata.trailer = pdf

  outdata.write(outfn)

for inpfn in sys.argv[1:]:
    print inpfn, ':'
    outfn = 'out/' + inpfn
    convert(inpfn, outfn)


Expected output: the output PDF should be identical to the input.

Actual result: In the output PDF the URI will have extra brackets added around 
it, ie instead of

http://www.example.com

the URI now points to:

(http://www.example.com)

which fails to open correctly in any PDF reader.


Using version 0.1-1 on Ubuntu 14.04.


Original issue reported on code.google.com by [email protected] on 21 Oct 2014 at 4:16

barcode

thanks for your job.
Can I use barcodes with pdfrw?
Need another library, or should I import the image barcode into the document?

code.google.com usage

Service code.google.com is closing. Do you have plans to migrate pdfrw to 
somewhere?

Original issue reported on code.google.com by [email protected] on 17 Mar 2015 at 10:31

crashes in makerl

What steps will reproduce the problem?
1. Go to example/rl1/
2. run subset.py test.pdf 1 1
3.

What is the expected output? What do you see instead?
I expect it to run, instead I get an error:

~/svn/pdfrw/examples/rl1$ python subset.py side1.pdf 1 1
Traceback (most recent call last):
  File "subset.py", line 43, in <module>
    go(inpfn, firstpage, lastpage)
  File "subset.py", line 36, in go
    canvas.doForm(makerl(canvas, page))
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 138, in makerl
    rlobj = makerl_recurse(doc, pdfobj)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 131, in makerl_recurse
    return func(rldoc, pdfobj)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 94, in _makestream
    rldict[key[1:]] = makerl_recurse(rldoc, value)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 131, in makerl_recurse
    return func(rldoc, pdfobj)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 72, in _makedict
    rldict[key[1:]] = makerl_recurse(rldoc, value)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 131, in makerl_recurse
    return func(rldoc, pdfobj)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 72, in _makedict
    rldict[key[1:]] = makerl_recurse(rldoc, value)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 131, in makerl_recurse
    return func(rldoc, pdfobj)
  File "~/svn/pdfrw/pdfrw/toreportlab.py", line 108, in _makearray
    mylist = rlobj.sequence
AttributeError: PDFObjectReference instance has no attribute 'sequence'

What version of the product are you using? On what operating system?
Subversion revision 82
On Linux.

Please provide any additional information below.
Don't know if this helps, but if I place a try/except around the sequence
usage like so:
    try:
        mylist = rlobj.sequence
        for value in pdfobj:   
            mylist.append(makerl_recurse(rldoc, value))
        print dir(rlobj)
    except:
        print dir(rlobj)

    return rlobj

I get the following output:
['__PDFObject__', '__doc__', '__init__', '__module__', 'format', 'name']
['__PDFObject__', '__doc__', '__init__', '__module__', 'format', 'name']
['__PDFObject__', '__doc__', '__init__', '__module__', 'format', 'name']
['References', '__PDFObject__', '__doc__', '__init__', '__module__',
'format', 'multiline', 'sequence']
['References', '__PDFObject__', '__doc__', '__init__', '__module__',
'format', 'multiline', 'sequence']
['References', '__PDFObject__', '__doc__', '__init__', '__module__',
'format', 'multiline', 'sequence']
['References', '__PDFObject__', '__doc__', '__init__', '__module__',
'format', 'multiline', 'sequence']

Ah, and it works.. (output file seems correct anyways) :)

Original issue reported on code.google.com by [email protected] on 12 Jan 2010 at 11:20

Add tests to the release tarball

Could you please add the tests to your next release tarball? while the git repo is of course better for developement, having tests in the tarball is useful to check that the installation is working, expecially in the context of packaging (I'm in the process of adopting the packaging of pdfrw for debian).

Thanks in advance.

Updating field's default value doesn't update rendered text

I have form fields in my PDF (that make it interactive - you can fill them and print with your data). I want to programatically fill those fields based on their names (template.Root.Pages.Kids[x].Annots[y] - name in 'T', default value in 'V'). The problem is that when I do so it's updated in metadata, but the old value is displayed until I edit the PDF in some desktop editor (I can see new default value and it starts to be displayed when I make any change to this field). I'd love it to be updated as well.

Example:

template = pdfrw.PdfReader('template.pdf')
template.Root.Pages.Kids[0].Annots[3].update(pdfrw.PdfDict(V='(test)'))
pdfrw.PdfWriter().write('test.pdf', template)

How to remove object from pdf

I'm sorry for posting something which is not directly an issue (and I'll be glad to push a PR for the docs with the answer !).

I try to remove some objects (mostly images) from an existing pdf, i can find them with pdfrw. findobjs.find_objects(), but I have no clue how to remove them from "the tree"... Can you provide any kind of guidance (or place to look for more resources?).

Many thanks,

Opening document with PdfReader fails of a flattened PDF document.

I have a PDF document with an Acroform in it. After filling in values and flattening the document, I tried to open the document again with the PdfReader, but this fails. It gives me the following stacktrace.

Error stacktrace:

../../.virtualenvs/pdftools35/lib/python3.5/site-packages/pdfrw/pdfreader.py:546: in __init__
    trailer, is_stream = self.parsexref(source)
../../.virtualenvs/pdftools35/lib/python3.5/site-packages/pdfrw/pdfreader.py:439: in parsexref
    return self.parse_xref_stream(source), True
../../.virtualenvs/pdftools35/lib/python3.5/site-packages/pdfrw/pdfreader.py:372: in parse_xref_stream
    xtype, p1, p2 = islice(get, 3)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

s = '\x00\x00\x00\x00ÿÿ\x01\x00\x00\x12\x00\x00\x01\x00\x02\x02\x00\x00\x01\x00\x12[\x00\x00\x01\x00\x13\x94\x00\x00\x01\x...12\x00\x00\x01\x01ãc\x00\x00\x01\x01ãÜ\x00\x00\x01\x01ä-\x00\x00\x01\x01ä¦\x00\x00\x01\x01ä÷\x00\x00\x01\x01åq\x00\x00'
lengths = <itertools.cycle object at 0x120fb4e08>

    def readint(s, lengths):
        lengths = itertools.cycle(lengths)
        offset = 0
        for length in itertools.cycle(lengths):
            next = offset + length
            # if isinstance(s, str):
            #    s = bytes(s, 'latin-1')
    
>           yield int(hexlify(s[offset:next]), 16) if length else None
E           TypeError: a bytes-like object is required, not 'str'

../../.virtualenvs/pdftools35/lib/python3.5/site-packages/pdfrw/pdfreader.py:342: TypeError

I am using Python 3.5.1.

My test code:

import pdfrw

with open('document_after_flattening.pdf', 'rb') as f:
    fdata = f.read().decode('latin-1')
    pdfrw.PdfReader(fdata=fdata)

I have traced the error back to :

        def readint(s, lengths):
            lengths = itertools.cycle(lengths)
            offset = 0
            for length in itertools.cycle(lengths):
                next = offset + length
                yield int(hexlify(s[offset:next]), 16) if length else None
                offset = next
hexlify(s[offset:next])

I replaced the code above with:

        def readint(s, lengths):
            lengths = itertools.cycle(lengths)
            offset = 0
            for length in itertools.cycle(lengths):
                next = offset + length


                if isinstance(s, str):
                   s = bytes(s, 'latin-1')


                yield int(hexlify(s[offset:next]), 16) if length else None
                offset = next

It appears that the stream is a string and the function didn't expect this and that's the reason why it crashes.

The document
document_before_flattening.pdf

document_after_flattening.pdf

Another release?

I would like to use pdfrw for a project, but it involves in-memory PDFs and runs on Python 3.x, so I'm stuck using a git+ssh:// URL to install it, which is somewhat problematic. Any chance of a new release including #43 / 9e4aa55 getting pushed to pypi?

Direct page objects in /Kids

In examples where XObjects are used, after adding new pages, somehow they are 
written in /Kids array as direct objects. According to specification, they must 
be indirect. Although pdf readers open such documents just fine, some tools are 
complaining about that. The solutions can be:

1) in examples (e.g. 4up.py function get4) change returning type from PdfDict 
to IndirectPdfDict.

2) changing type to indirect in writer. For example, in _get_trailer:

        # Make all the pages point back to the page dictionary
        pagedict = trailer.Root.Pages
        for page in pagedict.Kids:
            page.Parent = pagedict
            page.indirect = True  <-- add this line

I think the second approach is more cleaner.

Original issue reported on code.google.com by [email protected] on 17 Nov 2012 at 3:56

Question : how to remove some elements in a pdf file ?

I'm trying to make a script to remove some images from a pdf file based on their dimension.

Iterating over pages,

  • if I use findobjs.find_objects(page, valid_subtypes=(PdfName.Image,)), it finds Image objects and I can check width and height properties. But then the link with the parent (the page) is lost so I'm not able to remove this element from the page.
  • if I use find_objects on each content of the page (page.Contents), so I can keep the link with the page, it is not able to find any Image object.

I've tried to understand find_objects function to mock the behavior in a custom function. But there is some magic around obj.iteritems() that I don't get.

Do you have any idea on how to proceed ?

Question: How to blacken text / Replace text / Remove text ?

Thanks for making this lib!
And sorry for the Question, this is not an issue.

I have an existing PDF with a specific word I want to hide out.
I am happy with any solution on how to hide it (Write on top of it, cut it out, replace it etc..).
I am not so much familier with the PDF format so not sure how to go about that, any suggestion?

Happy to contribute back a working example when I get this to work :)

errors decoding pdf files

I'm developing a Python's application using pdfrw and all seems ok, but i 
discovered that when i run my application with optimizations activated (python 
-OO) pdfrw can't decode any pdf and raises Exceptions.

By a quickly inspection of pdfrw's source code i found in pdfreader.py rows as 
these:
  assert source.next() == 'R'
  assert source.next() == '<<'
  assert source.next() == 'startxref' and source.floc > startloc

calling .next() in an assert will change the program working flow if 
optimizations are on or off.

Giuseppe

Original issue reported on code.google.com by [email protected] on 14 Sep 2012 at 7:48

PDFString values containing 2 backslashes are incorrectly decoded

What steps will reproduce the problem?
1. Call pdfrw.pdfobjects.PdfString.encode on a string containing a double 
backslash.
2. Call .decode() on the pdfstring.

What is the expected output? What do you see instead?
Encoding and then decoding a string, should return the original.

What version of the product are you using? On what operating system?
Latest SVN (revision 136).

Please provide any additional information below.
Patch attached (including a unittest).

Original issue reported on code.google.com by beechhorn on 13 Sep 2011 at 4:28

Attachments:

add to pypi

it would be good if pdfrw could be installed with easy_install or pip


the following simple setup.py works for me:

#!/usr/bin/env python

from setuptools import setup

setup(
    name = "pdfrw",
    version = "0.1",

    packages = ["pdfrw"]
)

Original issue reported on code.google.com by [email protected] on 17 Sep 2012 at 11:38

Bug: Can't rewatermark file

Hi,

Just discovered a small bug:

code to reproduce:

from reportlab.pdfgen import canvas
from pdfrw import PdfReader, PdfWriter, PageMerge


# create some files
pdf_file = canvas.Canvas('page.pdf')
pdf_file.drawString(0, 0, 'hello')
pdf_file.save()

watermark_file = canvas.Canvas('water.pdf')
watermark_file.drawString(0, 0, 'water')
watermark_file.save()


# watermark 1
wmark = PageMerge().add(PdfReader('water.pdf').pages[0])[0]
trailer = PdfReader('page.pdf')

for page in trailer.pages:
    PageMerge(page).add(wmark).render()

PdfWriter().write('merged.pdf', trailer)


# watermark the watermarked file
trailer = PdfReader('merged.pdf')

for page in trailer.pages:
    PageMerge(page).add(wmark).render()

PdfWriter().write('merged2.pdf', trailer)

The problem is around https://github.com/pmaupin/pdfrw/blob/master/pdfrw/pagemerge.py#L202.

The number 6 is not len('\pdfrw_'), so the isdigit() fails, and \pdfrw_0 is re-used every time.

Pdf2txt

Can a pdf to text conversion tool(a la pdf2txt in pdfminer) be added?

Tests are failing with AttributeError

Running the tests e.g. with nosetests results in a failure:

======================================================================
ERROR: test_doubleslash (tests.test_pdfstring.TestEncoding)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/valhalla/packaging/misc/pdfrw/pkg-pdfrw/tests/test_pdfstring.py", line 29, in test_doubleslash
    self.roundtrip('\\')
  File "/home/valhalla/packaging/misc/pdfrw/pkg-pdfrw/tests/test_pdfstring.py", line 26, in roundtrip
    self.assertEqual(value, self.encode_decode(value))
  File "/home/valhalla/packaging/misc/pdfrw/pkg-pdfrw/tests/test_pdfstring.py", line 23, in encode_decode
    return cls.decode(cls.encode(value))
  File "/home/valhalla/packaging/misc/pdfrw/pkg-pdfrw/tests/test_pdfstring.py", line 19, in encode
    return str(pdfrw.pdfobjects.PdfString.encode(value))
AttributeError: 'module' object has no attribute 'pdfobjects'

----------------------------------------------------------------------
Ran 1 test in 0.027s

FAILED (errors=1)

I've noticed that pdfrw/__init__.py includes a line

   from pdfrw.objects import PdfObject [...] PdfString

so I've tried to change:

  s/pdfrw.pdfobjects.PdfString/pdfrw.PdfString/g

everywhere in the file, which resulted in a passing test.

What is the expected behaviour? the one used in the tests or the one resulting 
from code?

Thanks in advance

Original issue reported on code.google.com by [email protected] on 30 Aug 2014 at 1:59

Inline images not handled

Inline images, as described at section 4.8.6 of the PDF 1.7 reference, turn content streams on their head by putting raw image data in the middle of normal PDF objects. It seems the tokenizer doesn't handle inline images at present, so the image data gets parsed into nonsense operators/operands. If there are left and right angle brackets in the image data, one of the tokens will be an invalid hex-encoded string, which will raise an assertion when you try to decode() it.

I've started work on this in my fork, but I'm wondering if the image data should be returned as a different data type or object. I haven't looked at PdfWriter yet either.

I filed a PR over at pmaupin/static_pdfs#1 to add a file with inline images to the test files. If you run the script below on that file, you should get an AssertionError with a message of '<\x00\x00>'.

import sys

import pdfrw


with open(sys.argv[1], "rb") as f:
    doc = pdfrw.PdfReader(f)
    for page in doc.pages:
        if isinstance(page.Contents, pdfrw.PdfArray):
            contents = list(page.Contents)
        else:
            contents = [page.Contents]
        pdfrw.uncompress.uncompress(contents)
        for content in contents:
            if content is None:
                continue
            for token in pdfrw.PdfTokens(content.stream):
                if isinstance(token, pdfrw.PdfString):
                    token.decode()

Stopiteration exception

Hello there,

First thanks for your great work!

I've been using this library for a while and it worked perfectly, my use case is the following:
1- I build a pdf document with reportlab library
2- I have other existing pdf documents that i append at the end of the document build in 1-. Till now every thing was fine till i encountered an error with a pdf file which when i want to add it at the end of the document, the program exits with an error on Stopiteration exception. Following is the error stack. The pdf document in question is fine when opened with adobe Acrobat reader and is made of 3 pages. So is there something i can do to know that some pdf file are not supported ?

Thanks!

File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfwriter.py", line 316, in write
[Mon Jun 13 13:15:50.782466 2016] [:error] [pid 16822] self.killobj, user_fmt=user_fmt)
[Mon Jun 13 13:15:50.782471 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfwriter.py", line 196, in FormatObjects
[Mon Jun 13 13:15:50.782476 2016] [:error] [pid 16822] format_deferred()
[Mon Jun 13 13:15:50.782481 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfwriter.py", line 164, in format_deferred
[Mon Jun 13 13:15:50.782487 2016] [:error] [pid 16822] objlist[index] = format_obj(obj)
[Mon Jun 13 13:15:50.782492 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfwriter.py", line 145, in format_obj
[Mon Jun 13 13:15:50.782512 2016] [:error] [pid 16822] myarray.append(add(value))
[Mon Jun 13 13:15:50.782517 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfwriter.py", line 83, in add
[Mon Jun 13 13:15:50.782523 2016] [:error] [pid 16822] result = format_obj(obj)
[Mon Jun 13 13:15:50.782528 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfwriter.py", line 135, in format_obj
[Mon Jun 13 13:15:50.782533 2016] [:error] [pid 16822] myarray = [add(x) for x in obj]
[Mon Jun 13 13:15:50.782538 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/objects/pdfarray.py", line 46, in iter
[Mon Jun 13 13:15:50.782543 2016] [:error] [pid 16822] self._resolve()
[Mon Jun 13 13:15:50.782548 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/objects/pdfarray.py", line 28, in _resolver
[Mon Jun 13 13:15:50.782554 2016] [:error] [pid 16822] value = value.real_value()
[Mon Jun 13 13:15:50.782559 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/objects/pdfindirect.py", line 21, in real_value
[Mon Jun 13 13:15:50.782564 2016] [:error] [pid 16822] value = self.value = self._loader(self)
[Mon Jun 13 13:15:50.782569 2016] [:error] [pid 16822] File "/usr/local/lib/python2.7/dist-packages/pdfrw/pdfreader.py", line 200, in loadindirect
[Mon Jun 13 13:15:50.782574 2016] [:error] [pid 16822] source.next()
[Mon Jun 13 13:15:50.782579 2016] [:error] [pid 16822] StopIteration

RE: PdfReader cannot read the io.BytesIO properly in Python 3.5

It seems there is a "tab/space" issue on line 499 in pdfreader.py, where it currently only do the 'convert_load' in case of file, but not from 'in-memory'(such as BytesIO) object. Ideally it should be done in both case, so I believe this is a typo that mis-place the line "fdata=conver_load(fdata)" into the 'file-reading' section only.

After I fix the 'tab' issue above(so that it applies for both case), I can use it for BytesIO object now.

By the way, it seems this bug only occurs in Python 3.5, I don't have any issue with Python 3.4.

Wrong boolean keywords

Boolean values get converted to "True" and "False". According to the PDF reference it must be lower-case.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.