Donner SVG 0.8.0-pre
SVG editor and embeddable C⁠+⁠+⁠20 engine.
Loading...
Searching...
No Matches
svg_to_png.cc

Render SVG to PNG.

Render SVG to PNG This example demonstrates how to parse an SVG file and render it to a PNG file using the active rendering backend.

To run:

bazel run //examples:svg_to_png -- donner_splash.svg

The output is saved to "output.png" in the current working directory.

/**
* @example svg_to_png.cc Render SVG to PNG
* @details This example demonstrates how to parse an SVG file and render it to a PNG file using
* the active rendering backend.
*
* To run:
*
* ```sh
* bazel run //examples:svg_to_png -- donner_splash.svg
* ```
*
* The output is saved to "output.png" in the current working directory.
*/
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <sstream>
#include "donner/svg/SVG.h"
/**
* Main function, usage: svg_to_png <filename>
*/
int main(int argc, char* argv[]) {
// When launched via `bazel run`, change to the user's original working
// directory so that relative paths resolve naturally.
if (const char* bwd = std::getenv("BUILD_WORKING_DIRECTORY")) {
std::filesystem::current_path(bwd);
}
using namespace donner;
using namespace donner::svg;
using namespace donner::svg::parser;
if (argc != 2) {
std::cerr << "Unexpected arg count.\n";
std::cerr << "USAGE: svg_to_png <filename>\n";
return 1;
}
//! [load_file]
const auto* fileData = std::get_if<std::string>(&fileResult);
if (fileData == nullptr) {
std::cerr << FileReadErrorMessage(std::get<FileReadError>(fileResult)) << ": "
<< EscapeTerminalText(argv[1]) << "\n";
return 1; // Return an error code from main.
}
//! [load_file]
// Parse the SVG. Note that the lifetime of the vector must be longer than the returned
// SVGDocument, since it is referenced internally.
//! [parse]
// Allow data-name attributes without generating a warning.
options.disableUserAttributes = false;
ParseWarningSink warnings;
// warnings and options are optional, call ParseSVG(fileData) to use defaults and ignore warnings.
ParseResult<SVGDocument> maybeDocument = SVGParser::ParseSVG(*fileData, warnings, options);
//! [parse]
//! [handle_errors]
// ParseResult either contains an SVGDocument or an error.
if (maybeDocument.hasError()) {
std::ostringstream diagnostic;
diagnostic << maybeDocument.error();
std::cerr << "Parse Error: " << EscapeTerminalText(diagnostic.str()) << "\n";
return 1; // Return an error code from main.
}
std::cout << "Parsed successfully.\n";
if (warnings.hasWarnings()) {
std::cout << "Warnings:\n";
for (const ParseDiagnostic& w : warnings.warnings()) {
std::ostringstream diagnostic;
diagnostic << w;
std::cout << " " << EscapeTerminalText(diagnostic.str()) << "\n";
}
}
SVGDocument document = std::move(maybeDocument.result());
//! [handle_errors]
//! [set_canvas_size]
// Setting the canvas size is equivalent to resizing a browser window. Some SVGs may scale to fit,
// other ones may only render at their base size. To auto-size, either omit this call or invoke
// useAutomaticCanvasSize().
document.setCanvasSize(800, 600);
//! [set_canvas_size]
//! [render]
// Draw the document, store the image in-memory.
Renderer renderer;
renderer.draw(document);
std::cout << "Final size: " << renderer.width() << "x" << renderer.height() << "\n";
// Then save it out using the save API.
if (renderer.save("output.png")) {
std::cout << "Saved to file: " << std::filesystem::absolute("output.png") << "\n";
return 0;
} else {
std::cerr << "Failed to save to file: " << std::filesystem::absolute("output.png") << "\n";
return 1;
}
//! [render]
}
A parser result, which may contain a result of type T, or an error, or both.
Definition ParseResult.h:17
bool hasError() const noexcept
Returns true if this ParseResult contains an error.
Definition ParseResult.h:110
T & result() &
Returns the contained result.
Definition ParseResult.h:51
ParseDiagnostic & error() &
Returns the contained error.
Definition ParseResult.h:81
Represents a parsed SVG document containing a tree of SVGElement nodes.
Definition SVGDocument.h:58
void setCanvasSize(int width, int height)
Set the canvas (output image) size to a fixed width and height, in pixels.
Collects parse warnings during parsing.
Definition ParseWarningSink.h:29
const std::vector< ParseDiagnostic > & warnings() const
Access the collected warnings.
Definition ParseWarningSink.h:76
bool hasWarnings() const
Returns true if any warnings have been added.
Definition ParseWarningSink.h:79
Backend-agnostic renderer that resolves to the active build backend (Skia or tiny-skia).
Definition Renderer.h:82
int height() const override
Returns the rendered height in pixels.
bool save(const char *filename)
Saves the last rendered frame to a PNG file.
void draw(SVGDocument &document) override
Draws the SVG document using the active backend.
int width() const override
Returns the rendered width in pixels.
static ParseResult< SVGDocument > ParseSVG(std::string_view source, ParseWarningSink &warningSink, Options options={}, SVGDocument::Settings settings={}) noexcept
Parses an SVG XML document from a string (typically the contents of a .svg file).
static constexpr size_t kDefaultMaximumInputSize
Default maximum number of source or expanded SVG bytes accepted from untrusted input.
Definition SVGParser.h:20
Parsers for the SVG XML format, SVGParser, as well as individual parsers for SVG components,...
Donner SVG library, which can load, manipulate and render SVG files.
Top-level Donner namespace, which is split into different sub-namespaces such as donner::svg and donn...
std::string EscapeTerminalText(std::string_view text, bool preserveNewlines=false)
Escape untrusted bytes and terminal format controls while preserving printable UTF-8.
Definition TerminalEscape.h:13
FileReadResult ReadFileBounded(const std::filesystem::path &path, size_t maximumSize)
Open and read a regular file without allocating more than maximumSize bytes.
A diagnostic message from a parser, with severity, source range, and human-readable reason.
Definition ParseDiagnostic.h:31
Options to modify the parsing behavior.
Definition SVGParser.h:37
bool disableUserAttributes
By default, the parser will ignore user-defined attributes (only presentation attributes will be pars...
Definition SVGParser.h:65