Project

vectory

0.0
The project is in a healthy, maintained state
Vectory performs pairwise vector image conversions for common vector image formats, such as SVG, EMF, EPS and PS.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

>= 3.2.0
~> 1.0
>= 0
~> 0.1, >= 0.1.2
~> 0.3
~> 1.0
~> 1.9.399
~> 1.0, >= 1.0.7
 Project Readme

Vectory

Gem Version rake Pull Requests Commits since latest

Purpose

Vectory is a Ruby gem that performs pairwise vector image conversions for common vector image formats (EPS, PS, EMF, SVG), with PNG output from each format.

Vectory shall give you a glorious vectory over EPS files.

Installation

Prerequisites

Vectory is written in Ruby. Format support is provided by these gems (installed automatically):

  • emfsvg (EMF <→ SVG)

  • postsvg (PS/EPS <→ SVG)

  • svgpng ~> 0.1.0 (SVG → PNG)

PNG rendering uses the prebuilt native artifact in the platform-specific svgpng package; it requires no separately installed renderer or compiler. The supported native targets are arm64-darwin, x86_64-darwin, x86_64-linux, aarch64-linux, x86_64-linux-musl, aarch64-linux-musl, and x64-mingw-ucrt.

On other platforms, RubyGems selects the same-version ruby shell package. Existing non-PNG conversions remain available. Requesting PNG raises Vectory::UnsupportedPlatformError (CLI exit status 5). The renderer is loaded only when PNG output is requested.

Note
The PNG integration is under development. Its dependency must not be released with Vectory until the tested seven native packages and the ruby shell package are published together.

Gem install

gem install vectory

Or include it in your gemspec.

Usage

$ vectory [-o {output-file-name}] -f {format} {input-file-name}

Where,

format

the desired output format (one of: svg, eps, ps, emf, png)

input-file-name

file path to the input file

output-file-name

file path to the desired output file (with the file extension) (default: writes to a current directory by the input filename with an extension changed to a desired format)

PNG output

PNG is output-only. SVG, EMF, EPS, and PS inputs can be converted to PNG:

vectory -f png -o diagram.png --width 1200 --background '#ffffff' diagram.svg
vectory -f png --font 'Example Sans=fonts/ExampleSans-Regular.ttf' \
  --font 'Example Sans=fonts/ExampleSans-Bold.ttf' \
  --fallback-font 'Example Symbols=fonts/ExampleSymbols.ttf' \
  --fallback-font 'Example CJK=fonts/ExampleCJK.otf' diagram.emf

--font FAMILY=PATH is repeatable. Repeat a family to supply distinct style, weight, or stretch faces. --fallback-font FAMILY=PATH is also repeatable; fallback faces are tried in the order supplied. FAMILY must be the font’s own family name, for example Arial for Arial.ttf. Fonts are read explicitly from these paths; the renderer does not search system fonts. A text-free image needs no font options. Font substitution warnings are printed once each to stderr in renderer order, separately from the binary output file.

These options are valid only with -f png:

--width PIXELS, --height PIXELS

Positive integer output dimensions. One specified dimension preserves the source aspect ratio. Both dimensions set the canvas size, fitting and centering the image without changing its aspect ratio.

--scale NUMBER

Positive decimal scale applied to intrinsic dimensions. Cannot be combined with width or height.

--background COLOR

transparent (the default), #RRGGBB, or #RRGGBBAA. Quote hexadecimal colors in shell commands.

--font FAMILY=PATH, --fallback-font FAMILY=PATH

Explicit font faces and ordered fallbacks as described above.

Without size options, the renderer uses the SVG’s intrinsic dimensions, then its viewBox, with a 300 by 150 default. A DOCTYPE with an internal […​] subset is rejected before XML parsing; a plain DOCTYPE, as SVG editors write it, is accepted and its external DTD is never loaded. External resources cannot be enabled through a CLI option.

Using the Ruby library

Some examples:

Take EMF as a path to a file and return SVG as a string:

path = "path/to/file.emf"

Vectory::Emf.from_path(path).to_svg.content

Take EPS as a string and return EMF as a path to a file:

# NOTE: content is shortened for readability
content = "%!PS-Adobe-3.0 EPSF-3.0\n ... %%Trailer"

Vectory::Eps.from_content(content).to_emf.write.path

Take SVG as a datauri and return EMF as a datauri:

# NOTE: datauri is shortened for readability
uri = "data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0 ... GRkYiLz48L3N2Zz4="

Vectory::Datauri.new(uri).to_vector.to_emf.to_uri.content

Binary PNG results

to_png returns a Vectory::Png from any supported vector class. Pass explicit font and fallback collections, including empty collections for text-free SVG:

require "vectory"

svg = Vectory::Svg.from_path("diagram.svg")
png = svg.to_png(profile: { width: 1200, background: "#ffffff" },
                 fonts: {}, fallback_fonts: [])

png.content       # binary PNG bytes (ASCII-8BIT)
png.mime          # "image/png"
png.width         # output width in pixels
png.height        # output height in pixels
png.size          # byte count in memory
png.warnings      # structured font substitution warnings, in renderer order
png.write("diagram.png").path

For text, construct faces with the public Svgpng::FontFace API. The fonts hash maps family names to arrays of faces; fallback_fonts is an ordered array:

require "svgpng"

face = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSans.ttf"),
                           source_id: "fonts/ExampleSans.ttf")
symbols = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSymbols.ttf"),
                              source_id: "fonts/ExampleSymbols.ttf")
png = svg.to_png(profile: { scale: "2" },
                 fonts: { "Example Sans" => [face] }, fallback_fonts: [symbols])

Exact font families are matched against the font metadata after normalization; a caller-provided family name must match that metadata. Supply separate faces for style, weight, and stretch. Each shaped cluster uses an exact-family face with coverage first, then the ordered fallback faces. Missing coverage raises Vectory::FontError; no system font search or implicit substitution occurs. Ruby callers receive structured warnings in png.warnings and decide how to present them; the CLI prints deduplicated substitutions to stderr.

Profile keys correspond to the CLI options. Width and height are integers; scale is a decimal string. PNG results share the image file lifecycle below: path and file_size raise before a write, the first no-argument write uses a temporary file, and subsequent no-argument writes reuse the written path. PNG is not accepted as an input format and has no vector data-URI API.

PNG safety, errors, and conformance

Output sizing applies explicit width/height first; a single dimension derives the other from the intrinsic aspect ratio. Otherwise scale multiplies intrinsic size; scale and explicit dimensions are mutually exclusive. Intrinsic size uses both SVG root dimensions, or derives a missing dimension from a positive viewBox; with neither dimension it uses the viewBox, then 300 by 150. Without a usable viewBox, a missing root dimension defaults to 300 or 150. Percent root lengths use that 300 by 150 viewport; absolute units use 96 dpi. Resolved dimensions round half up and clamp to at least one pixel.

The raw SVG byte boundary rejects DOCTYPE internal subsets before parsing, including subsets whose entities are unused. A plain DOCTYPE is accepted and its external DTD is never loaded. Only same-document fragments and inline data: resources are allowed. Relative/absolute paths, network URLs, other non-inline references, and CSS @import are rejected. There is no resource loader or opt-in for external access.

Enforced limits are 16 MiB of SVG, 64 font faces, 32 MiB per font, 128 MiB of fonts total, 32768 pixels per output axis, 64,000,000 output pixels, and a 256 MiB output buffer with checked row-stride arithmetic. These are allocation bounds, not a time budget. For a wall-clock deadline, render in a separate, killable process; the synchronous native call has no safe in-process cancellation.

Ruby error Typical cause CLI status

Vectory::RenderProfileError

Invalid size, scale, background, or profile key

4

Vectory::MalformedSvgError

Malformed SVG/XML

4

Vectory::FontError

Invalid, duplicate, missing family, or missing glyph face

4

Vectory::ForbiddenExternalReferenceError

DOCTYPE internal subset or non-inline reference

4

Vectory::RenderLimitError

Input, font, dimension, pixel, or buffer bound

4

Vectory::UnsupportedPlatformError, Vectory::RendererLoadError

Unsupported platform or unavailable packaged renderer

5

Vectory::NativeRenderError, Vectory::PngEncodingError

Native rendering or PNG encoding failure

5

Vectory::SystemCallError

Unreadable font/input or unwritable output

5

Success returns CLI status 0. PNG-only options with another output format return status 4. Unsupported input/output formats retain statuses 2/3, and conversion to the same vector format retains status 7.

Deterministic bytes require the same SVG bytes, font bytes and order, render profile, and qualified renderer/dependency build. Conformance validation checks PNG structure; it does not establish visual correctness, cross-build byte identity, or general support for every SVG construct. Native details belong to svgpng’s support, provenance, encoder, and release contract and golden compatibility documentation.

The test-only png_conform dependency is version 0.1.4 at Git commit 653abae0d16d9533a37a5d5eca40896d3b307993. After bundle install, validate the written file directly (the validator is not a Vectory runtime dependency):

require "png_conform"
require "png_conform/services/validation_orchestrator"

path = png.write("diagram.png").path
analysis = PngConform::Services::ValidationOrchestrator.validate_file(path)
raise analysis.to_json unless analysis.valid?
bundle exec rspec spec/integration/png_conform_spec.rb
bundle exec png_conform check --format json diagram.png

The integration spec validates a real render with explicit font collections and a corrupted-file negative control with nonempty diagnostic errors. It tests the existing file boundary without an adapter. Gemfile.lock remains ignored and untracked; the tracked Gemfile’s Git ref supplies the validator pin.

The transform pipeline may produce the final SVG bytes; PNG rendering consumes those bytes and does not depend on transform pipeline internals.

What is supported?

There are several vector classes which support conversion between each other:

Vectory::Eps
Vectory::Ps
Vectory::Emf
Vectory::Svg

Each of them can be instantiated in several ways:

Vectory::Eps.from_path("images/img.eps")
Vectory::Eps.from_content("%!PS-Adobe-3.0...")
Vectory::Eps.from_datauri("data:image/svg+xml;base64,PHN2 ... 2Zz4=")
Vectory::Eps.from_node(Nokogiri::XML(
  "<image mimetype="application/postscript" alt="3">
    %!PS-Adobe-3.0 EPSF-3.0 ...
   </image>"
).child)

Converting to other formats:

Vectory::Eps.from_content(content).to_ps
Vectory::Eps.from_content(content).to_emf
Vectory::Eps.from_content(content).to_svg

Several ways of getting content of an object:

Vectory::Eps.from_content(content).to_svg.content
Vectory::Eps.from_content(content).to_svg.to_uri.content # as datauri
Vectory::Eps.from_content(content).to_svg.write.path

Datauri

Also there is the Vectory::Datauri class which represents vectory images in the datauri format.

Convert an SVG datauri to a plain SVG:

# NOTE: datauri is shortened for readability
uri = "data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0 ... GRkYiLz48L3N2Zz4="
Vectory::Datauri.new(uri).to_vector.content

Convert an EPS file to its datauri representation:

eps = Vectory::Eps.from_path("img.eps")
Vectory::Datauri.from_vector(eps).content

There is also a simplified API for this case:

Vectory::Eps.from_path("img.eps").to_uri.content

SVG mapping (for the metanorma project)

Vectory can integrate SVG files into XML or HTML, respecting internal id and link references. It supports ID disambiguation for multi-document and multi-svgmap scenarios.

Basic usage
xml_string = Vectory::SvgMapping.from_path("doc.xml").to_xml
ID suffixing for uniqueness

When processing multiple documents or multiple svgmaps within a document, SVG IDs must be unique to avoid conflicts. Vectory applies two types of suffixes:

ID suffix (Cross-document uniqueness)

An optional suffix derived from document or container identity (e.g., _ISO_17301-1_2016). This provides uniqueness across documents or collections.

Index suffix (Multi-svgmap uniqueness)

Automatically applied based on the svgmap’s position in the document (0, 1, 2, …​). Formatted as a 9-digit zero-padded number (e.g., _000000000, _000000001). This provides uniqueness when a document contains multiple svgmaps.

Final ID composition
Original ID:  fig1
With ID suffix only:  fig1_ISO_17301-1_2016
With both suffixes:   fig1_ISO_17301-1_2016_000000000
Usage with ID suffix
mapping = Vectory::SvgMapping.new(doc, "", id_suffix: "_ISO_17301-1_2016")
xml_string = mapping.call.to_xml
Input format

The input XML must support the svgmap tag with link mapping.

<svgmap id="_4072bdcb-5895-4821-b636-5795b96787cb">
  <figure><image src="action_schemaexpg1.svg"/></figure>
  <target href="mn://action_schema">
    <xref target="ref1">Computer</xref>
  </target>
  <target href="http://www.example.com">
    <link target="http://www.example.com">Phone</link>
  </target>
</svgmap>
action_schemaexpg1.svg
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <style type="text/css">
    #Layer_1 { fill:none }
    svg[id = 'Layer_1'] { fill:none }
    .st0{fill:none;stroke:#000000;stroke-miterlimit:10;}
  </style>
  <a xlink:href="mn://action_schema" xlink:dummy="Layer_1">
    <rect x="123.28" y="273.93" class="st0" width="88.05" height="41.84"/>
  </a>
  <a xlink:href="mn://basic_attribute_schema" >
    <rect x="324.69" y="450.52" class="st0" width="132.62" height="40.75"/>
  </a>
  <a xlink:href="mn://support_resource_schema" >
    <rect x="324.69" y="528.36" class="st0" width="148.16" height="40.75"/>
  </a>
</svg>
Output format
<figure>
  <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1'
       id='Layer_1_000000001' x='0px' y='0px' viewBox='0 0 595.28 841.89'>
    <style> #Layer_1_000000001 { fill:none }</style>
    <a xlink:href='#ref1' xlink:dummy='Layer_1_000000001'>
      <rect x='123.28' y='273.93' class='st0' width='88.05' height='41.84'/>
    </a>
    <a xlink:href='mn://basic_attribute_schema'>
      <rect x='324.69' y='450.52' class='st0' width='132.62' height='40.75'/>
    </a>
    <a xlink:href='mn://support_resource_schema'>
      <rect x='324.69' y='528.36' class='st0' width='148.16' height='40.75'/>
    </a>
  </svg>
</figure>
Inline SVG support

SVG can also be provided inline within the svgmap:

<svgmap id="_60dadf08-48d4-4164-845c-b4e293e00abd">
  <figure>
    <svg xmlns='http://www.w3.org/2000/svg' id='Layer_1'>
      <a href="mn://action_schema">
        <rect x="123.28" y="273.93" class="st0"/>
      </a>
    </svg>
  </figure>
  <target href="mn://action_schema">
    <xref target="ref1">Computer</xref>
  </target>
</svgmap>
Data URI support

Images can be provided as data URIs:

<svgmap id="_60dadf08-48d4-4164-845c-b4e293e00abd">
  <figure>
    <image src='data:image/svg+xml;base64,PD94...'/>
  </figure>
  <target href="href1.htm">
    <xref target="ref1">Computer</xref>
  </target>
</svgmap>

File system operations

An image object contains information where it is written. It can be obtained with the #path API:

vector = Vectory::Eps.from_path("img.eps")
vector.path

Before the first write it raises the NotWrittenToDiskError error:

vector.path # => raise NotWrittenToDiskError

After writing it returns a path of the image on a disk:

vector.write
vector.path # => "/tmp/xxx/yyy"

By default it writes to a temporary directory but it can be changed by providing an argument with a desired path:

vector.write("images/img.eps")
vector.path # => "images/img.eps"

Since an image can be initially read from a disk, it also keeps an initial path. To avoid accidental overwrite, this path is used only for read-only purposes.

vector.initial_path # => "storage/images/img.eps"

Additional properties

The following additional properties are supported:

Datauri#mime
Datauri#height
Datauri#width
Vector (Eps, Ps, Svg, Emf)
Vector#mime
Vector#size
Vector#file_size
Vector#height
Vector#width
Png#mime
Png#size
Png#file_size
Png#height
Png#width
Png#warnings

Development

Regenerating test fixtures

Some test fixtures are generated by external tools (Ghostscript, Inkscape, cairo). When these tools are updated, the reference files may need to be regenerated.

To regenerate all test fixtures:

bundle exec rake regenerate_fixtures

This will update the following files:

  • spec/examples/ps2eps/ref.eps - PS to EPS conversion reference

  • spec/examples/ps2svg/ref.svg - PS to SVG conversion reference

  • spec/examples/svg/doc2-ref.xml - SVG mapping reference

Note
After regenerating fixtures, review the changes to ensure they are expected before committing.

Releasing

Releasing is done automatically with GitHub Actions. Just bump and tag with gem-release.

For a patch release (0.0.x) use:

gem bump --version patch --tag --push

For a minor release (0.x.0) use:

gem bump --version minor --tag --push

Serialized SVG transforms

Vectory exposes immutable transformations of serialized XML strings. Class selectors are parsed with Crass (~> 1.0, >= 1.0.7); class lists and selectors use the same positional inject<index> suffix as ID disambiguation. SvgClassSuffixer is the canonical Vectory class-suffix implementation.

cleanup = Vectory::SvgTransform.disambiguate(index: 0, duplicate_ids: collisions) >>
  Vectory::SvgTransform.suffix_classes(index: 0) >>
  Vectory::SvgTransform.bind_namespaces(bind: { "xlink" => "http://www.w3.org/1999/xlink" })
result = cleanup.call(svg_xml)

The executable profiles are graft (G), svg_cleanup (D → S → N), and graft_then_svg_cleanup (G → D → S → N). Other sequences are rejected; construction prefixes cannot execute until complete. Cleanup accepts a selected SVG root, while a graft can accept a complete host document. Reapplying a profile with the same captured inputs is XML-equivalent. Step options are deeply frozen snapshots, so later changes to a caller’s collision map cannot change a pipeline.

Namespace binding preserves expanded element and attribute names; it is separate from the legacy SvgDocument#namespace ID/link cleanup. See the API reference for safe binding, unbinding and URI-to-prefix remapping.

For multiple embedded SVGs, graft the complete mapped document once, then build a fresh cleanup pipeline for each SVG from the current collision map. Merge each result’s IDs before constructing the next pipeline. Standoc #1298 adopts ID disambiguation while retaining its inline Crass helpers; adopting SvgClassSuffixer is a separate downstream task after a containing release. SVG-to-PNG rendering is a separate projection feature.

Contributing

Bug reports and pull requests are welcome on GitHub at: