tdewolff/canvas

repository·master·Indexed 23 days ago

https://github.com/tdewolff/canvas

A library and toolkit featuring the pdftext CLI utility for inspecting, extracting, and replacing text within PDF documents. It supports various PDF text encodings (Standard, WinAnsi, MacRoman, Builtin, ToUnicode, and Type1 Differences) and provides programmatic APIs for PDF reading, writing, and stream compression/decompression. Additionally, it includes functionality to parse LaTeX strings and DVI files into canvas paths using external binaries like latex and dvisvgm.

Tokens
6.2K
Snippets
5
Records
52
Agent score
83%

What's inside tdewolff/canvas

  1. Use the pdftext CLI tool

    master

    The pdftext tool is a toolkit for extracting and replacing text within PDF files. It provides two primary modes of operation: extraction and replacement.

    Extraction

    Extract text content from specific pages or retrieve document metadata.

    Replacement

    Replace existing text strings at specific indices with new text, allowing for positional offsets and alignment adjustments.

  2. How PDF font Unicode mapping works

    master

    When a PDF font provides a ToUnicode CMap, the system uses a pdfFontUnicode structure to map character codes to UTF-8 strings.

    • Mapping: A map from uint16 character codes to string destinations.
    • Byte Width: Supports both 1-byte (standard) and 2-byte (Type0/CID) character encodings.
    • Complex Mappings: The system can handle multi-rune mappings (e.g., mapping a single code to a ligature like "ffl") by attempting to match the longest possible sequence of runes against the reverse mapping.
  3. Configure the FillRule for path filling

    master

    The FillRule determines how overlapping subpaths are filled. You can choose between several algorithms:

    • NonZero (default): Fills any point enclosed by an unequal number of clockwise and counter-clockwise paths.
    • EvenOdd: Fills any point enclosed by an uneven number of paths, regardless of direction.
    • Positive: Fills only counter-clockwise oriented paths.
    • Negative: Fills only clockwise oriented paths.
  4. Supported PDF text encodings

    master

    The pdftext utility handles several types of character encodings to correctly decode text from PDF documents. These include:

    • StandardEncoding: The default PDF encoding.
    • WinAnsiEncoding: Windows-specific ANSI encoding.
    • MacRomanEncoding: Macintosh-specific Roman encoding.
    • Builtin Encoding: Uses the font's internal Cmap (character map) via the SFNT font program.
    • ToUnicode Mapping: Uses an explicit ToUnicode stream provided in the PDF to map character codes to UTF-8 strings.
    • Type1 Differences: Handles specific character replacements defined in the font's Differences array.
  5. Flatten Bézier curves and arcs into linear segments

    master
    To convert complex curves into a series of straight lines, use the Flatten(tolerance float64) method. The tolerance parameter defines the maximum allowed deviation from the original curve. This returns a new path consisting only of MoveTo, LineTo, and Close commands.
  6. Convert arcs to cubic Bézier curves

    master
    The ReplaceArcs() method returns a new path where all ArcTo commands have been replaced by CubeTo (cubic Bézier) commands. This is useful for formats like PDF that do not natively support elliptical arcs.
  7. Add commands to a Path

    master

    Use the following methods to build a path by adding segments. If the path is empty, these methods will automatically perform an initial MoveTo to (0,0) or the specified coordinates.

    • MoveTo(x, y float64): Starts a new independent subpath at (x, y).
    • LineTo(x, y float64): Adds a straight line from the current position to (x, y).
    • QuadTo(cpx, cpy, x, y float64): Adds a quadratic Bézier curve with control point (cpx, cpy) and end point (x, y).
    • CubeTo(cpx1, cpy1, cpx2, cpy2, x, y float64): Adds a cubic Bézier curve with two control points and an end point (x, y).
    • ArcTo(rx, ry, rot float64, large, sweep bool, x, y float64): Adds an elliptical arc. rot is rotation in degrees, large and sweep are boolean flags for arc direction and size.
    • Close(): Closes the current subpath by drawing a line back to the last MoveTo position.
  8. Convert DVI files to Paths with DVI2Path

    master

    The DVI2Path function parses a DVI file (the output format from TeX) and converts its contents into a *Path. To use this function, you must provide a DVIFonts implementation that can resolve font names and sizes to specific DVIFont instances.

    Workflow:

    1. Implement the DVIFonts interface to handle font lookups.
    2. Call DVI2Path(data, yourFontsImplementation).
    3. The resulting *Path can then be used for drawing operations in the canvas library.
  9. Rasterize a Path to a scanx.Scanner

    master

    Use ToScanxScanner to convert a *Path into commands for a *scanx.Scanner. This is useful for scanline-based rasterization. The method requires a dy value (representing the vertical offset/height) and a Resolution. Like the vector rasterizer, it flattens curves into lines using a tolerance derived from the resolution.

    func (p *Path) ToScanxScanner(ras *scanx.Scanner, dy float64, resolution Resolution)
  10. Check if a point is inside a Path

    master

    The ContainsPoint method determines if a specific coordinate (x, y) is inside the area defined by the path. This result depends on the provided FillRule.

    Note: If the point lies exactly on the path's boundary, it is considered to be on the exterior.

  11. Calculate path length and check flatness

    master

    Use these methods to inspect the geometric properties of a path:

    • Length(): Returns the total length of the path in millimeters. Note that lengths for cubic Béziers are approximated.
    • IsFlat(): Returns true if the path consists exclusively of MoveTo, LineTo, and Close commands (no curves or arcs).
  12. Initialize a PDF reader with NewPDFReader

    master

    Use NewPDFReader to create a new instance of a pdfReader. This function reads the entire content from an io.Reader and parses the PDF structure, including the trailer, encryption (if a password is provided), and the page tree (kids).

    If the PDF is invalid or the version is unsupported, it returns an error. If the PDF is encrypted, you must provide the correct password to successfully parse the objects.