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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
#![warn(missing_docs)]
use crate::error::Error;
use crate::page::Page;
use crate::outline::Outline;
use crate::Font;
use crate::encoder::Encoder;
use crate::destination::Destination;
use crate::image::Image;
use bitflags::bitflags;
use std::ffi::CString;
use std::convert::TryInto;
/// Page label style.
#[derive(Debug)]
pub enum PageNumStyle {
/// Page label is displayed by Arabic numerals.
Decimal,
/// Page label is displayed by Uppercase roman numerals.
UpperRoman,
/// Page label is displayed by Lowercase roman numerals.
LowerRoman,
/// Page label is displayed by Uppercase letters (using A to Z).
UpperLetters,
/// Page label is displayed by Lowercase letters (using a to Z).
LowerLetters,
}
bitflags! {
/// The flags specifying which type of contents should be compressed.
pub struct CompressionMode: u32 {
/// All contents are not compressed.
const NONE = 0x00;
/// Compress the contents stream of the page.
const TEXT = 0x01;
/// Compress the streams of the image objects.
const IMAGE = 0x02;
/// Other stream datas (fonts, cmaps and so on) are compressed.
const METADATA = 0x04;
/// All stream datas are compressed. (The same as `CompressionMode::Text | CompressionMode::Image | CompressionMode::Metadata`)
const ALL = Self::TEXT.bits | Self::IMAGE.bits | Self::METADATA.bits;
}
}
/// Page display style.
#[derive(Debug)]
pub enum PageMode {
/// Display the document with neither outline nor thumbnail.
None,
/// Display the document with outline pain.
Outline,
/// Display the document with thumbnail pain.
Thumbs,
/// Display the document with full screen mode.
FullScreen,
}
/// Page layout style.
#[derive(Debug)]
pub enum PageLayout {
/// Only one page is displayed.
Single,
/// Display the pages in one column.
OneColumn,
/// Display the pages in two column. The page of the odd number is displayed left.
TwoColumnLeft,
/// Display the pages in two column. The page of the odd number is displayed right.
TwoColumnRight,
}
// onerrorのクロージャをBoxで持ちたいためInnerを別にしている。
// TODO: onerrorは必要か?
struct DocumentInner {
onerror: Box<dyn Fn(Error)>,
last_errno: libharu_sys::HPDF_STATUS,
last_detailno: libharu_sys::HPDF_STATUS,
}
/// PDF Document handle type.
///
/// The document handle is a handle to operate a document object.
pub struct Document {
doc: libharu_sys::HPDF_Doc,
#[allow(dead_code)]
inner: Box<DocumentInner>,
}
impl Document {
/// Create a new instance of document.
pub fn new(onerror: impl Fn(Error) + 'static) -> anyhow::Result<Self>
{
let onerror = Box::new(onerror);
let mut inner = Box::new(DocumentInner{onerror, last_errno: 0, last_detailno: 0});
let doc = unsafe {
libharu_sys::HPDF_New(
onerror_callback,
std::mem::transmute(inner.as_mut()),
)
};
if doc == std::ptr::null_mut() {
anyhow::bail!("HPDF_New() failed");
}
Ok(Self { doc, inner })
}
#[inline]
pub(crate) fn handle(&self) -> libharu_sys::HPDF_Doc {
self.doc
}
/// Create a new page and adds it after the last page of a document.
pub fn add_page(&self) -> anyhow::Result<Page> {
let page = unsafe {
libharu_sys::HPDF_AddPage(self.handle())
};
if page == std::ptr::null_mut() {
anyhow::bail!("HPDF_AddPage failed");
}
Ok(Page::new(self, page))
}
/// Return the current page object.
pub fn current_page(&self) -> anyhow::Result<Page> {
let page = unsafe {
libharu_sys::HPDF_GetCurrentPage(self.handle())
};
if page == std::ptr::null_mut() {
anyhow::bail!("HPDF_GetCurrentPage failed");
}
Ok(Page::new(self, page))
}
/// Set how the document should be displayed.
pub fn set_page_mode(&self, mode: PageMode) -> anyhow::Result<()> {
let mode = match mode {
PageMode::None => libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_USE_NONE,
PageMode::Outline => libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_USE_OUTLINE,
PageMode::Thumbs => libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_USE_THUMBS,
PageMode::FullScreen => libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_FULL_SCREEN,
};
let status = unsafe {
libharu_sys::HPDF_SetPageMode(self.handle(), mode)
};
if status != 0 {
anyhow::bail!("HPDF_SetPageMode failed (status={})", status);
}
Ok(())
}
/// Get how the document should be displayed.
pub fn page_mode(&self) -> anyhow::Result<PageMode> {
let mode = unsafe {
libharu_sys::HPDF_GetPageMode(self.handle())
};
let mode = match mode {
libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_USE_NONE => PageMode::None,
libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_USE_OUTLINE => PageMode::Outline,
libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_USE_THUMBS => PageMode::Thumbs,
libharu_sys::HPDF_PageMode::HPDF_PAGE_MODE_FULL_SCREEN => PageMode::FullScreen,
_ => {
anyhow::bail!("HPDF_GetPageMode failed");
}
};
Ok(mode)
}
/// Create a new page and inserts it just before the specified page.
pub fn insert_page(&self, target: &Page) -> anyhow::Result<Page> {
let page = unsafe {
libharu_sys::HPDF_InsertPage(self.handle(), target.handle())
};
if page == std::ptr::null_mut() {
anyhow::bail!("HPDF_InsertPage failed");
}
Ok(Page::new(self, page))
}
/// Gets the handle of a corresponding font object by specified name and encoding.
pub fn font(&self, font_name: &str, encoding_name: Option<&str>) -> anyhow::Result<Font> {
let font_name = CString::new(font_name)?;
let encoding_name = match encoding_name {
Some(s) => Some(CString::new(s)?),
None => None,
};
let font = unsafe {
libharu_sys::HPDF_GetFont(self.handle(),
std::mem::transmute(font_name.as_ptr()),
match encoding_name {
Some(ref s) => std::mem::transmute(s.as_ptr()),
None => std::ptr::null_mut(),
})
};
if font == std::ptr::null_mut() {
anyhow::bail!("HPDF_GetFont failed");
}
Ok(Font::new(self, font))
}
/// Add a page labeling range for the document.
pub fn add_page_label(&self, page_num: usize, style: PageNumStyle, first_page: usize, prefix: Option<&str>) -> anyhow::Result<()> {
let style = match style {
PageNumStyle::Decimal => libharu_sys::HPDF_PageNumStyle::HPDF_PAGE_NUM_STYLE_DECIMAL,
PageNumStyle::UpperRoman => libharu_sys::HPDF_PageNumStyle::HPDF_PAGE_NUM_STYLE_UPPER_ROMAN,
PageNumStyle::LowerRoman => libharu_sys::HPDF_PageNumStyle::HPDF_PAGE_NUM_STYLE_LOWER_ROMAN,
PageNumStyle::UpperLetters => libharu_sys::HPDF_PageNumStyle::HPDF_PAGE_NUM_STYLE_UPPER_LETTERS,
PageNumStyle::LowerLetters => libharu_sys::HPDF_PageNumStyle::HPDF_PAGE_NUM_STYLE_LOWER_LETTERS,
};
let page_num = page_num.try_into()?;
let first_page = first_page.try_into()?;
let prefix = match prefix {
Some(s) => CString::new(s)?,
None => CString::new("")?,
};
let status = unsafe {
libharu_sys::HPDF_AddPageLabel(self.handle(), page_num, style, first_page, std::mem::transmute(prefix.as_ptr()))
};
if status != 0 {
anyhow::bail!("HPDF_AddPageLabelf failed (status = {})", status);
}
Ok(())
}
/// Enable Japanese fonts. After the method invoked, an application can use the following Japanese fonts.
/// * MS-mincho
/// * MS-mincho,Bold
/// * MS-mincho,Bold
/// * MS-mincho,Italic
/// * MS-mincho,BoldItalic
/// * MS-Gothic
/// * MS-Gothic,Bold
/// * MS-Gothic,Italic
/// * MS-Gothic,BoldItalic
/// * MS-Pmincho
/// * MS-Pmincho,Bold
/// * MS-Pmincho,Italic
/// * MS-Pmincho,BoldItalic
/// * MS-PGothic
/// * MS-PGothic,Bold
/// * MS-PGothic,Italic
/// * MS-PGothic,BoldItalic
pub fn use_jpfonts(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseJPFonts(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseJPFonts failed (status = {})", status);
}
Ok(())
}
/// Enable Korian fonts. After the method invoked, an application can use the following Korean fonts.
/// * DotumChe
/// * DotumChe,Bold
/// * DotumChe,Italic
/// * DotumChe,BoldItalic
/// * Dotum
/// * Dotum,Bold
/// * Dotum,Italic
/// * Dotum,BoldItalic
/// * BatangChe
/// * BatangChe,Bold
/// * BatangChe,Italic
/// * BatangChe,BoldItalic
/// * Batang
/// * Batang,Bold
/// * Batang,Italic
/// * Batang,BoldItalic
pub fn use_krfonts(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseKRFonts(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseKRFonts failed (status = {})", status);
}
Ok(())
}
/// Enable simplified Chinese fonts. After the method invoked, an application can use the following simplified Chinese fonts.
/// * SimSun
/// * SimSun,Bold
/// * SimSun,Italic
/// * SimSun,BoldItalic
/// * SimHei
/// * SimHei,Bold
/// * SimHei,Italic
/// * SimHei,BoldItalic
pub fn use_cnsfonts(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseCNSFonts(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseCNSFonts failed (status = {})", status);
}
Ok(())
}
/// Enable traditional Chinese fonts. After the method invoked, an application can use the following traditional Chinese fonts.
/// * MingLiU
/// * MingLiU,Bold
/// * MingLiU,Italic
/// * MingLiU,BoldItalic
pub fn use_cntfonts(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseCNTFonts(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseCNTFonts failed (status = {})", status);
}
Ok(())
}
/// Enable Japanese encodings. After the method invoked, an application can use the following Japanese encodings.
/// * 90ms-RKSJ-H
/// * 90ms-RKSJ-V
/// * 90msp-RKSJ-H
/// * EUC-H
/// * EUC-V
pub fn use_jpencodings(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseJPEncodings(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseJPEncodings failed (status = {})", status);
}
Ok(())
}
/// Enable Korean encodings. After the method is invoked, an application can use the following Korean encodings.
/// * KSC-EUC-H
/// * KSC-EUC-V
/// * KSCms-UHC-H
/// * KSCms-UHC-HW-H
/// * KSCms-UHC-HW-V
pub fn use_krencodings(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseKREncodings(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseKREncodings failed (status = {})", status);
}
Ok(())
}
/// Enable simplified Chinese encodings. After the method is invoked, an application can use the following simplified Chinese encodings.
/// * GB-EUC-H
/// * GB-EUC-V
/// * GBK-EUC-H
/// * GBK-EUC-V
pub fn use_cnsencodings(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseCNSEncodings(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseCNSEncodings failed (status = {})", status);
}
Ok(())
}
/// Enable traditional Chinese encodings. After the method is invoked, an application can use the following traditional Chinese encodings.
/// * GB-EUC-H
/// * GB-EUC-V
/// * GBK-EUC-H
/// * GBK-EUC-V
pub fn use_cntencodings(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseCNTEncodings(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseCNTEncodings failed (status = {})", status);
}
Ok(())
}
/// Enable UTF-8 encoding.
pub fn use_utfencodings(&self) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_UseUTFEncodings(self.handle())
};
if status != 0 {
anyhow::bail!("HPDF_UseCNTEncodings failed (status = {})", status);
}
Ok(())
}
/// Save the current document to a file.
pub fn save_to_file(&self, name: &str) -> anyhow::Result<()> {
let name = CString::new(name).unwrap();
let status = unsafe {
libharu_sys::HPDF_SaveToFile(self.handle(), std::mem::transmute(name.as_bytes().as_ptr()))
};
if status != 0 {
anyhow::bail!("HPDF_SaveToFile failed (status = {})", status);
}
Ok(())
}
/// Set the mode of compression.
pub fn set_compression_mode(&self, mode: CompressionMode) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_SetCompressionMode(self.handle(), mode.bits())
};
if status != 0 {
anyhow::bail!("HPDF_SetCompressionMode failed (status = {})", status);
}
Ok(())
}
/// creates root outline object.
pub fn create_outline(&self, title: &str, parent: Option<&Outline>, enc: Option<&Encoder>) -> anyhow::Result<Outline> {
let title = CString::new(title)?;
let outline = unsafe {
libharu_sys::HPDF_CreateOutline(
self.handle(),
match parent {
Some(p) => p.handle(),
None => std::ptr::null_mut(),
},
title.as_ptr() as *const i8,
match enc {
Some(e) => e.handle(),
None => std::ptr::null_mut(),
}
)
};
if outline == std::ptr::null_mut() {
anyhow::bail!("HPDF_CreateOutline failed");
}
Ok(Outline::new(self, outline))
}
/// creates root outline object. (raw bytes)
pub fn create_outline_bytes(&self, title: &[u8], parent: Option<&Outline>, enc: Option<&Encoder>) -> anyhow::Result<Outline> {
let title = CString::new(title)?;
let outline = unsafe {
libharu_sys::HPDF_CreateOutline(
self.handle(),
match parent {
Some(p) => p.handle(),
None => std::ptr::null_mut(),
},
title.as_ptr() as *const i8,
match enc {
Some(e) => e.handle(),
None => std::ptr::null_mut(),
}
)
};
if outline == std::ptr::null_mut() {
anyhow::bail!("HPDF_CreateOutline failed");
}
Ok(Outline::new(self, outline))
}
/// Get the handle of a corresponding encoder object by specified encoding name.
pub fn find_encoder(&self, encoding_name: &str) -> anyhow::Result<Encoder> {
let encoding_name = CString::new(encoding_name)?;
let enc = unsafe {
libharu_sys::HPDF_GetEncoder(self.handle(), encoding_name.as_ptr())
};
if enc == std::ptr::null_mut() {
anyhow::bail!("HPDF_GetEncoder failed");
}
Ok(Encoder::new(self, enc))
}
/// Get the handle of the current encoder of the document object.
pub fn current_encoder(&self) -> anyhow::Result<Encoder> {
let enc = unsafe {
libharu_sys::HPDF_GetCurrentEncoder(self.handle())
};
if enc == std::ptr::null_mut() {
anyhow::bail!("HPDF_GetCurrentEncoder failed");
}
Ok(Encoder::new(self, enc))
}
/// Set the handle of the current encoder of the document object.
pub fn set_current_encoder(&self, encoding_name: &str) -> anyhow::Result<()> {
let encoding_name = CString::new(encoding_name)?;
let status = unsafe {
libharu_sys::HPDF_SetCurrentEncoder(self.handle(), encoding_name.as_ptr())
};
if status != 0 {
anyhow::bail!("HPDF_SetCurrentEncoder failed (status={})", status);
}
Ok(())
}
/// Get the current setting for page layout.
pub fn page_layout(&self) -> anyhow::Result<PageLayout> {
let layout = unsafe {
libharu_sys::HPDF_GetPageLayout(self.handle())
};
Ok(match layout {
libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_SINGLE => PageLayout::Single,
libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_ONE_COLUMN => PageLayout::OneColumn,
libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_TWO_COLUMN_LEFT => PageLayout::TwoColumnLeft,
libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_TWO_COLUMN_RIGHT => PageLayout::TwoColumnRight,
_ => anyhow::bail!("HPDF_GetPageLayout failed"),
})
}
/// Set how the page should be displayed. If this attribute is not set, the setting of a viewer application is used.
pub fn set_page_layout(&self, layout: PageLayout) -> anyhow::Result<()> {
let layout = match layout {
PageLayout::Single => libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_SINGLE,
PageLayout::OneColumn => libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_ONE_COLUMN,
PageLayout::TwoColumnLeft => libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_TWO_COLUMN_LEFT,
PageLayout::TwoColumnRight => libharu_sys::HPDF_PageLayout::HPDF_PAGE_LAYOUT_TWO_COLUMN_RIGHT,
};
let status = unsafe {
libharu_sys::HPDF_SetPageLayout(self.handle(), layout)
};
if status != 0 {
anyhow::bail!("HPDF_SetPageLayout failed (status={})", status);
}
Ok(())
}
/// load a TrueType font from an external file and register it to a document object.
pub fn load_ttf_font(&self, name: &str, embedding: bool) -> anyhow::Result<&str> {
let name = CString::new(name)?;
let ret = unsafe {
libharu_sys::HPDF_LoadTTFontFromFile(self.handle(), name.as_ptr(), if embedding { 1 } else { 0 } )
};
if ret == std::ptr::null_mut() {
anyhow::bail!("HPDF_LoadTTFontFromFile failed");
}
let s = unsafe { std::ffi::CStr::from_ptr(ret).to_str()? };
//let ret = unsafe { CString::from_raw(ret as *mut i8).into_string()? };
Ok(s)
}
/// Load a TrueType font from an TrueType collection file and register it to a document object.
pub fn load_ttf_font_from_ttc(&self, name: &str, index: usize, embedding: bool) -> anyhow::Result<&str> {
let name = CString::new(name)?;
let index = index as u32;
let ret = unsafe {
libharu_sys::HPDF_LoadTTFontFromFile2(self.handle(), name.as_ptr(), index, if embedding { 1 } else { 0 } )
};
if ret == std::ptr::null_mut() {
anyhow::bail!("HPDF_LoadTTFontFromFile failed");
}
let s = unsafe { std::ffi::CStr::from_ptr(ret).to_str()? };
//let ret = unsafe { CString::from_raw(ret as *mut i8).into_string()? };
Ok(s)
}
/// Load an external png image file.
pub fn load_png_image(&self, name: &str) -> anyhow::Result<Image> {
let name = CString::new(name)?;
let image = unsafe {
libharu_sys::HPDF_LoadPngImageFromFile(self.handle(), name.as_ptr())
};
if image == std::ptr::null_mut() {
anyhow::bail!("HPDF_LoadPngImageFromFile failed");
}
Ok(Image::new(self, image))
}
/// Set the first page appears when a document is opened.
pub fn set_open_action(&self, dst: &Destination) -> anyhow::Result<()> {
let status = unsafe {
libharu_sys::HPDF_SetOpenAction(self.handle(), dst.handle())
};
if status != 0 {
anyhow::bail!("HPDF_SetOpenAction failed (status={})", status);
}
Ok(())
}
}
impl Drop for Document {
fn drop(&mut self) {
unsafe {
libharu_sys::HPDF_Free(self.handle());
}
}
}
extern "C" fn onerror_callback(
errno: libharu_sys::HPDF_STATUS,
detailno: libharu_sys::HPDF_STATUS,
userdata: libharu_sys::HPDF_HANDLE)
{
let inner: &mut DocumentInner = unsafe { std::mem::transmute(userdata) };
inner.last_errno = errno;
inner.last_detailno = detailno;
(inner.onerror)(Error::from_num(errno));
}