kcode-html-to-pdf 0.1.1

A tiny self-contained HTML/CSS to PDF wrapper around Ironpress
Documentation
use kcode_html_to_pdf::{Font, render};

fn assert_plausible_pdf(pdf: &[u8]) {
    assert!(
        pdf.len() > 256,
        "PDF should contain more than a bare header"
    );
    assert!(pdf.starts_with(b"%PDF-"), "PDF header is missing");

    let last_non_whitespace = pdf
        .iter()
        .rposition(|byte| !byte.is_ascii_whitespace())
        .expect("PDF should not be empty");
    assert!(
        pdf[..=last_non_whitespace].ends_with(b"%%EOF"),
        "PDF trailer is missing"
    );
}

#[test]
fn renders_styled_self_contained_document() {
    let html = r#"<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <style>
    @page { size: 160mm 90mm; margin: 8mm; }
    * { box-sizing: border-box; }
    body { margin: 0; color: #f8fafc; font-family: sans-serif; }
    .page {
      min-height: 74mm;
      padding: 10mm;
      background: linear-gradient(135deg, #111827 0%, #2563eb 55%, #7c3aed 100%);
    }
    .hero {
      display: grid;
      grid-template-columns: 2fr 1fr;
      gap: 8mm;
      align-items: center;
    }
    .metrics { display: flex; gap: 4mm; }
    .metric { padding: 4mm; border: 1px solid #bfdbfe; border-radius: 3mm; }
    .next { break-before: page; page-break-before: always; background: #0f172a; }
  </style>
</head>
<body>
  <section class="page hero">
    <div>
      <h1>Self-contained partner brief</h1>
      <p>Grid, flexbox, gradients, paged media, and ordinary HTML.</p>
    </div>
    <div class="metrics">
      <div class="metric">12 MW</div>
      <div class="metric">2026</div>
    </div>
  </section>
  <section class="page next">
    <h2>Second page</h2>
    <p>This page is separated with a CSS page break.</p>
  </section>
</body>
</html>"#;

    let pdf = render(html, vec![]).expect("styled HTML should render");
    assert_plausible_pdf(&pdf);
}

#[test]
fn renders_with_supplied_ahem_font() {
    let html = r#"<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <style>
    @page { size: A4; margin: 20mm; }
    body { font-family: Ahem; font-size: 20pt; }
  </style>
</head>
<body><p>Ahem custom font smoke test</p></body>
</html>"#;

    let pdf = render(
        html,
        vec![Font {
            family: "Ahem".to_owned(),
            ttf: font_test_data::AHEM.to_vec(),
        }],
    )
    .expect("HTML using the supplied Ahem font should render");

    assert_plausible_pdf(&pdf);
}