This tutorial will guide you on how to use the library to convert a series of code files to code snapshot images.
We'll create a Rust project that reads multiple code files and generates a gallery of formatted code snapshots.
Ensure CodeSnap is installed. You can install the CLI for command line access or integrate it as a library in your project.
To install via Cargo:
cargo install codesnap-cli
Or, to add it as a library:
cargo add codesnap
Set up a directory with the code files you want to convert into snapshots. Make sure these files are well-formatted.
Create a new Rust project or add the following script to an existing one:
use codesnap::CodeSnap;
use codesnap::content::CodeBuilder;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let files = vec!["snippet1.rs", "snippet2.rs", "snippet3.rs"];
for file in files {
let code_content = std::fs::read_to_string(file)?;
let content = CodeBuilder::new()
.content(&code_content)
.language("rust")
.build()?;
let snapshot = CodeSnap::from_default_theme()
.content(content)
.build()?
.create_snapshot()?;
snapshot.save_as(format!("{}.png", file))?;
println!("Snapshot for {} created.", file);
}
Ok(())
}
Execute the script to produce snapshots for each code file in your directory:
cargo run
The PNG files will appear in your project's root folder.
Customize your snapshots through configuration files. Here's how to apply a JSON configuration:
CodeSnap::from_config("custom_configuration")?;
You can view more details on our Configuration page.