Skip to main content

oxpdf_wasm/
lib.rs

1use oxpdf::Document;
2use wasm_bindgen::prelude::*;
3
4fn to_js_error(err: oxpdf::Error) -> JsValue {
5    #[cfg(target_arch = "wasm32")]
6    {
7        js_sys::Error::new(&err.to_string()).into()
8    }
9    #[cfg(not(target_arch = "wasm32"))]
10    {
11        let _ = err;
12        JsValue::NULL
13    }
14}
15
16/// WebAssembly-compatible wrapper for an `oxpdf` document.
17#[wasm_bindgen]
18pub struct WasmDocument {
19    data: Vec<u8>,
20}
21
22#[wasm_bindgen]
23impl WasmDocument {
24    /// Constructs a new `WasmDocument` by validating and ingesting raw PDF byte data.
25    #[wasm_bindgen(constructor)]
26    pub fn new(data: &[u8]) -> Result<WasmDocument, JsValue> {
27        // Validate document integrity / xref structure upon ingestion
28        Document::load(data).map_err(to_js_error)?;
29        Ok(WasmDocument {
30            data: data.to_vec(),
31        })
32    }
33
34    /// Returns the total resolved page count of the document.
35    #[wasm_bindgen]
36    pub fn page_count(&self) -> Result<usize, JsValue> {
37        let doc = Document::load(&self.data).map_err(to_js_error)?;
38        doc.page_count().map_err(to_js_error)
39    }
40
41    /// Returns the array of indirect object IDs corresponding to document pages.
42    #[wasm_bindgen]
43    pub fn get_page_ids(&self) -> Result<Vec<u32>, JsValue> {
44        let doc = Document::load(&self.data).map_err(to_js_error)?;
45        doc.get_page_ids().map_err(to_js_error)
46    }
47
48    /// Extracts decoded text from a single page specified by its object ID.
49    #[wasm_bindgen]
50    pub fn extract_text(&self, page_id: u32) -> Result<String, JsValue> {
51        let doc = Document::load(&self.data).map_err(to_js_error)?;
52        doc.extract_text(page_id).map_err(to_js_error)
53    }
54
55    /// Extracts decoded text from all pages in sequence, returning a JavaScript array of strings.
56    #[wasm_bindgen]
57    pub fn extract_text_all(&self) -> Result<js_sys::Array, JsValue> {
58        let doc = Document::load(&self.data).map_err(to_js_error)?;
59        let pages = doc.extract_text_all().map_err(to_js_error)?;
60        let array = js_sys::Array::new();
61        for page_text in pages {
62            array.push(&JsValue::from_str(&page_text));
63        }
64        Ok(array)
65    }
66
67    /// Returns the total number of objects in the cross-reference table.
68    #[wasm_bindgen]
69    pub fn object_count(&self) -> usize {
70        match Document::load(&self.data) {
71            Ok(doc) => doc.object_count(),
72            Err(_) => 0,
73        }
74    }
75
76    /// Packs and compresses the document into an optimized object stream (`/ObjStm`),
77    /// returning the serialized PDF bytes.
78    #[wasm_bindgen]
79    pub fn pack(&self) -> Result<Vec<u8>, JsValue> {
80        let doc = Document::load(&self.data).map_err(to_js_error)?;
81        let mut output = Vec::new();
82        doc.write_packed(&mut output).map_err(to_js_error)?;
83        Ok(output)
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    const SAMPLE_PDF: &[u8] = b"%PDF-1.4\n\
921 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
932 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n\
943 0 obj\n<< /Type /Page /Parent 2 0 R /Contents 4 0 R >>\nendobj\n\
954 0 obj\n<< /Length 48 >>\nstream\n\
96BT /F1 12 Tf 72 712 Td (Hello WebAssembly) Tj ET\n\
97endstream\nendobj\n\
98trailer\n\
99<< /Size 5 /Root 1 0 R >>\n\
100startxref\n\
1010\n\
102%%EOF";
103
104    #[test]
105    fn test_wasm_document_lifecycle() {
106        let doc = match WasmDocument::new(SAMPLE_PDF) {
107            Ok(d) => d,
108            Err(_) => panic!("Failed to instantiate WasmDocument"),
109        };
110
111        assert_eq!(doc.object_count(), 4);
112
113        let page_count = match doc.page_count() {
114            Ok(c) => c,
115            Err(_) => panic!("Failed to get page_count"),
116        };
117        assert_eq!(page_count, 1);
118
119        let page_ids = match doc.get_page_ids() {
120            Ok(ids) => ids,
121            Err(_) => panic!("Failed to get get_page_ids"),
122        };
123        assert_eq!(page_ids, vec![3]);
124
125        let text = match doc.extract_text(3) {
126            Ok(t) => t,
127            Err(_) => panic!("Failed to extract_text"),
128        };
129        assert!(text.contains("Hello WebAssembly"));
130
131        let packed_bytes = match doc.pack() {
132            Ok(b) => b,
133            Err(_) => panic!("Failed to pack document"),
134        };
135        assert!(!packed_bytes.is_empty());
136        assert!(packed_bytes.starts_with(b"%PDF-1.5"));
137
138        let packed_doc = match WasmDocument::new(&packed_bytes) {
139            Ok(d) => d,
140            Err(_) => panic!("Failed to load packed document"),
141        };
142        assert_eq!(packed_doc.page_count().unwrap(), 1);
143    }
144
145    #[test]
146    fn test_wasm_document_invalid_pdf() {
147        let invalid_pdf = b"NOT A VALID PDF DATA";
148        assert!(WasmDocument::new(invalid_pdf).is_err());
149    }
150}