Skip to main content

aylis_docview/
pdf.rs

1//! PDF pelo `hayro` (Rust puro): os tamanhos das páginas e cada página em RGBA, na escala
2//! pedida. Fora do navegador, uma thread por documento rasteriza as páginas (é a parte
3//! demorada); no navegador, sem threads, rasteriza na hora.
4
5use std::sync::Arc;
6
7use hayro::hayro_interpret::InterpreterSettings;
8use hayro::hayro_syntax::Pdf;
9use hayro::vello_cpu::color::palette::css::WHITE;
10use hayro::{PixmapSettings, RenderCache, RenderSettings};
11
12/// Tamanho de cada página, em pontos (1/72 de polegada).
13pub fn page_sizes(bytes: &[u8]) -> Result<Vec<(f32, f32)>, String> {
14    let pdf = Pdf::new(bytes.to_vec()).map_err(|e| format!("PDF: {e:?}"))?;
15    Ok(pdf.pages().iter().map(|p| p.render_dimensions()).collect())
16}
17
18/// O padrão da maior página rasterizada (64 megapixels).
19pub const MAX_PIXELS: f32 = 64_000_000.0;
20
21/// Rasteriza a página `index` com `scale` pixels por ponto: (largura, altura, RGBA).
22pub fn render_page(pdf: &Pdf, index: usize, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
23    render_page_with(pdf, index, scale, MAX_PIXELS)
24}
25
26/// Como [`render_page`], com no máximo `max_pixels`: o tamanho da página vem do arquivo
27/// (até 14.400 × 14.400 pontos), e uma página enorme com zoom viraria bilhões de pixels.
28/// Acima do limite a escala diminui (a página aparece menos nítida).
29pub fn render_page_with(pdf: &Pdf, index: usize, scale: f32, max_pixels: f32) -> Option<(u32, u32, Vec<u8>)> {
30    let page = pdf.pages().get(index)?;
31    let (w, h) = page.render_dimensions();
32    let side = aylis_core::image::MAX_IMAGE_SIDE as f32;
33    let fit_area = (max_pixels / (w * h * scale * scale).max(1.0)).sqrt();
34    let fit_side = side / (w.max(h) * scale).max(1.0);
35    let scale = scale * fit_area.min(fit_side).min(1.0);
36    let cache = RenderCache::new();
37    let settings = PixmapSettings { x_scale: scale, y_scale: scale, bg_color: WHITE };
38    let pixmap = hayro::render(page, &cache, &InterpreterSettings::default(), &RenderSettings::default(), &settings);
39    let (w, h) = (pixmap.width() as u32, pixmap.height() as u32);
40    // Fundo branco opaco: o RGBA pré-multiplicado é o mesmo que o comum.
41    Some((w, h, pixmap.data_as_u8_slice().to_vec()))
42}
43
44/// Uma página pronta: (página, escala em centésimos, largura, altura, RGBA).
45pub type Rendered = (usize, u32, u32, u32, Vec<u8>);
46
47/// Quem rasteriza as páginas de um documento.
48pub struct Renderer {
49    #[cfg(not(target_arch = "wasm32"))]
50    jobs: std::sync::mpsc::Sender<(usize, u32)>,
51    #[cfg(target_arch = "wasm32")]
52    pdf: Pdf,
53    #[cfg(target_arch = "wasm32")]
54    max_pixels: f32,
55}
56
57impl Renderer {
58    /// `done` recebe cada página pronta (de outra thread, fora do navegador). Cada página tem
59    /// no máximo `max_pixels`.
60    pub fn new(bytes: Arc<Vec<u8>>, max_pixels: f32, done: impl Fn(Rendered) + Send + 'static) -> Result<Self, String> {
61        #[cfg(not(target_arch = "wasm32"))]
62        {
63            let (tx, rx) = std::sync::mpsc::channel::<(usize, u32)>();
64            std::thread::Builder::new()
65                .name("aylis-pdf".into())
66                .spawn(move || {
67                    let Ok(pdf) = Pdf::new(bytes.as_ref().clone()) else { return };
68                    // O canal fecha quando o visualizador some: a thread sai.
69                    while let Ok((page, scale)) = rx.recv() {
70                        if let Some((w, h, rgba)) = render_page_with(&pdf, page, scale as f32 / 100.0, max_pixels) {
71                            done((page, scale, w, h, rgba));
72                        }
73                    }
74                })
75                .map_err(|e| e.to_string())?;
76            Ok(Self { jobs: tx })
77        }
78        #[cfg(target_arch = "wasm32")]
79        {
80            let _ = done;
81            Ok(Self { pdf: Pdf::new(bytes.as_ref().clone()).map_err(|e| format!("PDF: {e:?}"))?, max_pixels })
82        }
83    }
84
85    /// Pede a página `page` na escala `scale` (centésimos de pixel por ponto).
86    #[cfg(not(target_arch = "wasm32"))]
87    pub fn request(&self, page: usize, scale: u32) -> Option<Rendered> {
88        let _ = self.jobs.send((page, scale));
89        None
90    }
91
92    /// No navegador a página sai na hora.
93    #[cfg(target_arch = "wasm32")]
94    pub fn request(&self, page: usize, scale: u32) -> Option<Rendered> {
95        render_page_with(&self.pdf, page, scale as f32 / 100.0, self.max_pixels).map(|(w, h, rgba)| (page, scale, w, h, rgba))
96    }
97}