use anyhow::{anyhow, Context, Result};
use genpdf::elements::{Break, Image, PageBreak, Paragraph, Text};
use genpdf::fonts;
use genpdf::style::Style;
use genpdf::{Document, Element as _, SimplePageDecorator};
use image::DynamicImage;
use libhardcopy::{HardCopy, HardCopySectionContent};
const FONT_NAMES: &[&str] = &["LiberationMono", "NotoMono"];
const SYSTEM_FONT_DIRS: &[&str] = &[
"/usr/share/fonts/truetype/liberation2",
"/usr/share/fonts/truetype/liberation",
"/usr/share/fonts/liberation-fonts",
"/usr/share/fonts/truetype/noto",
"/usr/local/share/fonts",
];
fn candidate_dirs() -> Vec<String> {
let mut dirs: Vec<String> = Vec::new();
let xdg_data_home = std::env::var("XDG_DATA_HOME").ok().or_else(|| {
std::env::var("HOME")
.ok()
.map(|h| format!("{}/{}", h, ".local/share"))
});
if let Some(data_home) = xdg_data_home {
dirs.push(format!("{}/fonts", data_home));
}
if let Ok(home) = std::env::var("HOME") {
dirs.push(format!("{}/.fonts", home));
}
for &sys in SYSTEM_FONT_DIRS {
dirs.push(sys.to_string());
}
dirs
}
type FontFamily = genpdf::fonts::FontFamily<genpdf::fonts::FontData>;
fn try_load_from_dir(dir: &str, name: &str) -> Option<FontFamily> {
if let Ok(f) = fonts::from_files(dir, name, None) {
return Some(f);
}
let regular_path = format!("{}/{}-Regular.ttf", dir, name);
let data = genpdf::fonts::FontData::load(®ular_path, None).ok()?;
Some(genpdf::fonts::FontFamily {
regular: data.clone(),
bold: data.clone(),
italic: data.clone(),
bold_italic: data,
})
}
fn load_font(font_dir: Option<&str>, font_name: Option<&str>) -> Result<FontFamily> {
let names: Vec<&str> = match font_name {
Some(n) => vec![n],
None => FONT_NAMES.to_vec(),
};
if let Some(dir) = font_dir {
for &name in &names {
if let Some(f) = try_load_from_dir(dir, name) {
return Ok(f);
}
}
return Err(anyhow!(
"Font '{}' not found in '{}'. \
Expected at least '{}/{}-Regular.ttf'.",
names.join("' or '"),
dir,
dir,
names[0],
));
}
let mut tried = Vec::new();
for dir in candidate_dirs() {
for &name in &names {
if let Some(f) = try_load_from_dir(&dir, name) {
return Ok(f);
}
tried.push(format!(" {}/{}-Regular.ttf", dir, name));
}
}
Err(anyhow!(
"No supported monospace font found. Tried:\n{}\n\
Install liberation-fonts or noto-fonts, or pass --font-dir DIR and/or --font-name NAME.",
tried.join("\n")
))
}
pub fn render(
hardcopy: &HardCopy,
checksum: &str,
font_dir: Option<&str>,
font_name: Option<&str>,
) -> Result<Vec<u8>> {
let version = env!("CARGO_PKG_VERSION");
let date = chrono::Local::now().format("%Y-%m-%d").to_string();
let font_family = load_font(font_dir, font_name)?;
let mut doc = Document::new(font_family);
doc.set_title(format!("hardcopy v{}", version));
doc.set_minimal_conformance();
doc.set_line_spacing(1.25);
let mut decorator = SimplePageDecorator::new();
decorator.set_margins(10);
doc.set_page_decorator(decorator);
doc.push(
Paragraph::new(format!("hardcopy v{}", version))
.styled(Style::new().bold().with_font_size(14)),
);
doc.push(Text::new(format!("Date: {}", date)));
doc.push(Text::new(format!("SHA-256: {}", checksum)));
doc.push(Break::new(1));
let mut qr_slot = 0usize;
for section in &hardcopy.sections {
match §ion.content {
HardCopySectionContent::Words(lines) => {
doc.push(
Paragraph::new(section.name.clone())
.styled(Style::new().bold().with_font_size(11)),
);
doc.push(Break::new(0.5));
for line in lines {
doc.push(Text::new(line.clone()));
}
doc.push(Break::new(1));
}
HardCopySectionContent::Bytes(png) => {
if qr_slot == 0 {
doc.push(PageBreak::new());
} else {
doc.push(Break::new(2));
}
doc.push(
Paragraph::new(section.name.clone())
.styled(Style::new().bold().with_font_size(11)),
);
doc.push(Break::new(0.5));
let img = image::load_from_memory(png).context("Failed to decode QR code PNG")?;
let element = Image::from_dynamic_image(DynamicImage::ImageLuma8(img.into_luma8()))
.context("Failed to create PDF image element")?
.with_alignment(genpdf::Alignment::Center);
doc.push(element);
qr_slot = (qr_slot + 1) % 2;
}
}
}
doc.push(Break::new(1));
doc.push(Text::new(format!("SHA-256: {}", checksum)));
let mut buf: Vec<u8> = Vec::new();
doc.render(&mut buf).context("Failed to render PDF")?;
Ok(buf)
}