use printpdf::{
units::{Mm, Pt},
Op, ParsedFont, PdfDocument, PdfPage, PdfParseOptions, PdfSaveOptions, TextItem,
};
#[test]
fn test_custom_font_roundtrip() {
const ROBOTO_TTF: &[u8] = include_bytes!("../examples/assets/fonts/RobotoMedium.ttf");
let font = ParsedFont::from_bytes(ROBOTO_TTF, 0, &mut Vec::new()).unwrap();
let mut pdf = PdfDocument::new("Test");
let font_id = pdf.add_font(&font);
let russian_text = "Привет, как дела?";
let bytes = pdf
.with_pages(vec![PdfPage::new(
Mm(210.0),
Mm(210.0),
vec![
Op::StartTextSection,
Op::SetFont {
font: printpdf::ops::PdfFontHandle::External(font_id.clone()),
size: Pt(20.0),
},
Op::ShowText {
items: vec![TextItem::Text(russian_text.to_string())],
},
Op::EndTextSection,
],
)])
.save(&PdfSaveOptions::default(), &mut Vec::new());
let mut warnings = Vec::new();
let opts = PdfParseOptions {
fail_on_error: false,
};
let parsed_pdf = PdfDocument::parse(&bytes, &opts, &mut warnings).unwrap();
let font_resources = &parsed_pdf.resources.fonts.map;
assert!(!font_resources.is_empty(), "No font resources loaded");
assert!(!parsed_pdf.pages.is_empty(), "No pages in the parsed PDF");
let page = &parsed_pdf.pages[0];
let text_chunks = page.extract_text(&parsed_pdf.resources);
assert!(!text_chunks.is_empty(), "No text extracted from the page");
let extracted_text = text_chunks.join("");
const RUSSIAN_ORIGINAL: &str = "Привет, как дела?";
const RUSSIAN_SUBSETTED: &str =
"\n\u{6}\u{4}\u{c}\t\u{2}\u{1}\u{7}\u{b}\u{7}\u{1}\u{5}\u{c}\u{8}\u{b}\u{3}";
assert!(
extracted_text == RUSSIAN_ORIGINAL || extracted_text == RUSSIAN_SUBSETTED,
"Text should be either the original '{}' or subsetted '{:?}', but got '{:?}'",
RUSSIAN_ORIGINAL,
RUSSIAN_SUBSETTED,
extracted_text
);
}