cairo-rs
| Language | Rust |
|---|---|
| License | MIT (cairo itself is LGPL-2.1 or MPL-1.1) |
| Repository | github.com/gtk-rs/gtk-rs-core (folder cairo) |
| Documentation | docs.rs/cairo-rs, PsSurface |
| Depends on | the cairo C library (system package) |
| Read / write | no / yes (PostScript Level 2 and 3, EPS) |
cairo-rs wraps cairo in safe Rust types. cairo::PsSurface is a PostScript output surface: create a Context on it, draw, and call show_page() for each page. The output is DSC-conforming PostScript with embedded font subsets.
The crate links to the system cairo library, so cairo must be installed with its development files. PostScript support is behind the ps cargo feature. cairo can’t read PostScript, and it turns transparency into embedded bitmaps.
Installation#
TOML
[dependencies]
cairo-rs = { version = "0.22", features = ["ps"] }
Shell
# Debian / Ubuntu
sudo apt install libcairo2-dev
# macOS
brew install cairo
On Windows, install cairo with vcpkg or MSYS2 and make sure pkg-config finds it.
Basic usage: write a two-page PostScript file#
Rust
use cairo::{Context, FontSlant, FontWeight, PsSurface};
use std::f64::consts::PI;
fn main() -> Result<(), cairo::Error> {
let surface = PsSurface::new(595.0, 842.0, "out.ps")?; // A4 in points
let cr = Context::new(&surface)?;
// page 1
cr.select_font_face("Sans", FontSlant::Normal, FontWeight::Bold);
cr.set_font_size(24.0);
cr.move_to(72.0, 72.0); // origin is top-left
cr.show_text("Hello, PostScript")?;
cr.set_source_rgb(0.2, 0.4, 0.8);
cr.rectangle(72.0, 120.0, 300.0, 150.0);
cr.fill()?;
cr.show_page()?;
// page 2
cr.set_source_rgb(0.8, 0.1, 0.1);
cr.set_line_width(4.0);
cr.arc(297.5, 421.0, 100.0, 0.0, 2.0 * PI);
cr.stroke()?;
cr.show_page()?;
drop(cr);
surface.finish(); // writes the trailer and closes the file
surface.status()
}
How to change the page size for one page#
Rust
surface.set_size(842.0, 595.0); // landscape A4, before drawing the page
How to add DSC comments#
Rust
let surface = PsSurface::new(842.0, 1191.0, "out.ps")?;
surface.dsc_comment("%%Title: Quarterly report");
surface.dsc_begin_setup();
surface.dsc_comment("%%IncludeFeature: *MediaColor White");
surface.begin_page_setup();
surface.dsc_comment("%%IncludeFeature: *PageSize A3");
How to write PostScript Level 2#
Rust
use cairo::PsLevel;
surface.restrict(PsLevel::_2);
for level in PsSurface::levels() {
println!("supported: {:?}", level);
}
How to write PostScript to stdout or any writer#
Rust
let surface = PsSurface::for_stream(595.0, 842.0, std::io::stdout())?;
for_stream takes any Write + 'static.
Tips#
surface.set_eps(true)writes Encapsulated PostScript; see cairo-rs for EPS.- Draw a PNG with
cairo::ImageSurface::create_from_png(&mut file)(featurepng) andcr.set_source_surface(&img, x, y)?; cr.paint()?.