lopdf 0.48.0

A Rust library for PDF document manipulation.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
use std::fs::File;
use std::io::{BufWriter, Result, Write};
use std::path::Path;
use std::vec;

use super::Object::*;
use super::{Dictionary, Document, Object, ObjectId, Stream, StringFormat};
use crate::encryption;
use crate::{IncrementalDocument, xref::*};

impl Document {
    /// Save PDF document to specified file path.
    #[inline]
    pub fn save<P: AsRef<Path>>(&mut self, path: P) -> Result<File> {
        let mut file = BufWriter::new(File::create(path)?);
        self.save_internal(&mut file, Style::default())?;
        Ok(file.into_inner()?)
    }

    /// Save PDF to arbitrary target
    #[inline]
    pub fn save_to<W: Write>(&mut self, target: &mut W) -> Result<()> {
        self.save_internal(target, Style::default())
    }

    /// Save PDF with custom options
    ///
    /// Object streams are skipped for an encrypted document, which is written with every
    /// object serialized individually instead. See [`Document::save_modern`].
    ///
    /// # Errors
    ///
    /// Fails with [`std::io::ErrorKind::InvalidInput`] when [`SaveOptions::ascii`](crate::SaveOptions::ascii)
    /// is set for an encrypted document, before anything is written.
    pub fn save_with_options<W: Write>(&mut self, target: &mut W, options: crate::SaveOptions) -> Result<()> {
        // A reader decrypts a stream's data before it applies the stream's filters, so an
        // `/ASCIIHexDecode` filter would have to be applied before encryption, which turns
        // the data back into binary ciphertext.
        if options.ascii && self.is_encrypted() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "an encrypted document cannot be saved as ASCII: its streams are decrypted before their filters apply",
            ));
        }
        let style = Style::new(&options);

        // Xref streams and object streams are independent; select the requested type here so it
        // applies to whichever path writes the body. Both arrived in PDF 1.5, so bump the version.
        if options.use_xref_streams {
            self.reference_table.cross_reference_type = XrefType::CrossReferenceStream;

            if self.version.as_str() < "1.5" {
                self.version = "1.5".to_string();
            }
        }

        if options.use_object_streams {
            self.save_with_object_streams(target, options, style)
        } else {
            self.save_internal(target, style)
        }
    }

    /// Save PDF with modern features (object streams and cross-reference streams)
    ///
    /// An encrypted document is written without object streams. The objects are already
    /// encrypted by the time they reach the writer and the file encryption key is gone,
    /// so an object stream built here could only be written in the clear, contradicting
    /// the document's `/Encrypt` dictionary. The requested cross-reference type is still
    /// used; cross-reference streams are never encrypted.
    pub fn save_modern<W: Write>(&mut self, target: &mut W) -> Result<()> {
        let options = crate::SaveOptions {
            use_object_streams: true,
            use_xref_streams: true,
            ..Default::default()
        };
        self.save_with_options(target, options)
    }

    /// Objects whose own bytes are never rewritten in a plain save: an object
    /// stream or cross-reference stream is regenerated from `self.objects`, and
    /// the linearization dictionary is dropped, so copying them forward would
    /// contradict the new file layout.
    fn is_regenerated_on_save(object: &Object) -> bool {
        matches!(object.type_name(), Ok(name) if name == b"ObjStm" || name == b"XRef" || name == b"Linearized")
    }

    fn save_internal<W: Write>(&mut self, target: &mut W, style: Style) -> Result<()> {
        // A plain save uses the document's existing xref format, including the default stream.
        if matches!(
            self.reference_table.cross_reference_type,
            XrefType::CrossReferenceStream
        ) && self.version.as_str() < "1.5"
        {
            self.version = "1.5".to_string();
        }
        let mut target = CountingWrite {
            inner: target,
            bytes_written: 0,
        };

        let mut xref = Xref::new(self.max_id.saturating_add(1), self.reference_table.cross_reference_type);
        self.write_header(&mut target, style)?;

        for (&(id, generation), object) in &self.objects {
            if !Self::is_regenerated_on_save(object) {
                Writer::write_indirect_object(&mut target, id, generation, object, &mut xref, style)?;
            }
        }

        let xref_start = target.bytes_written;
        Self::write_xref_and_trailer(
            &mut target,
            &mut xref,
            xref_start,
            self.trailer.clone(),
            self.max_id,
            style,
        )
    }

    /// Write the `%PDF-x.y` line and, unless the output is to be ASCII, the binary mark.
    fn write_header(&self, target: &mut dyn Write, style: Style) -> Result<()> {
        writeln!(target, "%PDF-{}", self.version)?;
        if style.ascii {
            Ok(())
        } else {
            Writer::write_binary_mark(target, &self.binary_mark)
        }
    }

    /// The number after `last_id`, for an object the writer generates: an object stream or the
    /// cross-reference stream. These are numbered after [`Document::max_id`] without raising it,
    /// so saving a document does not change it and saving it again writes the same file.
    fn next_generated_id(last_id: &mut u32) -> Result<u32> {
        *last_id = last_id
            .checked_add(1)
            .ok_or_else(|| std::io::Error::other(crate::Error::ObjectIdOverflow))?;
        Ok(*last_id)
    }

    /// Write the cross-reference data in the requested form, then the
    /// `startxref` pointer that closes the file.
    ///
    /// `trailer` is a copy of the document's trailer that the writer completes with `/Size` and,
    /// for a cross-reference stream, the stream's own entries, so the document's trailer stays as
    /// it was. `last_id` is the highest object number written so far.
    fn write_xref_and_trailer<W: Write>(
        target: &mut CountingWrite<&mut W>, xref: &mut Xref, xref_start: usize, trailer: Dictionary, last_id: u32,
        style: Style,
    ) -> Result<()> {
        // Pick right cross reference stream.
        match xref.cross_reference_type {
            XrefType::CrossReferenceTable => {
                Writer::write_xref(target, xref)?;
                Self::write_trailer(target, trailer, last_id, style)?;
            }
            XrefType::CrossReferenceStream => {
                // Cross Reference Stream instead of XRef and Trailer
                Self::write_cross_reference_stream(target, xref, xref_start as u32, trailer, last_id, style)?;
            }
        }
        // Write `startxref` part of trailer
        write!(target, "\nstartxref\n{xref_start}\n%%EOF")
    }

    /// Save PDF with object streams enabled
    fn save_with_object_streams<W: Write>(
        &mut self, target: &mut W, options: crate::SaveOptions, style: Style,
    ) -> Result<()> {
        use crate::ObjectStream;

        // Ensure PDF version is at least 1.5 (required for object streams)
        if self.version.as_str() < "1.5" {
            self.version = "1.5".to_string();
        }

        // An object stream would go out unencrypted: `Document::encrypt` already dropped the key,
        // and the strings packed inside are themselves already encrypted (an object stream is the
        // unit of encryption). Write the objects out individually instead, as `save` does.
        if self.is_encrypted() {
            return self.save_internal(target, style);
        }

        let mut target = CountingWrite {
            inner: target,
            bytes_written: 0,
        };

        let mut xref = Xref::new(self.max_id.saturating_add(1), self.reference_table.cross_reference_type);
        self.write_header(&mut target, style)?;

        // Group the objects that go into object streams, borrowed: a stream is serialized from the
        // objects where they are, so saving does not hold a second copy of them.
        // The builder of `SaveOptions` reads 0 as the default; so does a config filled in by hand.
        let max_objects = match options.object_stream_config.max_objects_per_stream {
            0 => crate::ObjectStreamConfig::default().max_objects_per_stream,
            max_objects => max_objects,
        };
        let mut object_streams: Vec<Vec<(ObjectId, &Object)>> = Vec::new();
        let mut objects_to_write_directly = Vec::new();

        // Categorize objects
        for (&(id, generation), object) in &self.objects {
            // Skip existing object streams - we'll create new ones
            if let Object::Stream(stream) = object
                && let Ok(type_obj) = stream.dict.get(b"Type")
                && let Ok(type_name) = type_obj.as_name()
                && type_name == b"ObjStm"
            {
                continue; // Skip existing object streams
            }

            if generation == 0 && ObjectStream::can_be_compressed((id, generation), object, self) {
                match object_streams.last_mut() {
                    Some(members) if members.len() < max_objects => members.push(((id, generation), object)),
                    _ => {
                        let mut members = Vec::with_capacity(max_objects.min(1024));
                        members.push(((id, generation), object));
                        object_streams.push(members);
                    }
                }
            } else {
                // Object must be written directly
                objects_to_write_directly.push(((id, generation), object));
            }
        }

        // Write direct objects first
        for ((id, generation), object) in objects_to_write_directly {
            Writer::write_indirect_object(&mut target, id, generation, object, &mut xref, style)?;
        }

        // Write object streams
        let mut last_id = self.max_id;
        for members in object_streams {
            let stream_id = Self::next_generated_id(&mut last_id)?;
            // The members are in id order, which is the order the stream stores them in.
            let stream_obj =
                ObjectStream::styled_stream_of(&members, options.object_stream_config.compression_level, style)
                    .map_err(std::io::Error::other)?;

            for (index_in_stream, (obj_id, _)) in members.iter().enumerate() {
                xref.insert(
                    obj_id.0,
                    XrefEntry::Compressed {
                        container: stream_id,
                        index: index_in_stream as u16,
                    },
                );
            }

            // Write the object stream
            Writer::write_indirect_object(&mut target, stream_id, 0, &Object::Stream(stream_obj), &mut xref, style)?;
        }

        let xref_start = target.bytes_written;
        Self::write_xref_and_trailer(&mut target, &mut xref, xref_start, self.trailer.clone(), last_id, style)
    }

    /// Write the Cross Reference Stream.
    ///
    /// Insert an `Object` to the end of the PDF (not visible when inspecting `Document`).
    /// Note: This is different from the "Cross Reference Table".
    fn write_cross_reference_stream<W: Write>(
        file: &mut CountingWrite<&mut W>, xref: &mut Xref, xref_start: u32, mut trailer: Dictionary, mut last_id: u32,
        style: Style,
    ) -> Result<()> {
        let new_obj_id_for_crs = Self::next_generated_id(&mut last_id)?;
        xref.insert(
            new_obj_id_for_crs,
            XrefEntry::Normal {
                offset: xref_start,
                generation: 0,
            },
        );
        trailer.set("Type", Name(b"XRef".to_vec()));
        // The cross-reference stream is the highest object number.
        trailer.set("Size", i64::from(last_id) + 1);
        // `[u8, u32, u16]` per entry (the PDF default is `[1 2 1]`).
        trailer.set("W", Array(vec![Integer(1), Integer(4), Integer(2)]));
        let filter = if style.ascii {
            XRefStreamFilter::ASCIIHexDecode
        } else {
            XRefStreamFilter::None
        };
        let (stream, stream_length, indexes) = Writer::create_xref_steam(xref, filter)?;
        trailer.set("Index", indexes);

        if filter == XRefStreamFilter::ASCIIHexDecode {
            trailer.set("Filter", Name(b"ASCIIHexDecode".to_vec()));
        } else {
            trailer.remove(b"Filter");
        }

        trailer.set("Length", stream_length as i64);

        let cross_reference_stream = Stream(Stream {
            dict: trailer,
            allows_compression: true,
            content: stream,
            start_position: None,
        });
        // Insert Cross Reference Stream as an `Object` to the end of the PDF.
        // The `Object` is not added to `Document` because it is generated every time you save.
        Writer::write_indirect_object(file, new_obj_id_for_crs, 0, &cross_reference_stream, xref, style)?;

        Ok(())
    }

    fn write_trailer(file: &mut dyn Write, mut trailer: Dictionary, last_id: u32, style: Style) -> Result<()> {
        trailer.set("Size", i64::from(last_id) + 1);
        file.write_all(b"trailer\n")?;
        Writer::write_dictionary(file, &trailer, style)?;
        Ok(())
    }
}

impl IncrementalDocument {
    /// Save PDF document to specified file path.
    ///
    /// The `check_incremental_save_supported` guard is invoked before
    /// `File::create` so an unsupported input (e.g. a still-encrypted
    /// previous revision) does not truncate a pre-existing file at `path`.
    #[inline]
    pub fn save<P: AsRef<Path>>(&mut self, path: P) -> Result<File> {
        self.check_incremental_save_supported()?;
        let mut file = BufWriter::new(File::create(path)?);
        self.save_internal(&mut file)?;
        Ok(file.into_inner()?)
    }

    /// Save PDF to arbitrary target
    #[inline]
    pub fn save_to<W: Write>(&mut self, target: &mut W) -> Result<()> {
        self.save_internal(target)
    }

    /// Reject the two cases we still cannot handle: a document that arrived
    /// still-encrypted (no password was supplied), and the inconsistent case
    /// of `encryption_state` set but `encrypt_object_id` missing (which should
    /// not occur in practice — `decrypt_raw` records the id — but we guard
    /// against it defensively).
    fn check_incremental_save_supported(&self) -> Result<()> {
        let prev = self.get_prev_documents();
        if prev.is_encrypted() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "incremental update of a still-encrypted PDF is not supported: \
                 call `Document::decrypt` on the previous revision first \
                 (see https://github.com/J-F-Liu/lopdf/issues/520)",
            ));
        }
        if let Some(state) = prev.encryption_state.as_ref()
            && state.encrypt_object_id().is_none()
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "cannot incrementally save this decrypted document: \
                 the /Encrypt object id was not recorded during decryption",
            ));
        }
        Ok(())
    }

    fn save_internal<W: Write>(&mut self, target: &mut W) -> Result<()> {
        self.check_incremental_save_supported()?;

        // Re-encrypt appended objects with the previous encryption state and restore `/Encrypt`.
        // Cloning the (small) state avoids borrow conflicts with `&mut self.new_document`.
        let encryption_state = self.get_prev_documents().encryption_state.as_ref().cloned();

        let mut target = CountingWrite {
            inner: target,
            bytes_written: 0,
        };

        // Write previous document versions.
        let prev_document_bytes = self.get_prev_documents_bytes();
        target.inner.write_all(prev_document_bytes)?;
        target.bytes_written += prev_document_bytes.len();

        // Write/Append new document version.
        let mut xref = Xref::new(
            self.new_document.max_id.saturating_add(1),
            self.get_prev_documents().reference_table.cross_reference_type,
        );

        if let Some(last_byte) = prev_document_bytes.last()
            && *last_byte != b'\n'
        {
            // Add a newline if it was not already present
            writeln!(target)?;
        }

        // No file header or binary marker: an incremental update (ISO 32000-1, 7.5.6) is the
        // original file plus changed objects, a xref section and a trailer. A second "%PDF-x.y"
        // would make the appended region look like the start of another document.

        // Encrypt a clone of each object, leaving the in-memory ones as plaintext so repeated
        // saves do not double-encrypt.
        for (&(id, generation), object) in &self.new_document.objects {
            // `Self` is an `IncrementalDocument` here; the helper belongs to `Document`.
            if Document::is_regenerated_on_save(object) {
                continue;
            }
            if let Some(state) = encryption_state.as_ref() {
                let mut encrypted = object.clone();
                encryption::encrypt_object(state, (id, generation), &mut encrypted).map_err(std::io::Error::other)?;
                Writer::write_indirect_object(&mut target, id, generation, &encrypted, &mut xref, Style::default())?;
            } else {
                Writer::write_indirect_object(&mut target, id, generation, object, &mut xref, Style::default())?;
            }
        }

        // Write a trailer copy carrying the /Encrypt reference, so `new_document.trailer` stays
        // clean for later saves.
        let mut trailer = self.new_document.trailer.clone();
        if let Some(state) = encryption_state.as_ref() {
            let encrypt_id = state
                .encrypt_object_id()
                .expect("encrypt_object_id presence checked by check_incremental_save_supported");
            trailer.set(b"Encrypt", Object::Reference(encrypt_id));
        }

        let xref_start = target.bytes_written;

        // Pick right cross reference stream.
        Document::write_xref_and_trailer(
            &mut target,
            &mut xref,
            xref_start,
            trailer,
            self.new_document.max_id,
            Style::default(),
        )
    }
}

/// Low-level PDF object serializer.
///
/// Exposed so that callers which write a document incrementally (reserving
/// object ids up front and emitting the body as it is produced) can serialize
/// individual objects with exactly the same bytes `Document::save` would
/// produce, instead of reimplementing the format.
pub struct Writer;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum XRefStreamFilter {
    ASCIIHexDecode,
    _FlateDecode, //this is generally a Zlib compressed Stream.
    None,
}

impl Writer {
    /// Whether a blank must precede this object when it directly follows
    /// another token (a dictionary key, an array element, or the
    /// `N G obj` header of an indirect object).
    ///
    /// Exposed for incremental writers (see [`Writer`]): framing an indirect
    /// object as `N G obj` + object + `endobj` requires the same separator
    /// decision `Document::save` makes internally, and reimplementing it
    /// downstream is how the two serializers drift apart. Pair with
    /// [`Self::need_end_separator`] for the trailing side.
    pub fn need_separator(object: &Object) -> bool {
        matches!(*object, Null | Boolean(_) | Integer(_) | Real(_) | Reference(_))
    }

    /// Whether a blank must follow this object before the next token (for
    /// example before `endobj` when framing an indirect object).
    ///
    /// Exposed for incremental writers; see [`Self::need_separator`].
    pub fn need_end_separator(object: &Object) -> bool {
        matches!(
            *object,
            Null | Boolean(_) | Integer(_) | Real(_) | Name(_) | Reference(_) | Object::Stream(_)
        )
    }

    /// Group the table's entries into the contiguous runs a cross-reference
    /// table or stream is built from.
    ///
    /// Walk the entries, not every number up to the highest, so that a high
    /// object number does not make saving slow. A section starts at a
    /// *present* id; starting it at a missing id would shift every subsequent
    /// entry by one. Object 0 is left out; only a table has to invent an entry
    /// for it, and [`Self::write_xref`] is where that happens.
    fn xref_sections(xref: &Xref) -> Vec<XrefSection> {
        let mut sections: Vec<XrefSection> = Vec::new();

        for (&obj_id, entry) in xref.entries.range(1..) {
            match sections.last_mut() {
                // No number is missing between the section and this entry. The sum cannot
                // overflow: it is at most `obj_id`.
                Some(section) if section.starting_id + section.entries.len() as u32 == obj_id => {
                    section.add_entry(entry.clone());
                }
                _ => {
                    let mut section = XrefSection::new(obj_id);
                    section.add_entry(entry.clone());
                    sections.push(section);
                }
            }
        }

        sections
    }

    /// Write Cross Reference Table.
    ///
    /// Note: This is different from a "Cross Reference Stream".
    fn write_xref(file: &mut dyn Write, xref: &Xref) -> Result<()> {
        writeln!(file, "xref")?;

        let mut sections = Self::xref_sections(xref);

        // A table has to list object 0 as free. It can only share a subsection
        // with the ids that directly follow it, so it joins the first section
        // when that section starts at object 1, and otherwise gets a section of
        // its own — appending it to a section that starts later would attribute
        // that section's first entry to object 1. A document with no objects at
        // all still needs the lone entry, which the `insert` covers.
        if sections.first().is_some_and(|section| section.starting_id == 1) {
            sections[0].starting_id = 0;
        } else {
            sections.insert(0, XrefSection::new(0));
        }
        sections[0].entries.insert(0, XrefEntry::UnusableFree);

        // `XrefEntry::write_xref_entry` already renders a compressed object in
        // the free-slot form the spec gives it, so the entries go out as they
        // are.
        for section in &sections {
            section.write_xref_section(file)?;
        }

        Ok(())
    }

    /// Create stream for Cross reference stream.
    fn create_xref_steam(xref: &Xref, filter: XRefStreamFilter) -> Result<(Vec<u8>, usize, Object)> {
        let mut xref_stream = Vec::new();
        let mut xref_index = Vec::new();

        for section in Self::xref_sections(xref) {
            // Add indexes to list
            xref_index.push(Integer(section.starting_id as i64));
            xref_index.push(Integer(section.entries.len() as i64));
            // Add entries to stream. A `starting_id..` range would overflow on reaching `u32::MAX`.
            for (obj_id, entry) in (section.starting_id..=u32::MAX).zip(section.entries) {
                match entry {
                    XrefEntry::Free => {
                        // Type 0
                        xref_stream.push(0);
                        xref_stream.extend(obj_id.to_be_bytes());
                        xref_stream.extend(vec![0, 0]); // TODO add generation number
                    }
                    XrefEntry::UnusableFree => {
                        // Type 0
                        xref_stream.push(0);
                        xref_stream.extend(obj_id.to_be_bytes());
                        xref_stream.extend(65535_u16.to_be_bytes());
                    }
                    XrefEntry::Normal { offset, generation } => {
                        // Type 1
                        xref_stream.push(1);
                        xref_stream.extend(offset.to_be_bytes());
                        xref_stream.extend(generation.to_be_bytes());
                    }
                    XrefEntry::Compressed { container, index } => {
                        // Type 2
                        xref_stream.push(2);
                        xref_stream.extend(container.to_be_bytes());
                        xref_stream.extend(index.to_be_bytes());
                    }
                }
            }
        }

        if filter == XRefStreamFilter::ASCIIHexDecode {
            xref_stream = Writer::ascii_hex(&xref_stream);
        }

        // `/Length` counts the bytes that are stored, after any encoding, and not the end of
        // line that is written before `endstream`.
        let stream_length = xref_stream.len();

        Ok((xref_stream, stream_length, Array(xref_index)))
    }

    fn write_indirect_object<W: Write>(
        file: &mut CountingWrite<&mut W>, id: u32, generation: u16, object: &Object, xref: &mut Xref, style: Style,
    ) -> Result<()> {
        let offset = file.bytes_written as u32;
        xref.insert(id, XrefEntry::Normal { offset, generation });
        write!(
            file,
            "{} {} obj\n{}",
            id,
            generation,
            if Writer::need_separator(object) { " " } else { "" }
        )?;
        Writer::write_styled_object(file, object, style)?;
        writeln!(
            file,
            "{}\nendobj",
            if Writer::need_end_separator(object) { " " } else { "" }
        )?;
        Ok(())
    }

    /// Serialize one object body (no `N G obj` / `endobj` wrapper).
    ///
    /// The bytes are identical to what [`Document::save`] writes for the same
    /// object, so a caller assembling a file by hand can mix this with its own
    /// framing and still produce a byte-compatible document.
    ///
    /// # Errors
    ///
    /// Propagates I/O errors from `file`.
    pub fn write_object(file: &mut dyn Write, object: &Object) -> Result<()> {
        Writer::write_styled_object(file, object, Style::default())
    }

    /// Serialize one object body in the layout that `style` asks for.
    pub(crate) fn write_styled_object(file: &mut dyn Write, object: &Object, style: Style) -> Result<()> {
        match object {
            Null => file.write_all(b"null"),
            Boolean(value) => {
                if *value {
                    file.write_all(b"true")
                } else {
                    file.write_all(b"false")
                }
            }
            Integer(value) => {
                let mut buf = itoa::Buffer::new();
                file.write_all(buf.format(*value).as_bytes())
            }
            // `Display` writes every digit and never an exponent, which PDF syntax does not have,
            // but it drops the point of a whole number (`0` for `0.0`), which would read back as
            // an integer. NaN and the infinities have no PDF spelling and are left as they print.
            Real(value) => {
                let text = value.to_string();
                file.write_all(text.as_bytes())?;
                if value.is_finite() && !text.contains('.') {
                    file.write_all(b".0")?;
                }
                Ok(())
            }
            Name(name) => Writer::write_name(file, name),
            String(text, format) => Writer::write_string(file, text, format, style),
            Array(array) => Writer::write_array(file, array, style),
            Object::Dictionary(dict) => Writer::write_dictionary(file, dict, style),
            Object::Stream(stream) => Writer::write_stream(file, stream, style),
            Reference(id) => write!(file, "{} {} R", id.0, id.1),
        }
    }

    pub(crate) fn write_name(file: &mut dyn Write, name: &[u8]) -> Result<()> {
        file.write_all(b"/")?;
        for &byte in name {
            // white-space and delimiter chars are encoded to # sequences
            // also encode bytes outside of the range 33 (!) to 126 (~)
            if b" \t\n\r\x0C()<>[]{}/%#".contains(&byte) || !(33..=126).contains(&byte) {
                write!(file, "#{byte:02X}")?;
            } else {
                file.write_all(&[byte])?;
            }
        }
        Ok(())
    }

    fn write_string(file: &mut dyn Write, text: &[u8], format: &StringFormat, style: Style) -> Result<()> {
        match *format {
            // In a literal string escape each backslash and unbalanced parenthesis, byte by
            // byte, and escape CR/LF since an unescaped end-of-line marker reads as \n. ASCII
            // output also writes every byte that is not ASCII text as an octal escape, which
            // keeps the string literal.
            StringFormat::Literal => {
                let octal = |byte: u8| style.ascii && !is_ascii_text(byte);
                let mut escape_indice = Vec::new();
                let mut parentheses = Vec::new();
                for (index, &byte) in text.iter().enumerate() {
                    match byte {
                        b'(' => parentheses.push(index),
                        b')' => {
                            if !parentheses.is_empty() {
                                parentheses.pop();
                            } else {
                                escape_indice.push(index);
                            }
                        }
                        b'\\' | b'\r' => escape_indice.push(index),
                        _ => continue,
                    }
                }
                escape_indice.append(&mut parentheses);

                file.write_all(b"(")?;
                if !escape_indice.is_empty() || text.iter().any(|&byte| octal(byte)) {
                    for (index, &byte) in text.iter().enumerate() {
                        if escape_indice.contains(&index) {
                            file.write_all(b"\\")?;
                            file.write_all(&[if byte == b'\r' { b'r' } else { byte }])?;
                        } else if octal(byte) {
                            // Three digits, so that a digit that follows is not read as part
                            // of the escape.
                            write!(file, "\\{byte:03o}")?;
                        } else {
                            file.write_all(&[byte])?;
                        }
                    }
                } else {
                    file.write_all(text)?;
                }
                file.write_all(b")")?;
            }
            StringFormat::Hexadecimal => {
                file.write_all(b"<")?;
                for &byte in text {
                    write!(file, "{byte:02X}")?;
                }
                file.write_all(b">")?;
            }
        }
        Ok(())
    }

    fn write_array(file: &mut dyn Write, array: &[Object], style: Style) -> Result<()> {
        if style.pretty {
            // An array of numbers, names and the like, such as a `/MediaBox`, stays on one line.
            if !array
                .iter()
                .any(|object| matches!(object, Array(_) | Object::Dictionary(_) | Object::Stream(_)))
            {
                file.write_all(b"[")?;
                for (index, object) in array.iter().enumerate() {
                    if index > 0 {
                        file.write_all(b" ")?;
                    }
                    Writer::write_styled_object(file, object, style)?;
                }
                return file.write_all(b"]");
            }
            let inner = style.nested();
            file.write_all(b"[\n")?;
            for object in array {
                inner.indent(file)?;
                Writer::write_styled_object(file, object, inner)?;
                file.write_all(b"\n")?;
            }
            style.indent(file)?;
            return file.write_all(b"]");
        }
        file.write_all(b"[")?;
        let mut first = true;
        for object in array {
            if first {
                first = false;
            } else if Writer::need_separator(object) {
                file.write_all(b" ")?;
            }
            Writer::write_styled_object(file, object, style)?;
        }
        file.write_all(b"]")?;
        Ok(())
    }

    fn write_dictionary(file: &mut dyn Write, dictionary: &Dictionary, style: Style) -> Result<()> {
        if style.pretty && !dictionary.is_empty() {
            let inner = style.nested();
            file.write_all(b"<<\n")?;
            for (key, value) in dictionary {
                inner.indent(file)?;
                Writer::write_name(file, key)?;
                file.write_all(b" ")?;
                Writer::write_styled_object(file, value, inner)?;
                file.write_all(b"\n")?;
            }
            style.indent(file)?;
            return file.write_all(b">>");
        }
        file.write_all(b"<<")?;
        for (key, value) in dictionary {
            Writer::write_name(file, key)?;
            if Writer::need_separator(value) {
                file.write_all(b" ")?;
            }
            Writer::write_styled_object(file, value, style)?;
        }
        file.write_all(b">>")?;
        Ok(())
    }

    fn write_stream(file: &mut dyn Write, stream: &Stream, style: Style) -> Result<()> {
        let encoded;
        let stream = if style.ascii && !stream.content.iter().all(|&byte| is_ascii_text(byte)) {
            encoded = Writer::ascii_hex_stream(stream)?;
            &encoded
        } else {
            stream
        };
        Writer::write_dictionary(file, &stream.dict, style)?;
        file.write_all(if style.pretty { b"\nstream\n" } else { b"stream\n" })?;
        file.write_all(&stream.content)?;
        file.write_all(b"\nendstream")?;
        Ok(())
    }

    /// A copy of `stream` whose data is encoded with `/ASCIIHexDecode`, which is added in front
    /// of its filters, so that a reader decodes it to the same data.
    fn ascii_hex_stream(stream: &Stream) -> Result<Stream> {
        let hex = Name(b"ASCIIHexDecode".to_vec());
        let mut dict = stream.dict.clone();
        let filter = match dict.get(b"Filter") {
            Err(_) | Ok(Null) => hex,
            Ok(Name(name)) => Array(vec![hex, Name(name.clone())]),
            Ok(Array(filters)) => Array([hex].into_iter().chain(filters.iter().cloned()).collect()),
            Ok(_) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "cannot add /ASCIIHexDecode to a stream whose /Filter is neither a name nor an array",
                ));
            }
        };
        // The new filter takes no parameters. The parameters of the stream's own filters move
        // one place along, or into an array if a dictionary or a reference held them.
        let params = match dict.get(b"DecodeParms") {
            Ok(Array(params)) => Some(Array([Null].into_iter().chain(params.iter().cloned()).collect())),
            Ok(params @ (Object::Dictionary(_) | Reference(_))) => Some(Array(vec![Null, params.clone()])),
            _ => None,
        };
        dict.set("Filter", filter);
        if let Some(params) = params {
            dict.set("DecodeParms", params);
        }
        let content = Writer::ascii_hex(&stream.content);
        dict.set("Length", content.len() as i64);
        Ok(Stream {
            dict,
            content,
            allows_compression: stream.allows_compression,
            start_position: stream.start_position,
        })
    }

    /// Encode `data` as `/ASCIIHexDecode` reads it: two hexadecimal digits per byte, 64 to a
    /// line, and `>` at the end.
    fn ascii_hex(data: &[u8]) -> Vec<u8> {
        const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
        let mut encoded = Vec::with_capacity(data.len() * 2 + data.len() / 32 + 1);
        for (index, &byte) in data.iter().enumerate() {
            if index > 0 && index % 32 == 0 {
                encoded.push(b'\n');
            }
            encoded.push(DIGITS[usize::from(byte >> 4)]);
            encoded.push(DIGITS[usize::from(byte & 0x0F)]);
        }
        encoded.push(b'>');
        encoded
    }

    /// Write Binary mark as follows: %{binary_mark[4]}\n -> %Ç쏢 or Hex(%25 c3 87 c3 ac)
    ///
    /// Note: Specified in  ISO 19005-2:2011, ISO 19005-3:2012
    /// headerByte1 > 127 && headerByte2 > 127 && headerByte3 > 127 && headerByte4 > 127
    fn write_binary_mark(file: &mut dyn Write, binary_mark: &[u8]) -> Result<()> {
        if binary_mark.iter().all(|&byte| byte >= 128) {
            file.write_all(b"%")?;
            file.write_all(binary_mark)?;
            file.write_all(b"\n")?;
        } else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid binary mark",
            ));
        }

        Ok(())
    }
}

/// Whether `byte` may appear in ASCII output: tab, line feed, carriage return, or a printable
/// character.
fn is_ascii_text(byte: u8) -> bool {
    matches!(byte, b'\t' | b'\n' | b'\r' | b' '..=b'~')
}

/// How the writer lays out what it writes: the [`SaveOptions::ascii`](crate::SaveOptions::ascii)
/// and [`SaveOptions::pretty`](crate::SaveOptions::pretty) options, and how deeply pretty printing
/// indents the object being written.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Style {
    ascii: bool,
    pretty: bool,
    depth: usize,
}

impl Style {
    fn new(options: &crate::SaveOptions) -> Self {
        Self {
            ascii: options.ascii,
            pretty: options.pretty,
            depth: 0,
        }
    }

    /// The style of an entry or element one level further in.
    fn nested(self) -> Self {
        Self {
            depth: self.depth + 1,
            ..self
        }
    }

    fn indent(self, file: &mut dyn Write) -> Result<()> {
        for _ in 0..self.depth {
            file.write_all(b"  ")?;
        }
        Ok(())
    }
}

pub struct CountingWrite<W: Write> {
    inner: W,
    bytes_written: usize,
}

impl<W: Write> Write for CountingWrite<W> {
    #[inline]
    fn write(&mut self, buffer: &[u8]) -> Result<usize> {
        let result = self.inner.write(buffer);
        if let Ok(bytes) = result {
            self.bytes_written += bytes;
        }
        result
    }

    #[inline]
    fn write_all(&mut self, buffer: &[u8]) -> Result<()> {
        self.bytes_written += buffer.len();
        // If this returns `Err` we can’t know how many bytes were actually written (if any)
        // but that doesn’t matter since we’re gonna abort the entire PDF generation anyway.
        self.inner.write_all(buffer)
    }

    #[inline]
    fn flush(&mut self) -> Result<()> {
        self.inner.flush()
    }
}

#[test]
fn save_document() {
    let mut doc = Document::with_version("1.5");
    doc.objects.insert((1, 0), Null);
    doc.objects.insert((2, 0), Boolean(true));
    doc.objects.insert((3, 0), Integer(3));
    doc.objects.insert((4, 0), Real(0.5));
    doc.objects
        .insert((5, 0), String("text((\r)".as_bytes().to_vec(), StringFormat::Literal));
    doc.objects.insert(
        (6, 0),
        String("text((\r)".as_bytes().to_vec(), StringFormat::Hexadecimal),
    );
    doc.objects.insert((7, 0), Name(b"name \t".to_vec()));
    doc.objects.insert((8, 0), Reference((1, 0)));
    doc.objects
        .insert((9, 2), Array(vec![Integer(1), Integer(2), Integer(3)]));
    doc.objects
        .insert((11, 0), Stream(Stream::new(Dictionary::new(), vec![0x41, 0x42, 0x43])));
    let mut dict = Dictionary::new();
    dict.set("A", Null);
    dict.set("B", false);
    dict.set("C", Name(b"name".to_vec()));
    doc.objects.insert((12, 0), Object::Dictionary(dict));
    doc.max_id = 12;

    // Create temporary folder to store file.
    let temp_dir = tempfile::tempdir().unwrap();
    let file_path = temp_dir.path().join("test_0_save.pdf");
    doc.save(&file_path).unwrap();
    // Check if file was created.
    assert!(file_path.exists());
    // Check if path is file
    assert!(file_path.is_file());
    // Check if the file is above 400 bytes (should be about 610 bytes)
    assert!(file_path.metadata().unwrap().len() > 400);
}

#[test]
fn separator_decisions_are_public_for_incremental_writers() {
    // Token-like objects need a separating blank; self-delimiting objects
    // (names, strings, arrays, dictionaries, streams) do not need one before
    // them, but a name/reference/stream still needs one after it.
    assert!(Writer::need_separator(&Null));
    assert!(Writer::need_separator(&Integer(1)));
    assert!(Writer::need_separator(&Reference((1, 0))));
    assert!(!Writer::need_separator(&Name(b"Type".to_vec())));
    assert!(!Writer::need_separator(&Array(vec![Integer(1)])));

    assert!(Writer::need_end_separator(&Null));
    assert!(Writer::need_end_separator(&Name(b"Type".to_vec())));
    assert!(Writer::need_end_separator(&Reference((1, 0))));
    assert!(!Writer::need_end_separator(&Array(vec![Integer(1)])));
}