pdfme.base

class pdfme.base.PDFBase(version='1.5', trailer=None)

Bases: object

This class represents a PDF file, and deals with parsing python objects you add to it (with method add) to PDF indirect objects. The python types that are parsable to their equivalent PDF types are dict (parsed to PDF Dictionaries), list, tuple, set (parsed to PDF Arrays), bytes (no parsing is done with this type), bool (parsed to PDF Boolean), int (parsed to PDF Integer), float (parsed to PDF Real), str (parsed to PDF String) and PDFObject, a python representation of a PDF object.

When you are done adding objects to an instance of this class, you just have to call its output method to create the PDF file, and we will take care of creating the head, the objects, the streams, the xref table, the trailer, etc.

As mentioned before, you can use python type bytes to add anything to the PDF file, and this can be used to add PDF objects like Names.

For dict objects, the keys must be of type str and you don’t have to use PDF Names for the keys, because they are automatically transformed into PDF Names when the PDF file is being created. For example, to add a page dict, the keys would be Type, Content and Resources, instead of /Type, /Content and /Resources, like this:

base = PDFBase()
page_dict = {
    'Type': b'/Page', 'Contents': stream_obj_ref, 'Resources': {}
}
base.add(page_dict)

You can add a stream object by adding a dict like the one described in function pdfme.parser.parse_stream().

This class behaves like a list, and you can get a PDFObject by index (you can get the index from a PDFObject.id attribute), update by index, iterate through the PDF PDFObjects and use len to get the amount of objects in this list-like class.

Parameters
  • version (str, optional) – Version of the PDF file. Defaults to ‘1.5’.

  • trailer (dict, optional) – You can create your own trailer dict and pass it as this argument.

Raises

ValueError – If trailer is not dict type

add(py_obj)

Add a new object to the PDF file

Parameters

py_obj (dict, list, tuple, set, bytes, bool, int, float, str, PDFObject) – Object to be added.

Raises

TypeError – If py_obj arg is not an allowed type.

Returns

A PDFObject representing the object added

Return type

PDFObject

output(buffer)

Create the PDF file.

Parameters

buffer (file_like) – A file-like object to write the PDF file into.