svgexport

repository·master·Indexed 21 days ago

https://github.com/piqnt/svgexport

A Node.js module and command-line tool for exporting SVG files to PNG and JPEG formats using Puppeteer for high-fidelity rendering. It supports single file conversion, batch processing via JSON datafiles, and programmatic use through the render() method. Features include configurable output sizes, viewbox modes, CSS styling, and adjustable timeouts via the SVGEXPORT_TIMEOUT environment variable.

Tokens
2.1K
Snippets
9
Records
9
Agent score
74%

What's inside svgexport

  1. Configure batch processing with a datafile

    master

    You can automate multiple exports by providing a path to a JSON file (or a Node module that exports the same structure). Each entry in the array defines an input and its corresponding outputs.

    Datafile Format:

    [
      {
        "input" : ["<input file>", "<option>", "<option>", ...],
        "output": [ ["<output file>", "<option>", "<option>", ...] ]
      }, ...
    ]

    Note: Input file options are merged with and overridden by output file options.

    CLI Usage: svgexport <datafile>

    [
      {
        "input" : ["input.svg", "1.5x"],
        "output": [ ["output.png", "80%"], ["output.jpg", "90%"] ]
      }
    ]
  2. Install svgexport via CLI

    master

    To use svgexport as a command-line tool, install it globally using npm.

    If you encounter installation errors related to Puppeteer, use the --unsafe-perm=true flag with sudo to circumvent permission issues.

    npm install svgexport -g
    
    # If installation fails due to puppeteer issues:
    sudo npm install -g svgexport --unsafe-perm=true
  3. Use svgexport as a Node.js module

    master

    To integrate svgexport into your application, install it as a dependency and use the render method.

    Installation: npm install svgexport --save

    API Signature: svgexport.render(datafile, callback)

    • datafile: Can be a JSON file path, an object, or an array of objects (following the same format as the CLI datafile).
    • callback: The function called after rendering is complete.
    var svgexport = require('svgexport');
    
    // Using a JSON file path
    svgexport.render('data.json', function(err) {
      if (err) console.error(err);
      else console.log('Export complete');
    });
  4. Set the SVGEXPORT_TIMEOUT environment variable

    master

    Puppeteer has a default page load timeout of 30 seconds. For large SVG files that require more time to render, set the SVGEXPORT_TIMEOUT environment variable to the desired number of seconds.

    Example (60 second timeout):

    SVGEXPORT_TIMEOUT=60 svgexport input.svg output.png
  5. Use the svgexport CLI

    master

    The svgexport CLI converts SVG files to PNG or JPEG using Puppeteer. You can provide an input file and output file directly, or pass a path to a JSON datafile for batch processing.

    Basic Syntax: svgexport <input file> <output file> <options> svgexport <datafile>

    Options Reference:

    • <format>: png | jpeg | jpg. Defaults to the output file extension or png.
    • <quality>: 1%-100% (for JPEG).
    • <input viewbox>: <left>:<top>:<width>:<height> or <width>:<height>. Defaults to the input file's viewbox.
    • <output size>: <scale>x (e.g., 1.5x), <width>:<height>, <width>:, or :<height>.
    • <viewbox mode>: crop (default) or pad. Determines how the input is handled to match the output aspect ratio.
    • <styles>: A CSS string to style the input SVG (e.g., "svg{background:silver;}").
    # Scale 1.5x proportionally
    svgexport input.svg output.png 1.5x
    
    # Scale proportionally to set output width to 32px
    svgexport input.svg output.png 32:
    
    # Scale proportionally and pad output to set width:height to 32px:54px
    svgexport input.svg output.png pad 32:54
    
    # Export a specific viewbox (-1:-1:24:24) at 1x scale
    svgexport input.svg output.png -1:-1:24:24 1x
    
    # Set JPEG quality to 80%
    svgexport input.svg output.jpg 80%
    
    # Apply CSS styles
    svgexport input.svg output.jpg "svg{background:silver;}"
  6. Export SVGs using render()

    master

    The render function is the primary programmatic API for converting SVGs to other formats (like PNG or JPEG). It accepts a configuration object or a path to a JSON/JS configuration file and an optional callback function for completion/error handling.

    Configuration Object

    The configuration object can be a single object or an array of objects. Each entry in the array defines an input and its corresponding outputs.

    Key Properties:

    • src or input: The path to the source SVG file(s). If a string, it is treated as a single file; if an array, multiple files can be specified.
    • dest or output: The destination path(s). This can be a single string, an array of strings, or a 2D array for mapping multiple inputs to multiple outputs.
    • cwd or base: The current working directory used to resolve relative paths. Defaults to process.cwd().

    Callback Handling

    The done parameter is a callback function. If provided, it is called when rendering is complete or if an error occurs. If you pass a process object (like process), the function will use its stdout and stderr for logging.

    const svgexport = require('svgexport');
    
    // Example 1: Using a configuration object
    await svgexport.render({
      input: 'path/to/image.svg',
      output: 'path/to/output.png',
      cwd: '/your/project/root'
    }, (err) => {
      if (err) console.error(err);
      else console.log('Done!');
    });
    
    // Example 2: Using an array of configurations
    await svgexport.render([
      {
        input: ['file1.svg', 'file2.svg'],
        output: ['out1.png', 'out2.png']
      }
    ]);
  7. Use render() with a configuration file

    master

    Instead of passing a full configuration object, you can pass a string representing the path to a .js or .json file that exports your configuration. render() will automatically resolve the path and require the file.

    const svgexport = require('svgexport');
    
    // Pass the path to a config file
    await svgexport.render('./my-config.json', (err) => {
      if (err) console.error(err);
    });
  8. Use the svgexport CLI

    master

    The cli function provides command-line interface functionality. It can be used to trigger renders via terminal arguments.

    CLI Usage Patterns

    1. Config File Mode: If the first argument is a path to a .js or .json file, it renders using that configuration.
      svgexport config.json
    
    2. **Direct Input/Output Mode**: If multiple arguments are provided, the first is treated as the input file and the subsequent arguments are treated as output destinations.
     ```bash
    svgexport input.svg output1.png output2.jpg
    1. Help Mode: Running with no arguments or the --help flag displays the usage guide.
      svgexport --help
    
    ```bash
    # Render using a config file
    svgexport config.json
    
    # Render an SVG to multiple outputs
    svgexport input.svg output1.png output2.jpg
  9. Use the svgexport CLI

    master

    The svgexport package provides a command-line interface for exporting SVGs. The CLI is invoked via the svgexport command (when installed globally or via npm scripts) and accepts arguments to process SVG files. The entrypoint is handled by the package's internal .cli() method, which processes the command-line arguments provided after the command name.

    # Example usage (assuming svgexport is in your PATH)
    svgexport [options] <file>