//! A paper made from nothing: a one-page PDF of a title and a few lines in //! Helvetica, so a synthetic file has bytes a phone opens in its viewer. A PDF //! this plain needs no library — five objects, a content stream and the table //! of where each object starts. /// `(` `)` and `\` are the three characters a PDF string has to escape; the /// rest of what this module is handed is plain ASCII. fn escaped(text: &str) -> String { text.chars() .filter(char::is_ascii) .flat_map(|c| match c { '(' | ')' | '\\' => vec!['\\', c], c => vec![c], }) .collect() } /// An A4 page: `title` large at the top, each of `lines` below it. pub fn pdf(title: &str, lines: &[&str]) -> Vec { let mut stream = format!("BT /F1 20 Tf 72 770 Td ({}) Tj ET\nBT /F1 12 Tf 14 TL 72 730 Td", escaped(title)); for line in lines { stream.push_str(&format!(" ({}) Tj T*", escaped(line))); } stream.push_str(" ET\n"); let objects = [ "<< /Type /Catalog /Pages 2 0 R >>".to_string(), "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>" .to_string(), "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(), format!("<< /Length {} >>\nstream\n{stream}endstream", stream.len()), ]; let mut out = String::from("%PDF-1.4\n"); let mut starts = Vec::with_capacity(objects.len()); for (n, object) in objects.iter().enumerate() { starts.push(out.len()); out.push_str(&format!("{} 0 obj\n{object}\nendobj\n", n + 1)); } let xref = out.len(); out.push_str(&format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1)); for start in starts { out.push_str(&format!("{start:010} 00000 n \n")); } out.push_str(&format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1)); out.into_bytes() }