forked from J-F-Liu/lopdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.rs
More file actions
1484 lines (1305 loc) · 52.5 KB
/
reader.rs
File metadata and controls
1484 lines (1305 loc) · 52.5 KB
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use log::{error, warn};
use std::cmp;
use std::collections::{BTreeMap, HashSet};
use std::convert::TryInto;
#[cfg(not(feature = "async"))]
use std::fs::File;
#[cfg(not(feature = "async"))]
use std::io::Read;
use std::path::Path;
use std::sync::Mutex;
#[cfg(feature = "rayon")]
use rayon::prelude::*;
#[cfg(feature = "async")]
use tokio::fs::File;
#[cfg(feature = "async")]
use tokio::io::{AsyncRead, AsyncReadExt};
#[cfg(feature = "async")]
use tokio::pin;
use crate::encryption::{self, EncryptionState};
use crate::error::{ParseError, XrefError};
use crate::load_options::{FilterFunc, LoadOptions};
use crate::object_stream::ObjectStream;
use crate::parser::{self, ParserInput};
use crate::xref::XrefEntry;
use crate::{Dictionary, Document, Error, IncrementalDocument, Object, ObjectId, Result};
use crate::common_data_structures;
#[cfg(not(feature = "async"))]
impl Document {
/// Load a PDF document from a specified file path.
#[inline]
pub fn load<P: AsRef<Path>>(path: P) -> Result<Document> {
Self::load_with_options(path, LoadOptions::default())
}
/// Load a PDF document from a specified file path with the given options.
#[inline]
pub fn load_with_options<P: AsRef<Path>>(path: P, options: LoadOptions) -> Result<Document> {
let file = File::open(path)?;
let capacity = Some(file.metadata()?.len() as usize);
Self::load_internal(file, capacity, options)
}
/// Load a PDF document from a specified file path with a password for encrypted PDFs.
#[inline]
pub fn load_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<Document> {
Self::load_with_options(path, LoadOptions::with_password(password))
}
#[deprecated(since = "0.41.0", note = "Use load_with_options instead")]
#[inline]
pub fn load_filtered<P: AsRef<Path>>(path: P, filter_func: FilterFunc) -> Result<Document> {
Self::load_with_options(path, LoadOptions::with_filter(filter_func))
}
/// Load a PDF document from an arbitrary source.
#[inline]
pub fn load_from<R: Read>(source: R) -> Result<Document> {
Self::load_from_with_options(source, LoadOptions::default())
}
/// Load a PDF document from an arbitrary source with the given options.
#[inline]
pub fn load_from_with_options<R: Read>(source: R, options: LoadOptions) -> Result<Document> {
Self::load_internal(source, None, options)
}
/// Load a PDF document from an arbitrary source with a password for encrypted PDFs.
#[deprecated(since = "0.41.0", note = "Use load_from_with_options instead")]
#[inline]
pub fn load_from_with_password<R: Read>(source: R, password: &str) -> Result<Document> {
Self::load_from_with_options(source, LoadOptions::with_password(password))
}
fn load_internal<R: Read>(mut source: R, capacity: Option<usize>, options: LoadOptions) -> Result<Document> {
let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
source.read_to_end(&mut buffer)?;
Reader {
buffer: &buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: options.password,
strict: options.strict,
}
.read(options.filter)
}
/// Load a PDF document from a memory slice.
pub fn load_mem(buffer: &[u8]) -> Result<Document> {
Self::load_mem_with_options(buffer, LoadOptions::default())
}
/// Load a PDF document from a memory slice with the given options.
pub fn load_mem_with_options(buffer: &[u8], options: LoadOptions) -> Result<Document> {
Reader {
buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: options.password,
strict: options.strict,
}
.read(options.filter)
}
/// Load a PDF document from a memory slice with a password for encrypted PDFs.
#[deprecated(since = "0.41.0", note = "Use load_mem_with_options instead")]
pub fn load_mem_with_password(buffer: &[u8], password: &str) -> Result<Document> {
Self::load_mem_with_options(buffer, LoadOptions::with_password(password))
}
/// Load PDF metadata (title and page count) without loading the entire document.
/// This is much faster for large PDFs when you only need basic information.
#[inline]
pub fn load_metadata<P: AsRef<Path>>(path: P) -> Result<PdfMetadata> {
let file = File::open(path)?;
let capacity = Some(file.metadata()?.len() as usize);
Self::load_metadata_internal(file, capacity, None)
}
/// Load PDF metadata from a file path with a password for encrypted PDFs.
#[inline]
pub fn load_metadata_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<PdfMetadata> {
let file = File::open(path)?;
let capacity = Some(file.metadata()?.len() as usize);
Self::load_metadata_internal(file, capacity, Some(password.to_string()))
}
/// Load PDF metadata from an arbitrary source without loading the entire document.
#[inline]
pub fn load_metadata_from<R: Read>(source: R) -> Result<PdfMetadata> {
Self::load_metadata_internal(source, None, None)
}
/// Load PDF metadata from an arbitrary source with a password for encrypted PDFs.
#[inline]
pub fn load_metadata_from_with_password<R: Read>(source: R, password: &str) -> Result<PdfMetadata> {
Self::load_metadata_internal(source, None, Some(password.to_string()))
}
/// Load PDF metadata from a memory slice without loading the entire document.
#[inline]
pub fn load_metadata_mem(buffer: &[u8]) -> Result<PdfMetadata> {
Reader {
buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: None,
strict: false,
}
.read_metadata()
}
/// Load PDF metadata from a memory slice with a password for encrypted PDFs.
#[inline]
pub fn load_metadata_mem_with_password(buffer: &[u8], password: &str) -> Result<PdfMetadata> {
Reader {
buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: Some(password.to_string()),
strict: false,
}
.read_metadata()
}
fn load_metadata_internal<R: Read>(
mut source: R, capacity: Option<usize>, password: Option<String>,
) -> Result<PdfMetadata> {
let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
source.read_to_end(&mut buffer)?;
Reader {
buffer: &buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password,
strict: false,
}
.read_metadata()
}
}
#[cfg(feature = "async")]
impl Document {
pub async fn load<P: AsRef<Path>>(path: P) -> Result<Document> {
Self::load_with_options(path, LoadOptions::default()).await
}
/// Load a PDF document from a specified file path with the given options.
pub async fn load_with_options<P: AsRef<Path>>(path: P, options: LoadOptions) -> Result<Document> {
let file = File::open(path).await?;
let metadata = file.metadata().await?;
let capacity = Some(metadata.len() as usize);
Self::load_internal(file, capacity, options).await
}
/// Load a PDF document from a specified file path with a password for encrypted PDFs.
pub async fn load_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<Document> {
Self::load_with_options(path, LoadOptions::with_password(password)).await
}
#[deprecated(since = "0.41.0", note = "Use load_with_options instead")]
pub async fn load_filtered<P: AsRef<Path>>(path: P, filter_func: FilterFunc) -> Result<Document> {
Self::load_with_options(path, LoadOptions::with_filter(filter_func)).await
}
async fn load_internal<R: AsyncRead>(source: R, capacity: Option<usize>, options: LoadOptions) -> Result<Document> {
pin!(source);
let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
source.read_to_end(&mut buffer).await?;
Reader {
buffer: &buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: options.password,
strict: options.strict,
}
.read(options.filter)
}
/// Load a PDF document from a memory slice.
pub fn load_mem(buffer: &[u8]) -> Result<Document> {
Self::load_mem_with_options(buffer, LoadOptions::default())
}
/// Load a PDF document from a memory slice with the given options.
pub fn load_mem_with_options(buffer: &[u8], options: LoadOptions) -> Result<Document> {
Reader {
buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: options.password,
strict: options.strict,
}
.read(options.filter)
}
/// Load PDF metadata (title and page count) without loading the entire document.
/// This is much faster for large PDFs when you only need basic information.
#[inline]
pub async fn load_metadata<P: AsRef<Path>>(path: P) -> Result<PdfMetadata> {
let file = File::open(path).await?;
let metadata = file.metadata().await?;
let capacity = Some(metadata.len() as usize);
Self::load_metadata_internal(file, capacity, None).await
}
/// Load PDF metadata from a file path with a password for encrypted PDFs.
#[inline]
pub async fn load_metadata_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<PdfMetadata> {
let file = File::open(path).await?;
let metadata = file.metadata().await?;
let capacity = Some(metadata.len() as usize);
Self::load_metadata_internal(file, capacity, Some(password.to_string())).await
}
/// Load PDF metadata from an arbitrary source without loading the entire document.
#[inline]
pub async fn load_metadata_from<R: AsyncRead>(source: R) -> Result<PdfMetadata> {
Self::load_metadata_internal(source, None, None).await
}
/// Load PDF metadata from an arbitrary source with a password for encrypted PDFs.
#[inline]
pub async fn load_metadata_from_with_password<R: AsyncRead>(source: R, password: &str) -> Result<PdfMetadata> {
Self::load_metadata_internal(source, None, Some(password.to_string())).await
}
/// Load PDF metadata from a memory slice without loading the entire document.
#[inline]
pub fn load_metadata_mem(buffer: &[u8]) -> Result<PdfMetadata> {
Reader {
buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: None,
strict: false,
}
.read_metadata()
}
/// Load PDF metadata from a memory slice with a password for encrypted PDFs.
#[inline]
pub fn load_metadata_mem_with_password(buffer: &[u8], password: &str) -> Result<PdfMetadata> {
Reader {
buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: Some(password.to_string()),
strict: false,
}
.read_metadata()
}
async fn load_metadata_internal<R: AsyncRead>(
source: R, capacity: Option<usize>, password: Option<String>,
) -> Result<PdfMetadata> {
pin!(source);
let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
source.read_to_end(&mut buffer).await?;
Reader {
buffer: &buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password,
strict: false,
}
.read_metadata()
}
}
impl TryInto<Document> for &[u8] {
type Error = Error;
fn try_into(self) -> Result<Document> {
Reader {
buffer: self,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: None,
strict: false,
}
.read(None)
}
}
#[cfg(not(feature = "async"))]
impl IncrementalDocument {
/// Load a PDF document from a specified file path.
#[inline]
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
let file = File::open(path)?;
let capacity = Some(file.metadata()?.len() as usize);
Self::load_internal(file, capacity)
}
/// Load a PDF document from an arbitrary source.
#[inline]
pub fn load_from<R: Read>(source: R) -> Result<Self> {
Self::load_internal(source, None)
}
fn load_internal<R: Read>(mut source: R, capacity: Option<usize>) -> Result<Self> {
let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
source.read_to_end(&mut buffer)?;
let document = Reader {
buffer: &buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: None,
strict: false,
}
.read(None)?;
Ok(IncrementalDocument::create_from(buffer, document))
}
/// Load a PDF document from a memory slice.
pub fn load_mem(buffer: &[u8]) -> Result<Document> {
buffer.try_into()
}
}
#[cfg(feature = "async")]
impl IncrementalDocument {
/// Load a PDF document from a specified file path.
#[inline]
pub async fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
let file = File::open(path).await?;
let metadata = file.metadata().await?;
let capacity = Some(metadata.len() as usize);
Self::load_internal(file, capacity).await
}
/// Load a PDF document from an arbitrary source.
#[inline]
pub async fn load_from<R: AsyncRead>(source: R) -> Result<Self> {
Self::load_internal(source, None).await
}
async fn load_internal<R: AsyncRead>(source: R, capacity: Option<usize>) -> Result<Self> {
pin!(source);
let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
source.read_to_end(&mut buffer).await?;
let document = Reader {
buffer: &buffer,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: None,
strict: false,
}
.read(None)?;
Ok(IncrementalDocument::create_from(buffer, document))
}
/// Load a PDF document from a memory slice.
pub fn load_mem(buffer: &[u8]) -> Result<Document> {
buffer.try_into()
}
}
impl TryInto<IncrementalDocument> for &[u8] {
type Error = Error;
fn try_into(self) -> Result<IncrementalDocument> {
let document = Reader {
buffer: self,
document: Document::new(),
encryption_state: None,
raw_objects: BTreeMap::new(),
password: None,
strict: false,
}
.read(None)?;
Ok(IncrementalDocument::create_from(self.to_vec(), document))
}
}
pub struct Reader<'a> {
pub buffer: &'a [u8],
pub document: Document,
pub encryption_state: Option<EncryptionState>,
pub raw_objects: BTreeMap<ObjectId, Vec<u8>>, // Store raw bytes for encrypted objects
pub password: Option<String>, // Password for encrypted PDFs
pub strict: bool, // Reject non-conforming PDFs when true
}
/// Maximum allowed embedding of literal strings.
pub const MAX_BRACKET: usize = 100;
/// PDF metadata extracted without loading the entire document.
/// This is useful for quickly getting basic information about large PDFs.
#[derive(Debug, Clone)]
pub struct PdfMetadata {
/// Document title from Info dictionary
pub title: Option<String>,
/// Document author from Info dictionary
pub author: Option<String>,
/// Document subject from Info dictionary
pub subject: Option<String>,
/// Document keywords from Info dictionary
pub keywords: Option<String>,
/// Application that created the document
pub creator: Option<String>,
/// Application that produced the document
pub producer: Option<String>,
/// Document creation date (PDF date format: D:YYYYMMDDHHmmSSOHH'mm')
pub creation_date: Option<String>,
/// Document modification date (PDF date format: D:YYYYMMDDHHmmSSOHH'mm')
pub modification_date: Option<String>,
/// Number of pages in the document
pub page_count: u32,
/// PDF version
pub version: String,
}
struct InfoMetadata {
title: Option<String>,
author: Option<String>,
subject: Option<String>,
keywords: Option<String>,
creator: Option<String>,
producer: Option<String>,
creation_date: Option<String>,
modification_date: Option<String>,
}
impl Reader<'_> {
/// Read metadata (title and page count) without loading the entire document.
/// This is much faster for large PDFs when you only need basic information.
///
/// For encrypted PDFs, use `Document::load_metadata_with_password()` instead.
pub fn read_metadata(mut self) -> Result<PdfMetadata> {
let offset = self.buffer.windows(5).position(|w| w == b"%PDF-").unwrap_or(0);
self.buffer = &self.buffer[offset..];
let version =
parser::header(ParserInput::new_extra(self.buffer, "header"), self.strict).ok_or(ParseError::InvalidFileHeader)?;
let xref_start = Self::get_xref_start(self.buffer)?;
if xref_start > self.buffer.len() {
return Err(Error::Xref(XrefError::Start));
}
let (mut xref, mut trailer) =
parser::xref_and_trailer(ParserInput::new_extra(&self.buffer[xref_start..], "xref"), &self)?;
let mut already_seen = HashSet::new();
let mut prev_xref_start = trailer.remove(b"Prev");
while let Some(prev) = prev_xref_start.and_then(|offset| offset.as_i64().ok()) {
if already_seen.contains(&prev) {
break;
}
already_seen.insert(prev);
if prev < 0 || prev as usize > self.buffer.len() {
return Err(Error::Xref(XrefError::PrevStart));
}
let (prev_xref, prev_trailer) =
parser::xref_and_trailer(ParserInput::new_extra(&self.buffer[prev as usize..], ""), &self)?;
xref.merge(prev_xref);
let prev_xref_stream_start = trailer.remove(b"XRefStm");
if let Some(prev) = prev_xref_stream_start.and_then(|offset| offset.as_i64().ok()) {
if prev < 0 || prev as usize > self.buffer.len() {
return Err(Error::Xref(XrefError::StreamStart));
}
let (prev_xref, _) =
parser::xref_and_trailer(ParserInput::new_extra(&self.buffer[prev as usize..], ""), &self)?;
xref.merge(prev_xref);
}
prev_xref_start = prev_trailer.get(b"Prev").cloned().ok();
}
let xref_entry_count = xref.max_id().checked_add(1).ok_or(ParseError::InvalidXref)?;
if xref.size != xref_entry_count {
warn!(
"Size entry of trailer dictionary is {}, correct value is {}.",
xref.size, xref_entry_count
);
xref.size = xref_entry_count;
}
self.document.reference_table = xref;
self.document.trailer = trailer.clone();
if self.document.trailer.get(b"Encrypt").is_ok() {
self.setup_encryption_for_metadata()?;
}
let info_metadata = self.extract_info_metadata()?;
let page_count = self.extract_page_count()?;
Ok(PdfMetadata {
title: info_metadata.title,
author: info_metadata.author,
subject: info_metadata.subject,
keywords: info_metadata.keywords,
creator: info_metadata.creator,
producer: info_metadata.producer,
creation_date: info_metadata.creation_date,
modification_date: info_metadata.modification_date,
page_count,
version,
})
}
fn extract_info_metadata(&self) -> Result<InfoMetadata> {
let info_ref = match self.document.trailer.get(b"Info") {
Ok(obj) => obj.as_reference().ok(),
Err(_) => {
return Ok(InfoMetadata {
title: None,
author: None,
subject: None,
keywords: None,
creator: None,
producer: None,
creation_date: None,
modification_date: None,
});
}
};
let info_id = match info_ref {
Some(id) => id,
None => {
return Ok(InfoMetadata {
title: None,
author: None,
subject: None,
keywords: None,
creator: None,
producer: None,
creation_date: None,
modification_date: None,
});
}
};
let mut already_seen = HashSet::new();
let info_obj = match self.get_object(info_id, &mut already_seen) {
Ok(obj) => obj,
Err(_) => {
return Ok(InfoMetadata {
title: None,
author: None,
subject: None,
keywords: None,
creator: None,
producer: None,
creation_date: None,
modification_date: None,
});
}
};
let info_dict = match info_obj.as_dict() {
Ok(dict) => dict,
Err(_) => {
return Ok(InfoMetadata {
title: None,
author: None,
subject: None,
keywords: None,
creator: None,
producer: None,
creation_date: None,
modification_date: None,
});
}
};
Ok(InfoMetadata {
title: Self::extract_string_field(info_dict, b"Title"),
author: Self::extract_string_field(info_dict, b"Author"),
subject: Self::extract_string_field(info_dict, b"Subject"),
keywords: Self::extract_string_field(info_dict, b"Keywords"),
creator: Self::extract_string_field(info_dict, b"Creator"),
producer: Self::extract_string_field(info_dict, b"Producer"),
creation_date: Self::extract_string_field(info_dict, b"CreationDate"),
modification_date: Self::extract_string_field(info_dict, b"ModDate"),
})
}
fn extract_string_field(dict: &Dictionary, key: &[u8]) -> Option<String> {
match dict.get(key) {
Ok(obj) => match obj {
Object::String(_bytes, _) => {
common_data_structures::decode_text_string(obj).ok()
}
_ => None,
},
Err(_) => None,
}
}
fn extract_page_count(&self) -> Result<u32> {
let root_ref = match self.document.trailer.get(b"Root").and_then(Object::as_reference) {
Ok(id) => id,
Err(_) => return Ok(0),
};
let mut already_seen = HashSet::new();
let catalog_obj = match self.get_object(root_ref, &mut already_seen) {
Ok(obj) => obj,
Err(_) => return Ok(0),
};
let catalog_dict = match catalog_obj.as_dict() {
Ok(dict) => dict,
Err(_) => return Ok(0),
};
let pages_ref = match catalog_dict.get(b"Pages").and_then(Object::as_reference) {
Ok(id) => id,
Err(_) => return Ok(0),
};
self.get_pages_tree_count(pages_ref, &mut HashSet::new()).or(Ok(0))
}
fn get_pages_tree_count(&self, pages_id: ObjectId, seen: &mut HashSet<ObjectId>) -> Result<u32> {
if seen.contains(&pages_id) {
return Err(Error::ReferenceCycle(pages_id));
}
seen.insert(pages_id);
let mut already_seen = HashSet::new();
let pages_obj = match self.get_object(pages_id, &mut already_seen) {
Ok(obj) => obj,
Err(_) => return Ok(0),
};
let pages_dict = match pages_obj.as_dict() {
Ok(dict) => dict,
Err(_) => return Ok(0),
};
match pages_dict.get_type() {
Ok(type_name) if type_name == b"Page" => Ok(1),
Ok(type_name) if type_name == b"Pages" => {
if let Ok(count_obj) = pages_dict.get(b"Count") {
if let Ok(count) = count_obj.as_i64() {
if count >= 0 {
return Ok(count as u32);
}
}
}
let kids = match pages_dict.get(b"Kids").and_then(Object::as_array) {
Ok(arr) => arr,
Err(_) => return Ok(0),
};
let mut total = 0u32;
for kid in kids.iter() {
if let Ok(kid_ref) = kid.as_reference() {
if let Ok(count) = self.get_pages_tree_count(kid_ref, seen) {
total += count;
}
}
}
Ok(total)
}
_ => Ok(1),
}
}
/// Read whole document.
pub fn read(mut self, filter_func: Option<FilterFunc>) -> Result<Document> {
let offset = self.buffer.windows(5).position(|w| w == b"%PDF-").unwrap_or(0);
self.buffer = &self.buffer[offset..];
// The document structure can be expressed in PEG as:
// document <- header indirect_object* xref trailer xref_start
let version =
parser::header(ParserInput::new_extra(self.buffer, "header"), self.strict).ok_or(ParseError::InvalidFileHeader)?;
//The binary_mark is in line 2 after the pdf version. If at other line number, then will be declared as invalid pdf.
if let Some(pos) = self.buffer.iter().position(|&byte| byte == b'\n') {
if let Some(binary_mark) =
parser::binary_mark(ParserInput::new_extra(&self.buffer[pos + 1..], "binary_mark"))
{
if binary_mark.iter().all(|&byte| byte >= 128) {
self.document.binary_mark = binary_mark;
}
}
}
let xref_start = Self::get_xref_start(self.buffer)?;
if xref_start > self.buffer.len() {
return Err(Error::Xref(XrefError::Start));
}
self.document.xref_start = xref_start;
let (mut xref, mut trailer) =
parser::xref_and_trailer(ParserInput::new_extra(&self.buffer[xref_start..], "xref"), &self)?;
// Read previous Xrefs of linearized or incremental updated document.
let mut already_seen = HashSet::new();
let mut prev_xref_start = trailer.remove(b"Prev");
while let Some(prev) = prev_xref_start.and_then(|offset| offset.as_i64().ok()) {
if already_seen.contains(&prev) {
break;
}
already_seen.insert(prev);
if prev < 0 || prev as usize > self.buffer.len() {
return Err(Error::Xref(XrefError::PrevStart));
}
let (prev_xref, prev_trailer) =
parser::xref_and_trailer(ParserInput::new_extra(&self.buffer[prev as usize..], ""), &self)?;
xref.merge(prev_xref);
// Read xref stream in hybrid-reference file
let prev_xref_stream_start = trailer.remove(b"XRefStm");
if let Some(prev) = prev_xref_stream_start.and_then(|offset| offset.as_i64().ok()) {
if prev < 0 || prev as usize > self.buffer.len() {
return Err(Error::Xref(XrefError::StreamStart));
}
let (prev_xref, _) =
parser::xref_and_trailer(ParserInput::new_extra(&self.buffer[prev as usize..], ""), &self)?;
xref.merge(prev_xref);
}
prev_xref_start = prev_trailer.get(b"Prev").cloned().ok();
}
let xref_entry_count = xref.max_id().checked_add(1).ok_or(ParseError::InvalidXref)?;
if xref.size != xref_entry_count {
warn!(
"Size entry of trailer dictionary is {}, correct value is {}.",
xref.size, xref_entry_count
);
xref.size = xref_entry_count;
}
self.document.version = version;
self.document.max_id = xref.size - 1;
self.document.trailer = trailer;
self.document.reference_table = xref;
// Check if encrypted
let is_encrypted = self.document.trailer.get(b"Encrypt").is_ok();
if is_encrypted {
// For encrypted PDFs, use a special loading strategy
self.load_encrypted_document(filter_func)?;
} else {
// For non-encrypted PDFs, use the normal loading
self.load_objects_raw(filter_func)?;
}
Ok(self.document)
}
fn load_encrypted_document(&mut self, _filter_func: Option<FilterFunc>) -> Result<()> {
// First, extract all raw object bytes without parsing
let entries: Vec<_> = self
.document
.reference_table
.entries
.iter()
.map(|(k, v)| (*k, v.clone()))
.collect();
let mut object_streams = Vec::new();
for (obj_num, entry) in entries {
match entry {
XrefEntry::Normal { offset, .. } => {
if let Ok((obj_id, raw_bytes)) = self.extract_raw_object(offset as usize) {
self.raw_objects.insert(obj_id, raw_bytes);
}
}
XrefEntry::Compressed { container, index } => {
// Store compressed object info for later processing
object_streams.push((obj_num, container, index));
}
XrefEntry::Free | XrefEntry::UnusableFree => {
// Skip free entries
}
}
}
self.parse_encryption_dictionary()?;
if self.authenticate_and_setup_encryption(false)?.is_none() {
return Ok(());
}
if let Some(ref state) = self.encryption_state {
let encrypt_ref = self
.document
.trailer
.get(b"Encrypt")
.ok()
.and_then(|o| o.as_reference().ok());
for (obj_id, raw_bytes) in &self.raw_objects {
if let Some(enc_ref) = encrypt_ref {
if *obj_id == enc_ref {
continue;
}
}
if let Ok((id, mut obj)) = self.parse_raw_object(raw_bytes) {
let _ = encryption::decrypt_object(state, *obj_id, &mut obj);
self.document.objects.insert(id, obj);
}
}
let mut streams_to_process: std::collections::HashMap<u32, Vec<(u32, u16)>> =
std::collections::HashMap::new();
for (obj_num, container_id, index) in object_streams {
streams_to_process
.entry(container_id)
.or_default()
.push((obj_num, index));
}
for (container_id, objects_in_stream) in streams_to_process {
if let Some(container_obj) = self.document.objects.get_mut(&(container_id, 0)) {
if let Ok(stream) = container_obj.as_stream_mut() {
match ObjectStream::new(stream) {
Ok(object_stream) => {
for (obj_num, _index) in objects_in_stream {
let obj_id = (obj_num, 0);
if let Some(obj) = object_stream.objects.get(&obj_id) {
self.document.objects.insert(obj_id, obj.clone());
}
}
}
Err(_e) => {}
}
}
}
}
self.document.encryption_state = Some(state.clone());
if let Some(enc_ref) = encrypt_ref {
self.document.objects.remove(&enc_ref);
}
self.document.trailer.remove(b"Encrypt");
}
Ok(())
}
fn parse_raw_object(&self, raw_bytes: &[u8]) -> Result<(ObjectId, Object)> {
// Parse the raw bytes as an indirect object
parser::indirect_object(
ParserInput::new_extra(raw_bytes, "indirect object"),
0,
None,
self,
&mut HashSet::new(),
)
}
fn load_objects_raw(&mut self, filter_func: Option<FilterFunc>) -> Result<()> {
let is_encrypted = self.document.trailer.get(b"Encrypt").is_ok();
let zero_length_streams = Mutex::new(vec![]);
let object_streams = Mutex::new(vec![]);
// Build a map of which container each compressed object belongs to
// according to the xref. This prevents stale ObjStm copies (e.g., from
// linearization first-page sections) from overriding the correct version.
let compressed_obj_containers: BTreeMap<u32, u32> = self
.document
.reference_table
.entries
.iter()
.filter_map(|(&id, entry)| {
if let XrefEntry::Compressed { container, .. } = entry {
Some((id, *container))
} else {
None
}
})
.collect();
let entries_filter_map = |(_, entry): (&_, &_)| {
if let XrefEntry::Normal { offset, .. } = *entry {
// read_object now handles decryption internally
let result = self.read_object(offset as usize, None, &mut HashSet::new());
let (object_id, mut object) = match result {
Ok(obj) => obj,
Err(e) => {
// Log error but continue
if is_encrypted {
// Expected for some encrypted objects - but log which ones
warn!("Skipping encrypted object at offset {}: {:?}", offset, e);
} else {
error!("Object load error at offset {}: {e:?}", offset);
}
return None;
}
};
if let Some(filter_func) = filter_func {
filter_func(object_id, &mut object)?;
}
if let Ok(ref mut stream) = object.as_stream_mut() {
if stream.dict.has_type(b"ObjStm") && !is_encrypted {
let obj_stream = ObjectStream::new(stream).ok()?;
let container_id = object_id.0;
let mut object_streams = object_streams.lock().unwrap();
if let Some(filter_func) = filter_func {
let objects: BTreeMap<(u32, u16), Object> = obj_stream
.objects
.into_iter()
.filter(|((obj_num, _), _)| {
compressed_obj_containers.get(obj_num).is_none_or(|&c| c == container_id)
})
.filter_map(|(object_id, mut object)| filter_func(object_id, &mut object))
.collect();
object_streams.extend(objects);
} else {
object_streams.extend(
obj_stream.objects.into_iter().filter(|((obj_num, _), _)| {
compressed_obj_containers.get(obj_num).is_none_or(|&c| c == container_id)
}),
);
}
} else if stream.content.is_empty() {
let mut zero_length_streams = zero_length_streams.lock().unwrap();
zero_length_streams.push(object_id);
}
}
Some((object_id, object))