borb PDF Library

repository·master·Indexed 25 days ago

https://github.com/borb-pdf/borb

A pure Python library for creating, reading, and manipulating PDF files using a JSON-like structure of nested lists and dictionaries. It features a comprehensive LayoutElement hierarchy for adding text, images, tables, and interactive forms, as well as tools for metadata management, text extraction, and PDF font decoding. The library includes built-in support for license generation and verification via SHA-256 hashing and cryptographic signatures.

Tokens
1.9K
Snippets
4
Records
11
Agent score
86%

What's inside borb

  1. Overview of borb features

    master

    borb is a pure Python library for PDF document management. Key capabilities include:

    • Metadata Management: Reading and editing PDF metadata.
    • Extraction: Extracting text and images from existing PDFs.
    • Annotations: Adding notes and links.
    • Content Manipulation: Adding text, images, tables, and lists.
    • Layout Management: Using PageLayout to manage page structures.
  2. Understand the PDF Font Types Hierarchy in borb

    master

    The borb library organizes PDF fonts into a hierarchy that determines how text is rendered and decoded. Understanding this hierarchy is essential for working with text-heavy PDFs.

    Font Classifications

    • Simple Fonts: Basic fonts that map characters directly to glyphs.
      • Type1Font (including StandardType1Font)
      • Type3Font
      • TrueTypeFont
    • Composite Fonts: Designed for large character sets and complex mappings.
      • CIDFont (including CIDType0Font and CIDType2Font)

    Key Font Properties

    • Simple Fonts (e.g., Type1Font) use properties like Encoding, ToUnicode, Widths, and FontDescriptor.
    • Composite Fonts (e.g., CIDFont) use CMap and CIDSystemInfo to manage complex character mappings.
  3. Understand the LayoutElement class hierarchy

    master

    The LayoutElement class hierarchy is the foundation for all content added to PDFs in borb. It provides a structured way to include text, images, shapes, annotations, forms, and tables.

    Key content categories include:

    • Paragraphs: Support for plain, styled, and header-like text via Paragraph, Heading, MarkdownParagraph, and List elements.
    • Images: Visual elements including Image, Avatar, Barcode, Chart, DallE, Equation, QRCode, Screenshot, Unsplash, and Watermark.
    • Shapes and Maps: Vector graphics and cartographic elements like Shape and various Map types (e.g., MapOfTheWorld, MapOfEurope).
    • Annotations: Interactive or visual markings such as LinkAnnotation, HighlightAnnotation, TextAnnotation, RubberStampAnnotation, and FreeTextAnnotation.
    • Interactive Forms: User-input elements including FormField types like TextBox, TextArea, RadioButton, CheckBox, Button, and DropDownList (including specialized CountryDropDownList and GenderDropDownList).
    • Tables and Layout Tools: Data organization via Table (including FixedColumnWidthTable and FlexibleColumnWidthTable) and structural tools like ProgressBar and HorizontalBreak.
  4. Decode text from a PDF font

    master

    When reading text from a PDF, borb decodes content bytes using a specific decision logic based on the font type and its properties. To ensure accurate text extraction, the library follows these encoding mechanisms:

    1. TrueType Fonts: Uses the /CMap for decoding.
    2. Standard 14 Fonts: Uses the defined /Encoding.
    3. ToUnicode Mapping: If the /ToUnicode property is present, it is used to decode characters into Unicode.
    4. Differences Mapping: If /ToUnicode is absent, the library checks for /Differences to map specific character codes.
    5. Base Encoding: If no specific encoding is found, the library falls back to /BaseEncoding (e.g., StandardEncoding, MacRoman) or the implied /BaseEncoding.
  5. Create a basic PDF with Hello World

    master

    To create a simple PDF, follow these steps:

    1. Initialize a Document.
    2. Create a Page and append it to the document.
    3. Define a PageLayout (e.g., SingleColumnLayout) for the page.
    4. Append layout elements like Paragraph to the layout.
    5. Use PDF.write to save the document to a file path.
    from pathlib import Path
    from borb.pdf import Document, Page, PageLayout, SingleColumnLayout, Paragraph, PDF
    
    # Create an empty Document
    d: Document = Document()
    
    # Create an empty Page
    p: Page = Page()
    d.append_page(p)
    
    # Create a PageLayout
    l: PageLayout = SingleColumnLayout(p)
    
    # Add a Paragraph
    l.append_layout_element(Paragraph('Hello World!'))
    
    # Write the PDF
    PDF.write(what=d, where_to="assets/output.pdf")
  6. Verify and register a license using License.register()

    master

    Verify the authenticity and validity of a license file. The register method checks the cryptographic signature against a public key, ensures the current date falls within the min_date and max_date range, and confirms the software version does not exceed max_version. If successful, it sets the license fields in the License class.

    if License.register("example_license.json"):
        print("License is valid and registered.")
    else:
        print("License verification failed.")
  7. Create a license using License.create_license()

    master

    Generate a signed license file by providing organization and user details, validity dates, and a maximum software version. The process serializes the data to JSON, computes a SHA-256 hash, and signs it using a private key from a PEM file. The resulting signature is stored in the license_key field of the JSON file.

    License.create_license(
        company="Example Corp",
        license_path="example_license.json",
        max_date=datetime.datetime.now() + datetime.timedelta(days=365),
        max_version=Version("2.1.0"),
        min_date=datetime.datetime.now(),
        name="John Doe",
        private_key_path="/path/to/private_key.pem",
    )
  8. Disable or enable usage statistics

    master
    By default, borb sends usage statistics (such as event type, document/page counts, version, and OS) to a secure endpoint when reading or writing PDF documents. You can opt out of this telemetry collection at any time to prevent any further events from being sent, or opt back in later.
  9. Reference: Collected usage statistics data

    master

    When telemetry is enabled, the following data points may be transmitted during read or write operations:

    • event: The action performed (e.g., "read_pdf", "write_pdf")
    • number_of_documents: The number of documents processed
    • number_of_pages: The number of pages processed
    • version: The installed version of borb
    • operating_system: The OS/platform used (e.g., linux, win32, darwin)
    • license_valid_from_in_ms / license_valid_until_in_ms: The validity period of a license (in milliseconds since epoch)
    • company: The company name if specified in the license metadata
    • A pseudonymous identifier derived from the source IP address
  10. License JSON data structure

    master

    A license is stored as a JSON dictionary containing the following fields:

    • company: The organization associated with the license.
    • name: The individual owner of the license.
    • max_version: The maximum software version supported by the license.
    • min_date: The earliest valid date for the license.
    • max_date: The expiration date of the license.
    • license_key: The base64 encoded cryptographic signature.