Skip to content

Commit

Permalink
Add the ability to list the fonts detected
Browse files Browse the repository at this point in the history
Adds a new CLI flag allowing the user to just list the fonts which are
detected on the system.

Signed-off-by: Rémy Greinhofer <remy.greinhofer@gmail.com>
  • Loading branch information
rgreinho committed Nov 15, 2023
1 parent a405a57 commit 9256a71
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
5 changes: 4 additions & 1 deletion crates/svg2pdf-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ use clap::Parser;
#[clap(about, version)]
pub struct Args {
/// Path to read SVG file from.
pub input: PathBuf,
pub input: Option<PathBuf>,
/// Path to write PDF file to.
pub output: Option<PathBuf>,
/// The number of SVG pixels per PDF points.
#[clap(long, default_value = "72.0")]
pub dpi: f32,
/// List the fonts available on the system.
#[clap(long)]
pub list_fonts: bool,
}
30 changes: 24 additions & 6 deletions crates/svg2pdf-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,24 @@ fn main() {
fn run() -> Result<(), String> {
let args = args::Args::parse();

let name =
Path::new(args.input.file_name().ok_or("Input path does not point to a file")?);
// Prepare the font database.
let mut fontdb = fontdb::Database::new();
fontdb.load_system_fonts();

// List the fonts and exit.
if args.list_fonts {
list_fonts(&fontdb);
return Ok(());
}

// Or convert the file.
let input = args.input.expect("Input path must be specified");
let name = Path::new(input.file_name().ok_or("Input path does not point to a file")?);
let output = args.output.unwrap_or_else(|| name.with_extension("pdf"));

let svg =
std::fs::read_to_string(&args.input).map_err(|_| "Failed to load SVG file")?;
let svg = std::fs::read_to_string(&input).map_err(|_| "Failed to load SVG file")?;

let options = usvg::Options::default();
let mut fontdb = fontdb::Database::new();
fontdb.load_system_fonts();

let mut tree = usvg::Tree::from_str(&svg, &options).map_err(|err| err.to_string())?;
tree.convert_text(&fontdb);
Expand All @@ -54,3 +62,13 @@ fn print_error(msg: &str) -> io::Result<()> {
w.reset()?;
writeln!(w, ": {msg}.")
}

fn list_fonts(fontdb: &fontdb::Database) {
let mut faces: Vec<String> =
fontdb.faces().map(|f| f.post_script_name.clone()).collect();
faces.sort();
println!("Fonts found: {}", faces.len());
for face in faces {
println!("{face}")
}
}

0 comments on commit 9256a71

Please sign in to comment.