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
use std::convert::TryFrom;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::num::NonZeroI32;
use super::*;
/// A primitive type or a strongly typed writer.
pub trait Type {}
impl Type for bool {}
impl Type for i32 {}
impl Type for f32 {}
impl Type for Str<'_> {}
impl Type for TextStr<'_> {}
impl Type for Name<'_> {}
impl Type for Null {}
impl Type for Ref {}
impl Type for Rect {}
impl Type for Date {}
impl<'a, T: Writer<'a>> Type for T {}
/// A primitive PDF object.
pub trait Primitive {
/// Write the object into a buffer.
fn write(self, buf: &mut Vec<u8>);
}
impl<T: Primitive> Primitive for &T
where
T: Copy,
{
#[inline]
fn write(self, buf: &mut Vec<u8>) {
(*self).write(buf);
}
}
impl Primitive for bool {
#[inline]
fn write(self, buf: &mut Vec<u8>) {
if self {
buf.extend(b"true");
} else {
buf.extend(b"false");
}
}
}
impl Primitive for i32 {
#[inline]
fn write(self, buf: &mut Vec<u8>) {
buf.push_int(self);
}
}
impl Primitive for f32 {
#[inline]
fn write(self, buf: &mut Vec<u8>) {
buf.push_float(self);
}
}
/// A string object (any byte sequence).
///
/// This is usually written as `(Thing)`. However, it falls back to hexadecimal
/// form (e.g. `<2829>` for the string `"()"`) if the byte sequence contains any
/// of the three ASCII characters `\`, `(` or `)`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Str<'a>(pub &'a [u8]);
impl Primitive for Str<'_> {
fn write(self, buf: &mut Vec<u8>) {
// Fall back to hex formatting if the string contains a:
// - backslash because it is used for escaping,
// - parenthesis because they are the delimiters,
// - carriage return (0x0D) because it would be silently
// transformed into a newline (0x0A).
if self.0.iter().any(|b| matches!(b, b'\\' | b'(' | b')' | b'\r')) {
buf.reserve(2 + 2 * self.0.len());
buf.push(b'<');
for &byte in self.0 {
buf.push_hex(byte);
}
buf.push(b'>');
} else {
buf.push(b'(');
buf.extend(self.0);
buf.push(b')');
}
}
}
/// A unicode text string object.
///
/// This is written as a [`Str`] containing a byte order mark followed by
/// UTF-16-BE bytes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct TextStr<'a>(pub &'a str);
impl Primitive for TextStr<'_> {
fn write(self, buf: &mut Vec<u8>) {
// ASCII and PDFDocEncoding match for 32 up to 126.
if self.0.bytes().all(|b| matches!(b, 32..=126)) {
Str(self.0.as_bytes()).write(buf);
} else {
let mut bytes = vec![254, 255];
for v in self.0.encode_utf16() {
bytes.extend(v.to_be_bytes());
}
Str(&bytes).write(buf);
}
}
}
/// A name object.
///
/// Written as `/Thing`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Name<'a>(pub &'a [u8]);
impl Primitive for Name<'_> {
fn write(self, buf: &mut Vec<u8>) {
buf.push(b'/');
for &byte in self.0 {
// Quite a few characters must be escaped in names, so we take the
// safe route and allow only ASCII letters and numbers.
if byte.is_ascii_alphanumeric() {
buf.push(byte);
} else {
buf.push(b'#');
buf.push_hex(byte);
}
}
}
}
/// The null object.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Null;
impl Primitive for Null {
#[inline]
fn write(self, buf: &mut Vec<u8>) {
buf.extend(b"null");
}
}
/// A reference to an indirect object.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Ref(NonZeroI32);
impl Ref {
/// Create a new indirect reference.
///
/// The provided value must be greater than zero.
///
/// Panics if `id` is out of the valid range.
#[inline]
pub fn new(id: i32) -> Ref {
let val = if id > 0 { NonZeroI32::new(id) } else { None };
Self(val.expect("indirect reference out of valid range"))
}
/// Return the underlying number as a primitive type.
#[inline]
pub fn get(self) -> i32 {
self.0.get()
}
}
impl Primitive for Ref {
#[inline]
fn write(self, buf: &mut Vec<u8>) {
buf.push_int(self.0.get());
buf.extend(b" 0 R");
}
}
/// A rectangle, specified by two opposite corners.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Rect {
/// The x-coordinate of the first (typically, lower-left) corner.
pub x1: f32,
/// The y-coordinate of the first (typically, lower-left) corner.
pub y1: f32,
/// The x-coordinate of the second (typically, upper-right) corner.
pub x2: f32,
/// The y-coordinate of the second (typically, upper-right) corner.
pub y2: f32,
}
impl Rect {
/// Create a new rectangle from four coordinate values.
#[inline]
pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
Self { x1, y1, x2, y2 }
}
/// Convert this rectangle into 8 floats describing the four corners of the
/// rectangle in counterclockwise order.
#[inline]
pub fn to_quad_points(self) -> [f32; 8] {
[self.x1, self.y1, self.x2, self.y1, self.x2, self.y2, self.x1, self.y2]
}
}
impl Primitive for Rect {
#[inline]
fn write(self, buf: &mut Vec<u8>) {
buf.push(b'[');
buf.push_val(self.x1);
buf.push(b' ');
buf.push_val(self.y1);
buf.push(b' ');
buf.push_val(self.x2);
buf.push(b' ');
buf.push_val(self.y2);
buf.push(b']');
}
}
/// A date, written as a text string.
///
/// A field is only respected if all superior fields are supplied. For example,
/// to set the minute, the hour, day, etc. have to be set. Similarly, in order
/// for the time zone information to be written, all time information (including
/// seconds) must be written. `utc_offset_minute` is optional if supplying time
/// zone info. It must only be used to specify sub-hour time zone offsets.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Date {
/// The year (0-9999).
year: u16,
/// The month (0-11).
month: Option<u8>,
/// The month (0-30).
day: Option<u8>,
/// The hour (0-23).
hour: Option<u8>,
/// The minute (0-59).
minute: Option<u8>,
/// The second (0-59).
second: Option<u8>,
/// The hour offset from UTC (-23 through 23).
utc_offset_hour: Option<i8>,
/// The minute offset from UTC (0-59). Will carry over the sign from
/// `utc_offset_hour`.
utc_offset_minute: u8,
}
impl Date {
/// Create a new, minimal date. The year will be clamped within the range
/// 0-9999.
#[inline]
pub fn new(year: u16) -> Self {
Self {
year: year.min(9999),
month: None,
day: None,
hour: None,
minute: None,
second: None,
utc_offset_hour: None,
utc_offset_minute: 0,
}
}
/// Add the month field. It will be clamped within the range 1-12.
#[inline]
pub fn month(mut self, month: u8) -> Self {
self.month = Some(month.clamp(1, 12));
self
}
/// Add the day field. It will be clamped within the range 1-31.
#[inline]
pub fn day(mut self, day: u8) -> Self {
self.day = Some(day.clamp(1, 31));
self
}
/// Add the hour field. It will be clamped within the range 0-23.
#[inline]
pub fn hour(mut self, hour: u8) -> Self {
self.hour = Some(hour.min(23));
self
}
/// Add the minute field. It will be clamped within the range 0-59.
#[inline]
pub fn minute(mut self, minute: u8) -> Self {
self.minute = Some(minute.min(59));
self
}
/// Add the second field. It will be clamped within the range 0-59.
#[inline]
pub fn second(mut self, second: u8) -> Self {
self.second = Some(second.min(59));
self
}
/// Add the offset from UTC in hours. If not specified, the time will be
/// assumed to be local to the viewer's time zone. It will be clamped within
/// the range -23-23.
#[inline]
pub fn utc_offset_hour(mut self, hour: i8) -> Self {
self.utc_offset_hour = Some(hour.clamp(-23, 23));
self
}
/// Add the offset from UTC in minutes. This will have the same sign as set in
/// [`Self::utc_offset_hour`]. It will be clamped within the range 0-59.
#[inline]
pub fn utc_offset_minute(mut self, minute: u8) -> Self {
self.utc_offset_minute = minute.min(59);
self
}
}
impl Primitive for Date {
fn write(self, buf: &mut Vec<u8>) {
write!(buf, "(D:{:04}", self.year).unwrap();
self.month
.and_then(|month| {
write!(buf, "{:02}", month).unwrap();
self.day
})
.and_then(|day| {
write!(buf, "{:02}", day).unwrap();
self.hour
})
.and_then(|hour| {
write!(buf, "{:02}", hour).unwrap();
self.minute
})
.and_then(|minute| {
write!(buf, "{:02}", minute).unwrap();
self.second
})
.and_then(|second| {
write!(buf, "{:02}", second).unwrap();
self.utc_offset_hour
})
.map(|utc_offset_hour| {
if utc_offset_hour == 0 && self.utc_offset_minute == 0 {
buf.push(b'Z');
} else {
write!(buf, "{:+03}'{:02}", utc_offset_hour, self.utc_offset_minute)
.unwrap();
}
});
buf.push(b')');
}
}
/// Writer for an arbitrary object.
#[must_use = "not consuming this leaves the writer in an inconsistent state"]
pub struct Obj<'a> {
buf: &'a mut Vec<u8>,
indirect: bool,
indent: u8,
}
impl<'a> Obj<'a> {
/// Start a new direct object.
#[inline]
pub(crate) fn direct(buf: &'a mut Vec<u8>, indent: u8) -> Self {
Self { buf, indirect: false, indent }
}
/// Start a new indirect object.
#[inline]
pub(crate) fn indirect(buf: &'a mut Vec<u8>, id: Ref) -> Self {
buf.push_int(id.get());
buf.extend(b" 0 obj\n");
Self { buf, indirect: true, indent: 0 }
}
/// Write a primitive object.
#[inline]
pub fn primitive<T: Primitive>(self, value: T) {
value.write(self.buf);
if self.indirect {
self.buf.extend(b"\nendobj\n\n");
}
}
/// Start writing an array.
#[inline]
pub fn array(self) -> Array<'a> {
self.start()
}
/// Start writing a dictionary.
#[inline]
pub fn dict(self) -> Dict<'a> {
self.start()
}
/// Start writing with an arbitrary writer.
///
/// For example, using this, you could write a Type 1 font directly into
/// a page's resource directionary.
/// ```
/// use pdf_writer::{PdfWriter, Ref, Name, writers::Type1Font};
///
/// let mut w = PdfWriter::new();
/// w.page(Ref::new(1))
/// .resources()
/// .fonts()
/// .insert(Name(b"F1"))
/// .start::<Type1Font>()
/// .base_font(Name(b"Helvetica"));
/// ```
#[inline]
pub fn start<W: Writer<'a>>(self) -> W {
W::start(self)
}
}
/// A writer for a specific type of PDF object.
pub trait Writer<'a> {
/// Start writing the object.
fn start(obj: Obj<'a>) -> Self;
}
/// Rewrites a writer's lifetime.
///
/// This is a workaround to ignore the `'b` lifetime in a
/// `TypedArray<'a, SomeWriter<'b>>` because that lifetime is meaningless. What
/// we actually want is each item's `SomeWriter` to borrow from the array itself.
pub trait Rewrite<'a> {
/// The writer with the rewritten lifetime.
type Output: Writer<'a>;
}
/// Writer for an array.
pub struct Array<'a> {
buf: &'a mut Vec<u8>,
indirect: bool,
indent: u8,
len: i32,
}
writer!(Array: |obj| {
obj.buf.push(b'[');
Self {
buf: obj.buf,
indirect: obj.indirect,
indent: obj.indent,
len: 0,
}
});
impl<'a> Array<'a> {
/// The number of written items.
#[inline]
pub fn len(&self) -> i32 {
self.len
}
/// Start writing an arbitrary item.
#[inline]
pub fn push(&mut self) -> Obj<'_> {
if self.len != 0 {
self.buf.push(b' ');
}
self.len += 1;
Obj::direct(self.buf, self.indent)
}
/// Write an item with a primitive value.
///
/// This is a shorthand for `array.push().primitive(value)`.
#[inline]
pub fn item<T: Primitive>(&mut self, value: T) -> &mut Self {
self.push().primitive(value);
self
}
/// Write a sequence of items with primitive values.
#[inline]
pub fn items<T: Primitive>(
&mut self,
values: impl IntoIterator<Item = T>,
) -> &mut Self {
for value in values {
self.item(value);
}
self
}
/// Convert into a typed version.
#[inline]
pub fn typed<T: Type>(self) -> TypedArray<'a, T> {
TypedArray::wrap(self)
}
}
impl Drop for Array<'_> {
#[inline]
fn drop(&mut self) {
self.buf.push(b']');
if self.indirect {
self.buf.extend(b"\nendobj\n\n");
}
}
}
/// Writer for an array of items of a fixed type.
pub struct TypedArray<'a, T> {
array: Array<'a>,
phantom: PhantomData<fn() -> T>,
}
impl<'a, T> Writer<'a> for TypedArray<'a, T> {
fn start(obj: Obj<'a>) -> Self {
Self { array: obj.array(), phantom: PhantomData }
}
}
impl<'a, 'any, T> Rewrite<'a> for TypedArray<'any, T> {
type Output = TypedArray<'a, T>;
}
impl<'a, T> TypedArray<'a, T>
where
T: Type,
{
/// Wrap an array to make it type-safe.
#[inline]
pub fn wrap(array: Array<'a>) -> Self {
Self { array, phantom: PhantomData }
}
/// The number of written items.
#[inline]
pub fn len(&self) -> i32 {
self.array.len()
}
/// Write an item.
#[inline]
pub fn item(&mut self, value: T) -> &mut Self
where
T: Primitive,
{
self.array.item(value);
self
}
/// Write a sequence of items.
#[inline]
pub fn items(&mut self, values: impl IntoIterator<Item = T>) -> &mut Self
where
T: Primitive,
{
self.array.items(values);
self
}
/// Start writing an item with the typed writer.
///
/// Returns `T` but with its lifetime rewritten from `'a` to `'b`.
#[inline]
pub fn push<'b>(&'b mut self) -> <T as Rewrite>::Output
where
T: Writer<'a> + Rewrite<'b>,
{
<T as Rewrite>::Output::start(self.array.push())
}
}
/// Writer for a dictionary.
pub struct Dict<'a> {
buf: &'a mut Vec<u8>,
indirect: bool,
indent: u8,
len: i32,
}
writer!(Dict: |obj| {
obj.buf.extend(b"<<");
Self {
buf: obj.buf,
indirect: obj.indirect,
indent: obj.indent.saturating_add(2),
len: 0,
}
});
impl<'a> Dict<'a> {
/// The number of written pairs.
#[inline]
pub fn len(&self) -> i32 {
self.len
}
/// Start writing a pair with an arbitrary value.
#[inline]
pub fn insert(&mut self, key: Name) -> Obj<'_> {
self.len += 1;
self.buf.push(b'\n');
for _ in 0..self.indent {
self.buf.push(b' ');
}
self.buf.push_val(key);
self.buf.push(b' ');
Obj::direct(self.buf, self.indent)
}
/// Write a pair with a primitive value.
///
/// This is a shorthand for `dict.insert(key).primitive(value)`.
#[inline]
pub fn pair<T: Primitive>(&mut self, key: Name, value: T) -> &mut Self {
self.insert(key).primitive(value);
self
}
/// Write a sequence of pairs with primitive values.
pub fn pairs<'n, T: Primitive>(
&mut self,
pairs: impl IntoIterator<Item = (Name<'n>, T)>,
) -> &mut Self {
for (key, value) in pairs {
self.pair(key, value);
}
self
}
/// Convert into a typed version.
#[inline]
pub fn typed<T: Type>(self) -> TypedDict<'a, T> {
TypedDict::wrap(self)
}
}
impl Drop for Dict<'_> {
#[inline]
fn drop(&mut self) {
if self.len != 0 {
self.buf.push(b'\n');
for _ in 0..self.indent - 2 {
self.buf.push(b' ');
}
}
self.buf.extend(b">>");
if self.indirect {
self.buf.extend(b"\nendobj\n\n");
}
}
}
/// Writer for a dictionary mapping to a fixed type.
pub struct TypedDict<'a, T> {
dict: Dict<'a>,
phantom: PhantomData<fn() -> T>,
}
impl<'a, T> Writer<'a> for TypedDict<'a, T> {
fn start(obj: Obj<'a>) -> Self {
Self { dict: obj.dict(), phantom: PhantomData }
}
}
impl<'a, 'any, T> Rewrite<'a> for TypedDict<'any, T> {
type Output = TypedDict<'a, T>;
}
impl<'a, T> TypedDict<'a, T>
where
T: Type,
{
/// Wrap a dictionary to make it type-safe.
#[inline]
pub fn wrap(dict: Dict<'a>) -> Self {
Self { dict, phantom: PhantomData }
}
/// The number of written pairs.
#[inline]
pub fn len(&self) -> i32 {
self.dict.len()
}
/// Write a key-value pair.
#[inline]
pub fn pair(&mut self, key: Name, value: T) -> &mut Self
where
T: Primitive,
{
self.dict.pair(key, value);
self
}
/// Write a sequence of key-value pairs.
#[inline]
pub fn pairs<'n>(
&mut self,
pairs: impl IntoIterator<Item = (Name<'n>, T)>,
) -> &mut Self
where
T: Primitive,
{
self.dict.pairs(pairs);
self
}
/// Start writing a pair with the typed writer.
///
/// Returns `T` but with its lifetime rewritten from `'a` to `'b`.
#[inline]
pub fn insert<'b>(&'b mut self, key: Name) -> <T as Rewrite>::Output
where
T: Writer<'a> + Rewrite<'b>,
{
<T as Rewrite>::Output::start(self.dict.insert(key))
}
}
/// Writer for an indirect stream object.
pub struct Stream<'a> {
dict: ManuallyDrop<Dict<'a>>,
data: &'a [u8],
}
impl<'a> Stream<'a> {
/// Start writing a stream.
///
/// Panics if the object writer is not indirect or the stream length exceeds
/// `i32::MAX`.
pub(crate) fn start(obj: Obj<'a>, data: &'a [u8]) -> Self {
assert!(obj.indirect);
let mut dict = obj.dict();
dict.pair(
Name(b"Length"),
i32::try_from(data.len()).unwrap_or_else(|_| {
panic!("data length (is `{}`) must be <= i32::MAX", data.len());
}),
);
Self { dict: ManuallyDrop::new(dict), data }
}
/// Write the `/Filter` attribute.
pub fn filter(&mut self, filter: Filter) -> &mut Self {
self.pair(Name(b"Filter"), filter.to_name());
self
}
}
impl Drop for Stream<'_> {
fn drop(&mut self) {
self.dict.buf.extend(b"\n>>");
self.dict.buf.extend(b"\nstream\n");
self.dict.buf.extend(self.data.as_ref());
self.dict.buf.extend(b"\nendstream");
self.dict.buf.extend(b"\nendobj\n\n");
}
}
deref!('a, Stream<'a> => Dict<'a>, dict);
/// A compression filter for a stream.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[allow(missing_docs)]
pub enum Filter {
AsciiHexDecode,
Ascii85Decode,
LzwDecode,
FlateDecode,
RunLengthDecode,
CcittFaxDecode,
Jbig2Decode,
DctDecode,
JpxDecode,
Crypt,
}
impl Filter {
pub(crate) fn to_name(self) -> Name<'static> {
match self {
Self::AsciiHexDecode => Name(b"ASCIIHexDecode"),
Self::Ascii85Decode => Name(b"ASCII85Decode"),
Self::LzwDecode => Name(b"LZWDecode"),
Self::FlateDecode => Name(b"FlateDecode"),
Self::RunLengthDecode => Name(b"RunLengthDecode"),
Self::CcittFaxDecode => Name(b"CCITTFaxDecode"),
Self::Jbig2Decode => Name(b"JBIG2Decode"),
Self::DctDecode => Name(b"DCTDecode"),
Self::JpxDecode => Name(b"JPXDecode"),
Self::Crypt => Name(b"Crypt"),
}
}
}
/// Writer for a _name tree node_.
///
/// Name trees associate a large number of names with PDF objects. They are
/// lexically ordered search trees. Root nodes may directly contain all leafs,
/// however, this might degrade performance for very large numbers of
/// name-object pairs.
///
/// For each node, either the `/Kids` or `/Names` attribute must be set, but
/// never both.
pub struct NameTree<'a, T> {
dict: Dict<'a>,
phantom: PhantomData<T>,
}
impl<'a, T> Writer<'a> for NameTree<'a, T> {
fn start(obj: Obj<'a>) -> Self {
Self { dict: obj.dict(), phantom: PhantomData }
}
}
impl<'a, 'any, T> Rewrite<'a> for NameTree<'any, T> {
type Output = NameTree<'a, T>;
}
impl<T> NameTree<'_, T> {
/// Start writing the `/Kids` attribute with the children of this node.
pub fn kids(&mut self) -> TypedArray<'_, Ref> {
self.dict.insert(Name(b"Kids")).array().typed()
}
/// Start writing the `/Names` attribute to set the immediate name-to-object
/// mappings of this node.
pub fn names(&mut self) -> NameTreeEntries<'_, T> {
self.dict.insert(Name(b"Names")).start()
}
/// Write the `/Limits` array to set the range of names in this node. This
/// is required for every node except the root node.
pub fn limits(&mut self, min: Name, max: Name) -> &mut Self {
self.dict.insert(Name(b"Limits")).array().typed().items([min, max]);
self
}
}
/// Writer for a _name tree names_ array.
///
/// The children must be added in ascending lexical order. Their minimum and
/// maximum keys must not exceed the `/Limits` property of the parent [`NameTree`]
/// node. This struct is created by [`NameTree::names`].
pub struct NameTreeEntries<'a, T> {
arr: Array<'a>,
phantom: PhantomData<T>,
}
impl<'a, T> Writer<'a> for NameTreeEntries<'a, T> {
fn start(obj: Obj<'a>) -> Self {
Self { arr: obj.array(), phantom: PhantomData }
}
}
impl<'a, 'any, T> Rewrite<'a> for NameTreeEntries<'any, T> {
type Output = NameTreeEntries<'a, T>;
}
impl<T> NameTreeEntries<'_, T>
where
T: Primitive,
{
/// Insert a name-value pair.
pub fn insert(&mut self, key: Str, value: T) -> &mut Self {
self.arr.item(key);
self.arr.item(value);
self
}
}
/// Writer for a _number tree node_.
///
/// Number trees associate a many integers with PDF objects. They are search
/// trees in ascending order. Root nodes may directly contain all leafs,
/// however, this might degrade performance for very large numbers of
/// integer-object pairs.
///
/// For each node, either the `/Kids` or `/Nums` attribute must be set, but
/// never both.
pub struct NumberTree<'a, T> {
dict: Dict<'a>,
phantom: PhantomData<T>,
}
impl<'a, T> Writer<'a> for NumberTree<'a, T> {
fn start(obj: Obj<'a>) -> Self {
Self { dict: obj.dict(), phantom: PhantomData }
}
}
impl<'a, 'any, T> Rewrite<'a> for NumberTree<'any, T> {
type Output = NumberTree<'a, T>;
}
impl<T> NumberTree<'_, T> {
/// Start writing the `/Kids` attribute with the children of this node.
pub fn kids(&mut self) -> TypedArray<'_, Ref> {
self.dict.insert(Name(b"Kids")).array().typed()
}
/// Start writing the `/Nums` attribute to set the immediate
/// number-to-object mappings of this node.
pub fn nums(&mut self) -> NumberTreeEntries<'_, T> {
self.dict.insert(Name(b"Nums")).start()
}
/// Write the `/Limits` array to set the range of numbers in this node. This
/// is required for every node except the root node.
pub fn limits(&mut self, min: i32, max: i32) -> &mut Self {
self.dict.insert(Name(b"Limits")).array().typed().items([min, max]);
self
}
}
/// Writer for a _number tree numbers_ array.
///
/// The children must be added in ascending order. Their minimum and
/// maximum keys must not exceed the `/Limits` property of the parent [`NumberTree`]
/// node. This struct is created by [`NumberTree::nums`].
pub struct NumberTreeEntries<'a, T> {
arr: Array<'a>,
phantom: PhantomData<T>,
}
impl<'a, T> Writer<'a> for NumberTreeEntries<'a, T> {
fn start(obj: Obj<'a>) -> Self {
Self { arr: obj.array(), phantom: PhantomData }
}
}
impl<'a, 'any, T> Rewrite<'a> for NumberTreeEntries<'any, T> {
type Output = NumberTreeEntries<'a, T>;
}
impl<T> NumberTreeEntries<'_, T>
where
T: Primitive,
{
/// Insert a number-value pair.
pub fn insert(&mut self, key: i32, value: T) -> &mut Self {
self.arr.item(key);
self.arr.item(value);
self
}
}
/// Finish objects in postfix-style.
///
/// In many cases you can use writers in builder-pattern style so that they are
/// automatically dropped at the appropriate time. Sometimes though you need to
/// bind a writer to a variable and still want to regain access to the
/// [`PdfWriter`] in the same scope. In that case, you need to manually invoke
/// the writer's `Drop` implementation. You can of course, just write
/// `drop(array)` to finish your array, but you might find it more aesthetically
/// pleasing to write `array.finish()`. That's what this trait is for.
///
/// ```
/// # use pdf_writer::{PdfWriter, Ref, Finish, Name, Str};
/// # let mut writer = PdfWriter::new();
/// let mut array = writer.indirect(Ref::new(1)).array();
/// array.push().dict().pair(Name(b"Key"), Str(b"Value"));
/// array.item(2);
/// array.finish(); // instead of drop(array)
///
/// // Do more stuff with the writer ...
/// ```
pub trait Finish: Sized {
/// Does nothing but move `self`, equivalent to [`drop`].
#[inline]
fn finish(self) {}
}
impl<T> Finish for T {}