micropdf 0.17.0

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! FFI exports for HTML to PDF conversion (v2 engine)
//!
//! Provides C-compatible functions for converting HTML/CSS to PDF using
//! the v2 rendering engine.  Function signatures intentionally differ
//! from the old v1 FFI — this is a breaking change as documented in
//! the design spec.

use crate::enhanced::html_to_pdf::{
    HtmlToPdfOptions, Margins, PageSize, html_file_to_pdf, html_to_pdf,
};
use crate::ffi::Handle;
use std::ffi::CStr;
use std::os::raw::c_char;

// ============================================================================
// Handle Types
// ============================================================================

/// HTML to PDF options handle
pub type HtmlToPdfOptionsHandle = Handle;

// ============================================================================
// Error Codes
// ============================================================================

/// Success
pub const MP_HTML_SUCCESS: i32 = 0;
/// Invalid parameter
pub const MP_HTML_ERROR_INVALID_PARAM: i32 = -1;
/// Conversion failed
pub const MP_HTML_ERROR_CONVERSION: i32 = -2;
/// File not found
pub const MP_HTML_ERROR_NOT_FOUND: i32 = -3;
/// IO error
pub const MP_HTML_ERROR_IO: i32 = -4;

// ============================================================================
// Page Size Constants
// ============================================================================

/// Letter page size (612x792 pt)
pub const MP_PAGE_SIZE_LETTER: i32 = 0;
/// Legal page size (612x1008 pt)
pub const MP_PAGE_SIZE_LEGAL: i32 = 1;
/// A3 page size
pub const MP_PAGE_SIZE_A3: i32 = 2;
/// A4 page size (595x842 pt)
pub const MP_PAGE_SIZE_A4: i32 = 3;
/// A5 page size
pub const MP_PAGE_SIZE_A5: i32 = 4;

// ============================================================================
// Options Functions
// ============================================================================

/// Create default HTML to PDF options
///
/// # Returns
/// Handle to the options, or 0 on failure
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_create() -> HtmlToPdfOptionsHandle {
    let options = Box::new(HtmlToPdfOptions::default());
    Box::into_raw(options) as Handle
}

/// Free HTML to PDF options
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_free(handle: HtmlToPdfOptionsHandle) {
    if handle != 0 {
        unsafe {
            let _ = Box::from_raw(handle as *mut HtmlToPdfOptions);
        }
    }
}

/// Set page size
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_set_page_size(
    handle: HtmlToPdfOptionsHandle,
    page_size: i32,
) -> i32 {
    if handle == 0 {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let options = unsafe { &mut *(handle as *mut HtmlToPdfOptions) };

    let size = match page_size {
        MP_PAGE_SIZE_LETTER => PageSize::Letter,
        MP_PAGE_SIZE_LEGAL => PageSize::Legal,
        MP_PAGE_SIZE_A3 => PageSize::A3,
        MP_PAGE_SIZE_A4 => PageSize::A4,
        MP_PAGE_SIZE_A5 => PageSize::A5,
        _ => return MP_HTML_ERROR_INVALID_PARAM,
    };

    let (w, h) = size.dimensions();
    options.page_width = w;
    options.page_height = h;

    MP_HTML_SUCCESS
}

/// Set custom page size in points
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_set_page_size_custom(
    handle: HtmlToPdfOptionsHandle,
    width: f32,
    height: f32,
) -> i32 {
    if handle == 0 {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let options = unsafe { &mut *(handle as *mut HtmlToPdfOptions) };
    options.page_width = width;
    options.page_height = height;

    MP_HTML_SUCCESS
}

/// Set page margins in points
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_set_margins(
    handle: HtmlToPdfOptionsHandle,
    top: f32,
    right: f32,
    bottom: f32,
    left: f32,
) -> i32 {
    if handle == 0 {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let options = unsafe { &mut *(handle as *mut HtmlToPdfOptions) };
    options.margins = Margins {
        top,
        right,
        bottom,
        left,
    };

    MP_HTML_SUCCESS
}

/// Set default font family
///
/// # Safety
/// - `handle` must be a valid options handle
/// - `family` must be a valid null-terminated UTF-8 string
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_set_default_font(
    handle: HtmlToPdfOptionsHandle,
    family: *const c_char,
) -> i32 {
    if handle == 0 || family.is_null() {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let options = unsafe { &mut *(handle as *mut HtmlToPdfOptions) };
    let family_str = unsafe { CStr::from_ptr(family) }.to_string_lossy();
    options.default_font_family = family_str.to_string();

    MP_HTML_SUCCESS
}

/// Set default font size in points
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_set_default_font_size(
    handle: HtmlToPdfOptionsHandle,
    size: f32,
) -> i32 {
    if handle == 0 {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let options = unsafe { &mut *(handle as *mut HtmlToPdfOptions) };
    options.default_font_size = size;

    MP_HTML_SUCCESS
}

// ============================================================================
// Conversion Functions
// ============================================================================

/// Convert HTML string to PDF
///
/// # Safety
/// - `html` must be a valid null-terminated UTF-8 string
/// - `output_path` must be a valid null-terminated UTF-8 string
/// - `options` must be a valid options handle, or 0 for defaults
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_to_pdf(
    html: *const c_char,
    output_path: *const c_char,
    options: HtmlToPdfOptionsHandle,
) -> i32 {
    if html.is_null() || output_path.is_null() {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let html_str = unsafe { CStr::from_ptr(html) }.to_string_lossy();
    let output_str = unsafe { CStr::from_ptr(output_path) }.to_string_lossy();

    let opts = if options == 0 {
        HtmlToPdfOptions::default()
    } else {
        unsafe { &*(options as *const HtmlToPdfOptions) }.clone()
    };

    match html_to_pdf(&html_str, &output_str, &opts) {
        Ok(()) => MP_HTML_SUCCESS,
        Err(_) => MP_HTML_ERROR_CONVERSION,
    }
}

/// Convert HTML file to PDF
///
/// # Safety
/// - `html_path` must be a valid null-terminated UTF-8 string
/// - `output_path` must be a valid null-terminated UTF-8 string
/// - `options` must be a valid options handle, or 0 for defaults
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_file_to_pdf(
    html_path: *const c_char,
    output_path: *const c_char,
    options: HtmlToPdfOptionsHandle,
) -> i32 {
    if html_path.is_null() || output_path.is_null() {
        return MP_HTML_ERROR_INVALID_PARAM;
    }

    let html_path_str = unsafe { CStr::from_ptr(html_path) }.to_string_lossy();
    let output_str = unsafe { CStr::from_ptr(output_path) }.to_string_lossy();

    let opts = if options == 0 {
        HtmlToPdfOptions::default()
    } else {
        unsafe { &*(options as *const HtmlToPdfOptions) }.clone()
    };

    match html_file_to_pdf(&html_path_str, &output_str, &opts) {
        Ok(()) => MP_HTML_SUCCESS,
        Err(e) => {
            if e.to_string().contains("not found") {
                MP_HTML_ERROR_NOT_FOUND
            } else {
                MP_HTML_ERROR_CONVERSION
            }
        }
    }
}

/// Get page width from options
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_get_page_width(handle: HtmlToPdfOptionsHandle) -> f32 {
    if handle == 0 {
        return 0.0;
    }
    let options = unsafe { &*(handle as *const HtmlToPdfOptions) };
    options.page_width
}

/// Get page height from options
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_get_page_height(handle: HtmlToPdfOptionsHandle) -> f32 {
    if handle == 0 {
        return 0.0;
    }
    let options = unsafe { &*(handle as *const HtmlToPdfOptions) };
    options.page_height
}

/// Get content width (page width minus margins)
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_get_content_width(handle: HtmlToPdfOptionsHandle) -> f32 {
    if handle == 0 {
        return 0.0;
    }
    let options = unsafe { &*(handle as *const HtmlToPdfOptions) };
    options.content_width()
}

/// Get content height (page height minus margins)
///
/// # Safety
/// - `handle` must be a valid options handle
#[unsafe(no_mangle)]
pub extern "C" fn mp_html_options_get_content_height(handle: HtmlToPdfOptionsHandle) -> f32 {
    if handle == 0 {
        return 0.0;
    }
    let options = unsafe { &*(handle as *const HtmlToPdfOptions) };
    options.content_height()
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::CString;

    #[test]
    fn test_options_create_free() {
        let handle = mp_html_options_create();
        assert_ne!(handle, 0);
        mp_html_options_free(handle);
    }

    #[test]
    fn test_options_page_size() {
        let handle = mp_html_options_create();
        assert_eq!(
            mp_html_options_set_page_size(handle, MP_PAGE_SIZE_A4),
            MP_HTML_SUCCESS
        );

        let width = mp_html_options_get_page_width(handle);
        assert!((width - 595.28).abs() < 0.01);

        mp_html_options_free(handle);
    }

    #[test]
    fn test_options_margins() {
        let handle = mp_html_options_create();
        assert_eq!(
            mp_html_options_set_margins(handle, 72.0, 72.0, 72.0, 72.0),
            MP_HTML_SUCCESS
        );

        let content_width = mp_html_options_get_content_width(handle);
        assert!((content_width - (612.0 - 144.0)).abs() < 0.01);

        mp_html_options_free(handle);
    }

    #[test]
    fn test_options_default_font() {
        let handle = mp_html_options_create();
        let font = CString::new("Times-Roman").unwrap();
        assert_eq!(
            mp_html_options_set_default_font(handle, font.as_ptr()),
            MP_HTML_SUCCESS
        );
        mp_html_options_free(handle);
    }

    #[test]
    fn test_options_default_font_size() {
        let handle = mp_html_options_create();
        assert_eq!(
            mp_html_options_set_default_font_size(handle, 14.0),
            MP_HTML_SUCCESS
        );
        mp_html_options_free(handle);
    }

    #[test]
    fn test_html_to_pdf_basic() {
        let html = CString::new("<html><body><h1>Hello</h1></body></html>").unwrap();
        let output = CString::new("/tmp/test_html_v2_output.pdf").unwrap();

        let result = mp_html_to_pdf(html.as_ptr(), output.as_ptr(), 0);
        assert_eq!(result, MP_HTML_SUCCESS);

        // Cleanup
        let _ = std::fs::remove_file("/tmp/test_html_v2_output.pdf");
    }

    #[test]
    fn test_null_params() {
        assert_eq!(
            mp_html_options_set_page_size(0, MP_PAGE_SIZE_A4),
            MP_HTML_ERROR_INVALID_PARAM
        );
        assert_eq!(
            mp_html_to_pdf(std::ptr::null(), std::ptr::null(), 0),
            MP_HTML_ERROR_INVALID_PARAM
        );
    }

    #[test]
    fn test_options_free_null() {
        mp_html_options_free(0);
    }

    #[test]
    fn test_options_invalid_page_size() {
        let handle = mp_html_options_create();
        assert_eq!(
            mp_html_options_set_page_size(handle, 99),
            MP_HTML_ERROR_INVALID_PARAM
        );
        mp_html_options_free(handle);
    }

    #[test]
    fn test_options_set_page_size_custom_invalid() {
        assert_eq!(
            mp_html_options_set_page_size_custom(0, 612.0, 792.0),
            MP_HTML_ERROR_INVALID_PARAM
        );
    }

    #[test]
    fn test_options_set_margins_invalid() {
        assert_eq!(
            mp_html_options_set_margins(0, 72.0, 72.0, 72.0, 72.0),
            MP_HTML_ERROR_INVALID_PARAM
        );
    }

    #[test]
    fn test_options_all_page_sizes() {
        let handle = mp_html_options_create();
        assert_eq!(
            mp_html_options_set_page_size(handle, MP_PAGE_SIZE_LETTER),
            MP_HTML_SUCCESS
        );
        assert_eq!(
            mp_html_options_set_page_size(handle, MP_PAGE_SIZE_LEGAL),
            MP_HTML_SUCCESS
        );
        assert_eq!(
            mp_html_options_set_page_size(handle, MP_PAGE_SIZE_A3),
            MP_HTML_SUCCESS
        );
        assert_eq!(
            mp_html_options_set_page_size(handle, MP_PAGE_SIZE_A5),
            MP_HTML_SUCCESS
        );
        mp_html_options_free(handle);
    }
}