1use std::path::Path;
6
7use pdfboss_core::{Dict, Name, ObjRef, Object};
8
9use crate::canvas::{Canvas, CanvasParts};
10use crate::content::serialize_ops;
11use crate::element::{self, Content};
12use crate::error::{Error, Result};
13use crate::font::Standard14;
14use crate::sink::AsyncByteSink;
15use crate::writer::{WriteOptions, Writer};
16
17#[derive(Debug, Clone, Copy, PartialEq, Default)]
19pub enum PageSize {
20 A3,
22 #[default]
24 A4,
25 A5,
27 Letter,
29 Legal,
31 Custom {
33 width: f32,
35 height: f32,
37 },
38}
39
40impl PageSize {
41 pub fn dimensions(self) -> (f32, f32) {
43 match self {
44 PageSize::A3 => (841.89, 1190.55),
45 PageSize::A4 => (595.28, 841.89),
46 PageSize::A5 => (419.53, 595.28),
47 PageSize::Letter => (612.0, 792.0),
48 PageSize::Legal => (612.0, 1008.0),
49 PageSize::Custom { width, height } => (width, height),
50 }
51 }
52
53 pub fn landscape(self) -> PageSize {
55 let (width, height) = self.dimensions();
56 PageSize::Custom {
57 width: height,
58 height: width,
59 }
60 }
61
62 pub fn by_name(name: &str) -> Option<PageSize> {
66 let name = name.to_ascii_lowercase();
67 match name.as_str() {
68 "a3" => return Some(PageSize::A3),
69 "a4" => return Some(PageSize::A4),
70 "a5" => return Some(PageSize::A5),
71 "letter" => return Some(PageSize::Letter),
72 "legal" => return Some(PageSize::Legal),
73 "tabloid" => {
74 return Some(PageSize::Custom {
75 width: 792.0,
76 height: 1224.0,
77 })
78 }
79 _ => {}
80 }
81 let (table, index) = match (name.get(..1), name.get(1..)) {
82 (Some("a"), Some(index)) => (&A_SERIES_MM, index),
83 (Some("b"), Some(index)) => (&B_SERIES_MM, index),
84 _ => return None,
85 };
86 let index: usize = index.parse().ok()?;
87 let (width, height) = *table.get(index)?;
88 Some(PageSize::Custom {
89 width: points_from_mm(width),
90 height: points_from_mm(height),
91 })
92 }
93
94 pub fn parse(text: &str) -> Option<PageSize> {
99 let text = text.trim();
100 if let Some(size) = PageSize::by_name(text) {
101 return Some(size);
102 }
103 let (width, height) = text.split_once(['x', 'X'])?;
104 Some(PageSize::Custom {
105 width: parse_length(width)?,
106 height: parse_length(height)?,
107 })
108 }
109
110 pub const ACCEPTED: &'static str = "a name (a0 to a10, b0 to b10, letter, legal, tabloid) \
112 or <width>x<height> in pt, mm, cm or in";
113}
114
115const A_SERIES_MM: [(f32, f32); 11] = [
117 (841.0, 1189.0),
118 (594.0, 841.0),
119 (420.0, 594.0),
120 (297.0, 420.0),
121 (210.0, 297.0),
122 (148.0, 210.0),
123 (105.0, 148.0),
124 (74.0, 105.0),
125 (52.0, 74.0),
126 (37.0, 52.0),
127 (26.0, 37.0),
128];
129
130const B_SERIES_MM: [(f32, f32); 11] = [
132 (1000.0, 1414.0),
133 (707.0, 1000.0),
134 (500.0, 707.0),
135 (353.0, 500.0),
136 (250.0, 353.0),
137 (176.0, 250.0),
138 (125.0, 176.0),
139 (88.0, 125.0),
140 (62.0, 88.0),
141 (44.0, 62.0),
142 (31.0, 44.0),
143];
144
145fn points_from_mm(mm: f32) -> f32 {
146 mm * 72.0 / 25.4
147}
148
149fn parse_length(text: &str) -> Option<f32> {
152 let text = text.trim();
153 let (number, points_per_unit) = if let Some(number) = text.strip_suffix("mm") {
154 (number, 72.0 / 25.4)
155 } else if let Some(number) = text.strip_suffix("cm") {
156 (number, 72.0 / 2.54)
157 } else if let Some(number) = text.strip_suffix("in") {
158 (number, 72.0)
159 } else if let Some(number) = text.strip_suffix("pt") {
160 (number, 1.0)
161 } else {
162 (text, 1.0)
163 };
164 let value: f32 = number.trim().parse().ok()?;
165 let points = value * points_per_unit;
166 (points.is_finite() && points > 0.0).then_some(points)
167}
168
169pub use pdfboss_core::Date;
174
175#[derive(Debug, Clone, Default, PartialEq)]
178pub struct Metadata {
179 pub title: Option<String>,
181 pub author: Option<String>,
183 pub subject: Option<String>,
185 pub keywords: Option<String>,
187 pub creator: Option<String>,
189 pub producer: Option<String>,
191 pub creation_date: Option<Date>,
193 pub modification_date: Option<Date>,
195}
196
197#[derive(Debug, Default)]
199pub struct Page {
200 pub size: PageSize,
202 pub rotation: i32,
204 pub canvas: Canvas,
206 pub content: Vec<Content>,
209 pub links: Vec<LinkAnnotation>,
211}
212
213#[derive(Debug, Clone, PartialEq)]
219pub struct LinkAnnotation {
220 pub rect: [f32; 4],
222 pub target: LinkTarget,
224}
225
226#[derive(Debug, Clone, PartialEq)]
228pub enum LinkTarget {
229 Uri(String),
231 Page(usize),
234}
235
236impl Page {
237 pub fn new(size: PageSize) -> Page {
239 Page {
240 size,
241 ..Page::default()
242 }
243 }
244}
245
246#[derive(Debug, Clone, Default, PartialEq)]
251pub struct Outline {
252 pub bookmarks: Vec<Bookmark>,
254}
255
256#[derive(Debug, Clone, Default, PartialEq)]
258pub struct Bookmark {
259 pub title: String,
261 pub page: usize,
264 pub children: Vec<Bookmark>,
266}
267
268impl Bookmark {
269 pub fn new(title: impl Into<String>, page: usize) -> Bookmark {
271 Bookmark {
272 title: title.into(),
273 page,
274 children: Vec::new(),
275 }
276 }
277}
278
279#[derive(Debug, Clone, PartialEq)]
284pub struct Attachment {
285 pub name: String,
288 pub data: Vec<u8>,
291 pub mime: Option<String>,
294 pub modified: Option<Date>,
296 pub description: Option<String>,
298}
299
300pub use pdfboss_core::page_label::{LabelStyle, PageLabel};
301
302#[derive(Debug, Clone, Copy, PartialEq)]
305pub enum PageLayout {
306 SinglePage,
308 OneColumn,
310 TwoColumnLeft,
312 TwoColumnRight,
314 TwoPageLeft,
316 TwoPageRight,
318}
319
320#[derive(Debug, Clone, Copy, PartialEq)]
323pub enum PageMode {
324 UseNone,
326 UseOutlines,
328 UseThumbs,
330 FullScreen,
332}
333
334#[derive(Debug, Clone, Default, PartialEq)]
337pub struct Viewer {
338 pub layout: Option<PageLayout>,
340 pub mode: Option<PageMode>,
342 pub open_to: Option<usize>,
345}
346
347#[derive(Debug, Default)]
350pub struct Pdf {
351 pub metadata: Option<Metadata>,
353 pub pages: Vec<Page>,
355 pub outline: Option<Outline>,
357 pub attachments: Vec<Attachment>,
361 pub page_labels: Vec<PageLabel>,
366 pub viewer: Option<Viewer>,
368 pub options: WriteOptions,
370}
371
372impl Pdf {
373 pub fn to_bytes(self) -> Result<Vec<u8>> {
382 let (w, root) = self.assemble()?;
383 w.finish(root)
384 }
385
386 pub fn write_into(self, out: impl std::io::Write) -> Result<()> {
391 let (w, root) = self.assemble()?;
392 w.finish_into(root, out)
393 }
394
395 pub async fn write_into_with<S: AsyncByteSink>(self, sink: S) -> Result<S> {
399 let (w, root) = self.assemble()?;
400 w.finish_into_with(root, sink).await
401 }
402
403 fn assemble(self) -> Result<(Writer, ObjRef)> {
408 let Pdf {
409 metadata,
410 pages,
411 outline,
412 attachments,
413 page_labels,
414 viewer,
415 options,
416 } = self;
417 if pages.is_empty() {
418 return Err(Error::Other(
419 "a document needs at least one page".to_string(),
420 ));
421 }
422 let mut w = Writer::new(options);
423 let pages_root = w.reserve();
424 let page_count = pages.len();
425 let page_refs: Vec<ObjRef> = pages.iter().map(|_| w.reserve()).collect();
426 let mut font_cache: Vec<(Standard14, ObjRef)> = Vec::new();
427 for (index, page) in pages.into_iter().enumerate() {
428 let Page {
429 size,
430 rotation,
431 mut canvas,
432 content,
433 mut links,
434 } = page;
435 if rotation % 90 != 0 {
436 return Err(Error::Other(format!(
437 "page rotation {rotation} is not a multiple of 90"
438 )));
439 }
440 element::lower(content, &mut canvas, &mut links)?;
441 let (width, height) = size.dimensions();
442 let parts = canvas.into_parts();
443 let (content, resources) = lower_canvas(&mut w, parts, &mut font_cache)?;
444 let content_ref = w.put_stream(Dict::new(), content);
445 let mut dict = Dict::new();
446 dict.insert(name("Type"), Object::Name(name("Page")));
447 dict.insert(name("Parent"), Object::Ref(pages_root));
448 dict.insert(
449 name("MediaBox"),
450 Object::Array(vec![
451 Object::Int(0),
452 Object::Int(0),
453 Object::Real(f64::from(width)),
454 Object::Real(f64::from(height)),
455 ]),
456 );
457 dict.insert(name("Contents"), Object::Ref(content_ref));
458 dict.insert(name("Resources"), Object::Dict(resources));
459 if !links.is_empty() {
460 let mut annots = Vec::with_capacity(links.len());
461 for link in links {
462 let action = match link.target {
463 LinkTarget::Uri(uri) => {
464 let mut action = Dict::new();
465 action.insert(name("S"), Object::Name(name("URI")));
466 action.insert(name("URI"), text_string(&uri));
467 action
468 }
469 LinkTarget::Page(target_index) => {
470 let target = page_refs.get(target_index).copied().ok_or_else(|| {
471 Error::Other(format!(
472 "link target page {target_index} is out of range: the document has {page_count} pages"
473 ))
474 })?;
475 let mut action = Dict::new();
476 action.insert(name("S"), Object::Name(name("GoTo")));
477 action.insert(
478 name("D"),
479 Object::Array(vec![
480 Object::Ref(target),
481 Object::Name(name("XYZ")),
482 Object::Null,
483 Object::Null,
484 Object::Null,
485 ]),
486 );
487 action
488 }
489 };
490 let mut annot = Dict::new();
491 annot.insert(name("Type"), Object::Name(name("Annot")));
492 annot.insert(name("Subtype"), Object::Name(name("Link")));
493 annot.insert(
494 name("Rect"),
495 Object::Array(
496 link.rect
497 .iter()
498 .map(|v| Object::Real(f64::from(*v)))
499 .collect(),
500 ),
501 );
502 annot.insert(
503 name("Border"),
504 Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(0)]),
505 );
506 annot.insert(name("A"), Object::Dict(action));
507 annots.push(Object::Ref(w.put(Object::Dict(annot))));
508 }
509 dict.insert(name("Annots"), Object::Array(annots));
510 }
511 if rotation != 0 {
512 dict.insert(name("Rotate"), Object::Int(i64::from(rotation)));
513 }
514 w.fill(page_refs[index], Object::Dict(dict))?;
515 }
516 let kids: Vec<Object> = page_refs.iter().copied().map(Object::Ref).collect();
517 let mut tree = Dict::new();
518 tree.insert(name("Type"), Object::Name(name("Pages")));
519 tree.insert(name("Count"), Object::Int(kids.len() as i64));
520 tree.insert(name("Kids"), Object::Array(kids));
521 w.fill(pages_root, Object::Dict(tree))?;
522 let xmp_ref = match metadata {
523 Some(meta) => {
524 let packet = crate::xmp::packet(&meta);
525 if let Some(info) = info_dict(meta) {
526 let info_ref = w.put(Object::Dict(info));
527 w.set_info(info_ref);
528 }
529 let mut xmp_dict = Dict::new();
530 xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
531 xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
532 Some(w.put_stream_raw(xmp_dict, packet))
533 }
534 None => None,
535 };
536 let outline_ref = match outline {
537 Some(outline) if !outline.bookmarks.is_empty() => {
538 let root_ref = w.reserve();
539 let refs = reserve_bookmarks(&mut w, &outline.bookmarks);
540 let (first, last, count) = fill_bookmarks(
541 &mut w,
542 outline.bookmarks,
543 &refs,
544 root_ref,
545 &page_refs,
546 page_count,
547 )?;
548 let mut dict = Dict::new();
549 dict.insert(name("Type"), Object::Name(name("Outlines")));
550 dict.insert(name("First"), Object::Ref(first));
551 dict.insert(name("Last"), Object::Ref(last));
552 dict.insert(name("Count"), Object::Int(count));
553 w.fill(root_ref, Object::Dict(dict))?;
554 Some(root_ref)
555 }
556 _ => None,
557 };
558 let names = embedded_files_dict(&mut w, attachments)?;
559 let page_labels_entry = page_labels_dict(page_labels)?;
560 let mut catalog = Dict::new();
561 catalog.insert(name("Type"), Object::Name(name("Catalog")));
562 catalog.insert(name("Pages"), Object::Ref(pages_root));
563 if let Some(outline_ref) = outline_ref {
564 catalog.insert(name("Outlines"), Object::Ref(outline_ref));
565 }
566 if let Some(xmp_ref) = xmp_ref {
567 catalog.insert(name("Metadata"), Object::Ref(xmp_ref));
568 }
569 if let Some(names) = names {
570 catalog.insert(name("Names"), Object::Dict(names));
571 }
572 if let Some(page_labels_entry) = page_labels_entry {
573 catalog.insert(name("PageLabels"), Object::Dict(page_labels_entry));
574 }
575 if let Some(viewer) = viewer {
576 let Viewer {
577 layout,
578 mode,
579 open_to,
580 } = viewer;
581 if let Some(layout) = layout {
582 catalog.insert(
583 name("PageLayout"),
584 Object::Name(name(page_layout_name(layout))),
585 );
586 }
587 if let Some(mode) = mode {
588 catalog.insert(name("PageMode"), Object::Name(name(page_mode_name(mode))));
589 }
590 if let Some(open_to) = open_to {
591 let target = page_refs.get(open_to).copied().ok_or_else(|| {
592 Error::Other(format!(
593 "open_to target page {open_to} is out of range: the document has {page_count} pages"
594 ))
595 })?;
596 catalog.insert(
597 name("OpenAction"),
598 Object::Array(vec![
599 Object::Ref(target),
600 Object::Name(name("XYZ")),
601 Object::Null,
602 Object::Null,
603 Object::Null,
604 ]),
605 );
606 }
607 }
608 let root = w.put(Object::Dict(catalog));
609 Ok((w, root))
610 }
611
612 pub fn save(self, path: impl AsRef<Path>) -> Result<()> {
614 let path = path.as_ref();
615 let bytes = self.to_bytes()?;
616 std::fs::write(path, bytes)?;
617 Ok(())
618 }
619}
620
621fn name(text: &str) -> Name {
623 Name(text.to_string())
624}
625
626fn info_dict(meta: Metadata) -> Option<Dict> {
630 let mut dict = Dict::new();
631 let texts = [
632 ("Title", meta.title),
633 ("Author", meta.author),
634 ("Subject", meta.subject),
635 ("Keywords", meta.keywords),
636 ("Creator", meta.creator),
637 ("Producer", meta.producer),
638 ];
639 for (key, value) in texts {
640 if let Some(value) = value {
641 dict.insert(name(key), text_string(&value));
642 }
643 }
644 let dates = [
645 ("CreationDate", meta.creation_date),
646 ("ModDate", meta.modification_date),
647 ];
648 for (key, value) in dates {
649 if let Some(date) = value {
650 dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
651 }
652 }
653 if dict.is_empty() {
654 return None;
655 }
656 Some(dict)
657}
658
659const DEFAULT_ATTACHMENT_MIME: &str = "application/octet-stream";
661
662fn embedded_files_dict(w: &mut Writer, mut attachments: Vec<Attachment>) -> Result<Option<Dict>> {
668 if attachments.is_empty() {
669 return Ok(None);
670 }
671 attachments.sort_by(|a, b| a.name.cmp(&b.name));
672 for pair in attachments.windows(2) {
673 if pair[0].name == pair[1].name {
674 return Err(Error::Other(format!(
675 "duplicate attachment name: {:?}",
676 pair[0].name
677 )));
678 }
679 }
680 let mut entries = Vec::with_capacity(attachments.len() * 2);
681 for attachment in attachments {
682 let Attachment {
683 name: file_name,
684 data,
685 mime,
686 modified,
687 description,
688 } = attachment;
689 let mime = mime.unwrap_or_else(|| DEFAULT_ATTACHMENT_MIME.to_string());
690
691 let mut params = Dict::new();
692 params.insert(name("Size"), Object::Int(data.len() as i64));
693 if let Some(modified) = modified {
694 params.insert(
695 name("ModDate"),
696 Object::String(modified.to_pdf_string().into_bytes()),
697 );
698 }
699 let mut stream_dict = Dict::new();
700 stream_dict.insert(name("Type"), Object::Name(name("EmbeddedFile")));
701 stream_dict.insert(name("Subtype"), Object::Name(Name(mime)));
702 stream_dict.insert(name("Params"), Object::Dict(params));
703 let stream_ref = w.put_stream(stream_dict, data);
704
705 let mut ef = Dict::new();
706 ef.insert(name("F"), Object::Ref(stream_ref));
707
708 let mut filespec = Dict::new();
709 filespec.insert(name("Type"), Object::Name(name("Filespec")));
710 filespec.insert(name("F"), text_string(&file_name));
711 filespec.insert(name("UF"), text_string(&file_name));
712 if let Some(description) = description {
713 filespec.insert(name("Desc"), text_string(&description));
714 }
715 filespec.insert(name("EF"), Object::Dict(ef));
716 let filespec_ref = w.put(Object::Dict(filespec));
717
718 entries.push(text_string(&file_name));
719 entries.push(Object::Ref(filespec_ref));
720 }
721 let mut name_tree = Dict::new();
722 name_tree.insert(name("Names"), Object::Array(entries));
723 let mut embedded_files = Dict::new();
724 embedded_files.insert(name("EmbeddedFiles"), Object::Dict(name_tree));
725 Ok(Some(embedded_files))
726}
727
728fn page_labels_dict(mut labels: Vec<PageLabel>) -> Result<Option<Dict>> {
735 if labels.is_empty() {
736 return Ok(None);
737 }
738 for label in &labels {
739 if label.start_at == 0 {
740 return Err(Error::Other(format!(
741 "page label at page {} has start_at 0: numbering starts at 1",
742 label.first_page
743 )));
744 }
745 }
746 labels.sort_by_key(|label| label.first_page);
747 if labels[0].first_page != 0 {
748 return Err(Error::Other("page labels must start at page 0".to_string()));
749 }
750 for pair in labels.windows(2) {
751 if pair[0].first_page == pair[1].first_page {
752 return Err(Error::Other(format!(
753 "duplicate page label at page {}",
754 pair[0].first_page
755 )));
756 }
757 }
758 let mut nums = Vec::with_capacity(labels.len() * 2);
759 for label in labels {
760 let PageLabel {
761 first_page,
762 style,
763 prefix,
764 start_at,
765 } = label;
766 let mut range = Dict::new();
767 if let Some(style) = style {
768 range.insert(name("S"), Object::Name(name(style.code())));
769 }
770 if let Some(prefix) = prefix {
771 range.insert(name("P"), text_string(&prefix));
772 }
773 if start_at != 1 {
774 range.insert(name("St"), Object::Int(i64::from(start_at)));
775 }
776 nums.push(Object::Int(first_page as i64));
777 nums.push(Object::Dict(range));
778 }
779 let mut dict = Dict::new();
780 dict.insert(name("Nums"), Object::Array(nums));
781 Ok(Some(dict))
782}
783
784fn page_layout_name(layout: PageLayout) -> &'static str {
786 match layout {
787 PageLayout::SinglePage => "SinglePage",
788 PageLayout::OneColumn => "OneColumn",
789 PageLayout::TwoColumnLeft => "TwoColumnLeft",
790 PageLayout::TwoColumnRight => "TwoColumnRight",
791 PageLayout::TwoPageLeft => "TwoPageLeft",
792 PageLayout::TwoPageRight => "TwoPageRight",
793 }
794}
795
796fn page_mode_name(mode: PageMode) -> &'static str {
798 match mode {
799 PageMode::UseNone => "UseNone",
800 PageMode::UseOutlines => "UseOutlines",
801 PageMode::UseThumbs => "UseThumbs",
802 PageMode::FullScreen => "FullScreen",
803 }
804}
805
806struct BookmarkRef {
810 r: ObjRef,
811 children: Vec<BookmarkRef>,
812}
813
814fn reserve_bookmarks(w: &mut Writer, bookmarks: &[Bookmark]) -> Vec<BookmarkRef> {
819 bookmarks
820 .iter()
821 .map(|bookmark| BookmarkRef {
822 r: w.reserve(),
823 children: reserve_bookmarks(w, &bookmark.children),
824 })
825 .collect()
826}
827
828fn fill_bookmarks(
835 w: &mut Writer,
836 bookmarks: Vec<Bookmark>,
837 refs: &[BookmarkRef],
838 parent: ObjRef,
839 page_refs: &[ObjRef],
840 page_count: usize,
841) -> Result<(ObjRef, ObjRef, i64)> {
842 let last_index = bookmarks.len() - 1;
843 let mut total = 0i64;
844 for (index, bookmark) in bookmarks.into_iter().enumerate() {
845 let Bookmark {
846 title,
847 page,
848 children,
849 } = bookmark;
850 let dest = page_refs.get(page).copied().ok_or_else(|| {
851 Error::Other(format!(
852 "bookmark target page {page} is out of range: the document has {page_count} pages"
853 ))
854 })?;
855 let mut dict = Dict::new();
856 dict.insert(name("Title"), text_string(&title));
857 dict.insert(name("Parent"), Object::Ref(parent));
858 if index > 0 {
859 dict.insert(name("Prev"), Object::Ref(refs[index - 1].r));
860 }
861 if index < last_index {
862 dict.insert(name("Next"), Object::Ref(refs[index + 1].r));
863 }
864 dict.insert(
865 name("Dest"),
866 Object::Array(vec![
867 Object::Ref(dest),
868 Object::Name(name("XYZ")),
869 Object::Null,
870 Object::Null,
871 Object::Null,
872 ]),
873 );
874 let mut subtree_count = 0i64;
875 if !children.is_empty() {
876 let (first, last, count) = fill_bookmarks(
877 w,
878 children,
879 &refs[index].children,
880 refs[index].r,
881 page_refs,
882 page_count,
883 )?;
884 dict.insert(name("First"), Object::Ref(first));
885 dict.insert(name("Last"), Object::Ref(last));
886 dict.insert(name("Count"), Object::Int(count));
887 subtree_count = count;
888 }
889 w.fill(refs[index].r, Object::Dict(dict))?;
890 total += 1 + subtree_count;
891 }
892 Ok((refs[0].r, refs[last_index].r, total))
893}
894
895fn cached_font(
901 w: &mut Writer,
902 font_cache: &mut Vec<(Standard14, ObjRef)>,
903 face: &Standard14,
904) -> ObjRef {
905 if let Some((_, r)) = font_cache.iter().find(|(seen, _)| seen == face) {
906 return *r;
907 }
908 let r = w.put(Object::Dict(face.font_dict()));
909 font_cache.push((*face, r));
910 r
911}
912
913fn lower_canvas(
919 w: &mut Writer,
920 parts: CanvasParts,
921 font_cache: &mut Vec<(Standard14, ObjRef)>,
922) -> Result<(Vec<u8>, Dict)> {
923 let content = serialize_ops(&parts.ops);
924 let mut fonts = Dict::new();
925 for (index, face) in parts.fonts.iter().enumerate() {
926 let font_ref = cached_font(w, font_cache, face);
927 fonts.insert(Name(format!("F{}", index + 1)), Object::Ref(font_ref));
928 }
929 let mut xobjects = Dict::new();
930 for (index, image) in parts.images.iter().enumerate() {
931 let image_ref = image.build_xobject(w);
932 xobjects.insert(Name(format!("Im{}", index + 1)), Object::Ref(image_ref));
933 }
934 for (index, (group_parts, group_bbox)) in parts.groups.into_iter().enumerate() {
935 let group_ref = build_form(w, group_parts, group_bbox, font_cache)?;
936 xobjects.insert(Name(format!("Gp{}", index + 1)), Object::Ref(group_ref));
937 }
938 let mut ext_gstates = Dict::new();
939 for (index, state) in parts.gstates.iter().enumerate() {
940 let gstate_ref = w.put(Object::Dict(state.ext_gstate_dict()));
941 ext_gstates.insert(Name(format!("Gs{}", index + 1)), Object::Ref(gstate_ref));
942 }
943 let mut resources = Dict::new();
944 if !fonts.is_empty() {
945 resources.insert(name("Font"), Object::Dict(fonts));
946 }
947 if !xobjects.is_empty() {
948 resources.insert(name("XObject"), Object::Dict(xobjects));
949 }
950 if !ext_gstates.is_empty() {
951 resources.insert(name("ExtGState"), Object::Dict(ext_gstates));
952 }
953 Ok((content, resources))
954}
955
956fn build_form(
962 w: &mut Writer,
963 parts: CanvasParts,
964 bbox: [f32; 4],
965 font_cache: &mut Vec<(Standard14, ObjRef)>,
966) -> Result<ObjRef> {
967 let (content, resources) = lower_canvas(w, parts, font_cache)?;
968 let mut dict = Dict::new();
969 dict.insert(name("Type"), Object::Name(name("XObject")));
970 dict.insert(name("Subtype"), Object::Name(name("Form")));
971 dict.insert(
972 name("BBox"),
973 Object::Array(bbox.iter().map(|v| Object::Real(f64::from(*v))).collect()),
974 );
975 dict.insert(name("Resources"), Object::Dict(resources));
976 Ok(w.put_stream(dict, content))
977}
978
979pub(crate) fn text_string(value: &str) -> Object {
983 if value.is_ascii() {
984 return Object::String(value.as_bytes().to_vec());
985 }
986 let mut bytes = vec![0xFE, 0xFF];
987 for unit in value.encode_utf16() {
988 bytes.extend_from_slice(&unit.to_be_bytes());
989 }
990 Object::String(bytes)
991}
992
993#[cfg(test)]
994mod tests {
995 use super::*;
996
997 #[test]
998 fn dimensions_match_the_contract() {
999 assert_eq!(PageSize::A3.dimensions(), (841.89, 1190.55));
1000 assert_eq!(PageSize::A4.dimensions(), (595.28, 841.89));
1001 assert_eq!(PageSize::A5.dimensions(), (419.53, 595.28));
1002 assert_eq!(PageSize::Letter.dimensions(), (612.0, 792.0));
1003 assert_eq!(PageSize::Legal.dimensions(), (612.0, 1008.0));
1004 assert_eq!(
1005 PageSize::Custom {
1006 width: 10.0,
1007 height: 20.0
1008 }
1009 .dimensions(),
1010 (10.0, 20.0)
1011 );
1012 }
1013
1014 #[test]
1015 fn by_name_parses_the_five_named_sizes_case_insensitively() {
1016 for (name, expected) in [
1017 ("a3", PageSize::A3),
1018 ("A4", PageSize::A4),
1019 ("a5", PageSize::A5),
1020 ("Letter", PageSize::Letter),
1021 ("LEGAL", PageSize::Legal),
1022 ] {
1023 assert_eq!(PageSize::by_name(name), Some(expected), "{name}");
1024 }
1025 }
1026
1027 #[test]
1028 fn by_name_rejects_anything_else() {
1029 assert_eq!(PageSize::by_name("poster"), None);
1030 assert_eq!(PageSize::by_name(""), None);
1031 }
1032
1033 fn dims(text: &str) -> (f32, f32) {
1034 PageSize::parse(text).expect(text).dimensions()
1035 }
1036
1037 fn close(got: (f32, f32), want: (f32, f32)) -> bool {
1038 (got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01
1039 }
1040
1041 #[test]
1042 fn parse_keeps_the_named_variants_and_trims() {
1043 assert_eq!(PageSize::parse("A4"), Some(PageSize::A4));
1044 assert_eq!(PageSize::parse(" letter "), Some(PageSize::Letter));
1045 }
1046
1047 #[test]
1048 fn every_iso_216_size_parses_to_its_millimetres() {
1049 assert!(close(dims("a0"), (2383.94, 3370.39)));
1050 assert!(close(dims("a1"), (1683.78, 2383.94)));
1051 assert!(close(dims("a2"), (1190.55, 1683.78)));
1052 assert!(close(dims("a4"), (595.28, 841.89)));
1053 assert!(close(dims("a10"), (73.70, 104.88)));
1054 assert!(close(dims("b0"), (2834.65, 4008.19)));
1055 assert!(close(dims("B5"), (498.90, 708.66)));
1056 assert!(close(dims("b10"), (87.87, 124.72)));
1057 assert!(close(dims("tabloid"), (792.0, 1224.0)));
1058 assert_eq!(PageSize::parse("a11"), None);
1059 assert_eq!(PageSize::parse("c4"), None);
1060 assert_eq!(PageSize::parse("a"), None);
1061 }
1062
1063 #[test]
1064 fn dimensions_parse_in_points_and_with_units() {
1065 assert!(close(dims("612x792"), (612.0, 792.0)));
1066 assert!(close(dims("612pt X 792pt"), (612.0, 792.0)));
1067 assert!(close(dims("210mmx297mm"), (595.28, 841.89)));
1068 assert!(close(dims("21cmx29.7cm"), (595.28, 841.89)));
1069 assert!(close(dims("8.5inx11in"), (612.0, 792.0)));
1070 assert!(close(dims("100x5in"), (100.0, 360.0)));
1071 }
1072
1073 #[test]
1074 fn malformed_dimensions_do_not_parse() {
1075 for text in [
1076 "612",
1077 "612x",
1078 "x792",
1079 "0x792",
1080 "-1x5",
1081 "ax5",
1082 "infx5",
1083 "3.4e38inx5",
1084 "5x3e38cm",
1085 "612x792x1",
1086 ] {
1087 assert_eq!(PageSize::parse(text), None, "{text}");
1088 }
1089 }
1090
1091 #[test]
1092 fn landscape_swaps_into_custom() {
1093 assert_eq!(
1094 PageSize::A4.landscape(),
1095 PageSize::Custom {
1096 width: 841.89,
1097 height: 595.28
1098 }
1099 );
1100 assert_eq!(
1101 PageSize::Custom {
1102 width: 1.0,
1103 height: 2.0
1104 }
1105 .landscape(),
1106 PageSize::Custom {
1107 width: 2.0,
1108 height: 1.0
1109 }
1110 );
1111 assert_eq!(PageSize::Letter.landscape().dimensions(), (792.0, 612.0));
1112 }
1113
1114 fn two_page_doc() -> Pdf {
1117 let mut first = Page::new(PageSize::A4);
1118 first
1119 .canvas
1120 .text("Streamed parity", 72.0, 720.0, Standard14::Helvetica, 14.0)
1121 .expect("ASCII encodes");
1122 let image = crate::image::ImageData::gray8(2, 2, vec![0, 85, 170, 255])
1123 .expect("2x2 grayscale builds");
1124 let handle = first.canvas.add_image(image);
1125 first.canvas.draw_image(handle, 72.0, 400.0, 144.0, 144.0);
1126 let mut second = Page::new(PageSize::Letter);
1127 second
1128 .canvas
1129 .text("Page two", 72.0, 700.0, Standard14::TimesRoman, 12.0)
1130 .expect("ASCII encodes");
1131 Pdf {
1132 pages: vec![first, second],
1133 ..Pdf::default()
1134 }
1135 }
1136
1137 #[test]
1141 fn write_into_and_write_into_with_match_to_bytes() {
1142 let bytes = two_page_doc().to_bytes().expect("to_bytes succeeds");
1143 let mut via_io = Vec::new();
1144 two_page_doc()
1145 .write_into(&mut via_io)
1146 .expect("write_into succeeds");
1147 assert_eq!(via_io, bytes);
1148 let via_sink = pdfboss_core::block_on(two_page_doc().write_into_with(Vec::new()))
1149 .expect("write_into_with succeeds");
1150 assert_eq!(via_sink, bytes);
1151 }
1152
1153 #[test]
1154 fn zero_page_document_is_an_error() {
1155 let err = Pdf::default()
1156 .to_bytes()
1157 .expect_err("a page-less document must not serialize");
1158 assert!(err.to_string().contains("at least one page"), "{err}");
1159 }
1160}