1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#![doc = include_str!("../README.md")]

pub mod bindgen {
    #![allow(non_upper_case_globals)]
    #![allow(non_camel_case_types)]
    #![allow(non_snake_case)]
    include!("bindgen.rs");
}

pub mod bindings;
pub mod bitmap;
pub mod bitmap_config;
pub mod document;
pub mod page;
pub mod pdfium;

use crate::bindgen::{
    FPDF_ERR_FILE, FPDF_ERR_FORMAT, FPDF_ERR_PAGE, FPDF_ERR_PASSWORD, FPDF_ERR_SECURITY,
    FPDF_ERR_UNKNOWN,
};

// Conditional compilation is used to compile different implementations of
// the PdfiumLibraryBindings trait depending on whether we are compiling to a
// WASM module or to a native shared library.

#[cfg(not(target_arch = "wasm32"))]
mod native;

#[cfg(target_arch = "wasm32")]
mod wasm;

pub type PdfPageIndex = u16;
pub type PdfPoints = f32;

#[derive(Debug)]
pub enum PdfiumInternalError {
    Unknown = FPDF_ERR_UNKNOWN as isize,
    FileError = FPDF_ERR_FILE as isize,
    FormatError = FPDF_ERR_FORMAT as isize,
    PasswordError = FPDF_ERR_PASSWORD as isize,
    SecurityError = FPDF_ERR_SECURITY as isize,
    PageError = FPDF_ERR_PAGE as isize,
}

#[derive(Debug)]
pub enum PdfiumError {
    DynamicLibraryLoadingNotSupportedOnWASM,
    #[cfg(not(target_arch = "wasm32"))]
    LoadLibraryError(libloading::Error),
    PageIndexOutOfBounds,
    UnknownBitmapFormat,
    PdfiumLibraryInternalError(PdfiumInternalError),
}

#[cfg(test)]
pub mod tests {
    use crate::bitmap::PdfBitmapRotation;
    use crate::bitmap_config::PdfBitmapConfig;
    use crate::pdfium::Pdfium;
    use image::ImageFormat;

    #[test]
    fn test() {
        let bindings = Pdfium::bind_to_library(Pdfium::pdfium_platform_library_name_at_path("./"))
            .or_else(|_| Pdfium::bind_to_system_library());

        assert!(bindings.is_ok());

        let render_config = PdfBitmapConfig::new()
            .set_target_width(2000)
            .set_maximum_height(2000)
            .rotate_if_landscape(PdfBitmapRotation::Degrees90, true);

        Pdfium::new(bindings.unwrap())
            .load_pdf_from_file("./test/test.pdf", None)
            .unwrap()
            .pages()
            .for_each(|page| {
                let result = page
                    .get_bitmap_with_config(&render_config)
                    .unwrap()
                    .as_image()
                    .as_bgra8()
                    .unwrap()
                    .save_with_format(format!("test-page-{}.jpg", page.index()), ImageFormat::Jpeg);

                assert!(result.is_ok());
            });
    }
}