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 match name.to_ascii_lowercase().as_str() {
67 "a3" => Some(PageSize::A3),
68 "a4" => Some(PageSize::A4),
69 "a5" => Some(PageSize::A5),
70 "letter" => Some(PageSize::Letter),
71 "legal" => Some(PageSize::Legal),
72 _ => None,
73 }
74 }
75}
76
77pub use pdfboss_core::Date;
82
83#[derive(Debug, Clone, Default, PartialEq)]
86pub struct Metadata {
87 pub title: Option<String>,
89 pub author: Option<String>,
91 pub subject: Option<String>,
93 pub keywords: Option<String>,
95 pub creator: Option<String>,
97 pub producer: Option<String>,
99 pub creation_date: Option<Date>,
101 pub modification_date: Option<Date>,
103}
104
105#[derive(Debug, Default)]
107pub struct Page {
108 pub size: PageSize,
110 pub rotation: i32,
112 pub canvas: Canvas,
114 pub content: Vec<Content>,
117 pub links: Vec<LinkAnnotation>,
119}
120
121#[derive(Debug, Clone, PartialEq)]
127pub struct LinkAnnotation {
128 pub rect: [f32; 4],
130 pub target: LinkTarget,
132}
133
134#[derive(Debug, Clone, PartialEq)]
136pub enum LinkTarget {
137 Uri(String),
139 Page(usize),
142}
143
144impl Page {
145 pub fn new(size: PageSize) -> Page {
147 Page {
148 size,
149 ..Page::default()
150 }
151 }
152}
153
154#[derive(Debug, Clone, Default, PartialEq)]
159pub struct Outline {
160 pub bookmarks: Vec<Bookmark>,
162}
163
164#[derive(Debug, Clone, Default, PartialEq)]
166pub struct Bookmark {
167 pub title: String,
169 pub page: usize,
172 pub children: Vec<Bookmark>,
174}
175
176impl Bookmark {
177 pub fn new(title: impl Into<String>, page: usize) -> Bookmark {
179 Bookmark {
180 title: title.into(),
181 page,
182 children: Vec::new(),
183 }
184 }
185}
186
187#[derive(Debug, Clone, PartialEq)]
192pub struct Attachment {
193 pub name: String,
196 pub data: Vec<u8>,
199 pub mime: Option<String>,
202 pub modified: Option<Date>,
204 pub description: Option<String>,
206}
207
208pub use pdfboss_core::page_label::{LabelStyle, PageLabel};
209
210#[derive(Debug, Clone, Copy, PartialEq)]
213pub enum PageLayout {
214 SinglePage,
216 OneColumn,
218 TwoColumnLeft,
220 TwoColumnRight,
222 TwoPageLeft,
224 TwoPageRight,
226}
227
228#[derive(Debug, Clone, Copy, PartialEq)]
231pub enum PageMode {
232 UseNone,
234 UseOutlines,
236 UseThumbs,
238 FullScreen,
240}
241
242#[derive(Debug, Clone, Default, PartialEq)]
245pub struct Viewer {
246 pub layout: Option<PageLayout>,
248 pub mode: Option<PageMode>,
250 pub open_to: Option<usize>,
253}
254
255#[derive(Debug, Default)]
258pub struct Pdf {
259 pub metadata: Option<Metadata>,
261 pub pages: Vec<Page>,
263 pub outline: Option<Outline>,
265 pub attachments: Vec<Attachment>,
269 pub page_labels: Vec<PageLabel>,
274 pub viewer: Option<Viewer>,
276 pub options: WriteOptions,
278}
279
280impl Pdf {
281 pub fn to_bytes(self) -> Result<Vec<u8>> {
290 let (w, root) = self.assemble()?;
291 w.finish(root)
292 }
293
294 pub fn write_into(self, out: impl std::io::Write) -> Result<()> {
299 let (w, root) = self.assemble()?;
300 w.finish_into(root, out)
301 }
302
303 pub async fn write_into_with<S: AsyncByteSink>(self, sink: S) -> Result<S> {
307 let (w, root) = self.assemble()?;
308 w.finish_into_with(root, sink).await
309 }
310
311 fn assemble(self) -> Result<(Writer, ObjRef)> {
316 let Pdf {
317 metadata,
318 pages,
319 outline,
320 attachments,
321 page_labels,
322 viewer,
323 options,
324 } = self;
325 if pages.is_empty() {
326 return Err(Error::Other(
327 "a document needs at least one page".to_string(),
328 ));
329 }
330 let mut w = Writer::new(options);
331 let pages_root = w.reserve();
332 let page_count = pages.len();
333 let page_refs: Vec<ObjRef> = pages.iter().map(|_| w.reserve()).collect();
334 let mut font_cache: Vec<(Standard14, ObjRef)> = Vec::new();
335 for (index, page) in pages.into_iter().enumerate() {
336 let Page {
337 size,
338 rotation,
339 mut canvas,
340 content,
341 mut links,
342 } = page;
343 if rotation % 90 != 0 {
344 return Err(Error::Other(format!(
345 "page rotation {rotation} is not a multiple of 90"
346 )));
347 }
348 element::lower(content, &mut canvas, &mut links)?;
349 let (width, height) = size.dimensions();
350 let parts = canvas.into_parts();
351 let (content, resources) = lower_canvas(&mut w, parts, &mut font_cache)?;
352 let content_ref = w.put_stream(Dict::new(), content);
353 let mut dict = Dict::new();
354 dict.insert(name("Type"), Object::Name(name("Page")));
355 dict.insert(name("Parent"), Object::Ref(pages_root));
356 dict.insert(
357 name("MediaBox"),
358 Object::Array(vec![
359 Object::Int(0),
360 Object::Int(0),
361 Object::Real(f64::from(width)),
362 Object::Real(f64::from(height)),
363 ]),
364 );
365 dict.insert(name("Contents"), Object::Ref(content_ref));
366 dict.insert(name("Resources"), Object::Dict(resources));
367 if !links.is_empty() {
368 let mut annots = Vec::with_capacity(links.len());
369 for link in links {
370 let action = match link.target {
371 LinkTarget::Uri(uri) => {
372 let mut action = Dict::new();
373 action.insert(name("S"), Object::Name(name("URI")));
374 action.insert(name("URI"), text_string(&uri));
375 action
376 }
377 LinkTarget::Page(target_index) => {
378 let target = page_refs.get(target_index).copied().ok_or_else(|| {
379 Error::Other(format!(
380 "link target page {target_index} is out of range: the document has {page_count} pages"
381 ))
382 })?;
383 let mut action = Dict::new();
384 action.insert(name("S"), Object::Name(name("GoTo")));
385 action.insert(
386 name("D"),
387 Object::Array(vec![
388 Object::Ref(target),
389 Object::Name(name("XYZ")),
390 Object::Null,
391 Object::Null,
392 Object::Null,
393 ]),
394 );
395 action
396 }
397 };
398 let mut annot = Dict::new();
399 annot.insert(name("Type"), Object::Name(name("Annot")));
400 annot.insert(name("Subtype"), Object::Name(name("Link")));
401 annot.insert(
402 name("Rect"),
403 Object::Array(
404 link.rect
405 .iter()
406 .map(|v| Object::Real(f64::from(*v)))
407 .collect(),
408 ),
409 );
410 annot.insert(
411 name("Border"),
412 Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(0)]),
413 );
414 annot.insert(name("A"), Object::Dict(action));
415 annots.push(Object::Ref(w.put(Object::Dict(annot))));
416 }
417 dict.insert(name("Annots"), Object::Array(annots));
418 }
419 if rotation != 0 {
420 dict.insert(name("Rotate"), Object::Int(i64::from(rotation)));
421 }
422 w.fill(page_refs[index], Object::Dict(dict))?;
423 }
424 let kids: Vec<Object> = page_refs.iter().copied().map(Object::Ref).collect();
425 let mut tree = Dict::new();
426 tree.insert(name("Type"), Object::Name(name("Pages")));
427 tree.insert(name("Count"), Object::Int(kids.len() as i64));
428 tree.insert(name("Kids"), Object::Array(kids));
429 w.fill(pages_root, Object::Dict(tree))?;
430 let xmp_ref = match metadata {
431 Some(meta) => {
432 let packet = crate::xmp::packet(&meta);
433 if let Some(info) = info_dict(meta) {
434 let info_ref = w.put(Object::Dict(info));
435 w.set_info(info_ref);
436 }
437 let mut xmp_dict = Dict::new();
438 xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
439 xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
440 Some(w.put_stream_raw(xmp_dict, packet))
441 }
442 None => None,
443 };
444 let outline_ref = match outline {
445 Some(outline) if !outline.bookmarks.is_empty() => {
446 let root_ref = w.reserve();
447 let refs = reserve_bookmarks(&mut w, &outline.bookmarks);
448 let (first, last, count) = fill_bookmarks(
449 &mut w,
450 outline.bookmarks,
451 &refs,
452 root_ref,
453 &page_refs,
454 page_count,
455 )?;
456 let mut dict = Dict::new();
457 dict.insert(name("Type"), Object::Name(name("Outlines")));
458 dict.insert(name("First"), Object::Ref(first));
459 dict.insert(name("Last"), Object::Ref(last));
460 dict.insert(name("Count"), Object::Int(count));
461 w.fill(root_ref, Object::Dict(dict))?;
462 Some(root_ref)
463 }
464 _ => None,
465 };
466 let names = embedded_files_dict(&mut w, attachments)?;
467 let page_labels_entry = page_labels_dict(page_labels)?;
468 let mut catalog = Dict::new();
469 catalog.insert(name("Type"), Object::Name(name("Catalog")));
470 catalog.insert(name("Pages"), Object::Ref(pages_root));
471 if let Some(outline_ref) = outline_ref {
472 catalog.insert(name("Outlines"), Object::Ref(outline_ref));
473 }
474 if let Some(xmp_ref) = xmp_ref {
475 catalog.insert(name("Metadata"), Object::Ref(xmp_ref));
476 }
477 if let Some(names) = names {
478 catalog.insert(name("Names"), Object::Dict(names));
479 }
480 if let Some(page_labels_entry) = page_labels_entry {
481 catalog.insert(name("PageLabels"), Object::Dict(page_labels_entry));
482 }
483 if let Some(viewer) = viewer {
484 let Viewer {
485 layout,
486 mode,
487 open_to,
488 } = viewer;
489 if let Some(layout) = layout {
490 catalog.insert(
491 name("PageLayout"),
492 Object::Name(name(page_layout_name(layout))),
493 );
494 }
495 if let Some(mode) = mode {
496 catalog.insert(name("PageMode"), Object::Name(name(page_mode_name(mode))));
497 }
498 if let Some(open_to) = open_to {
499 let target = page_refs.get(open_to).copied().ok_or_else(|| {
500 Error::Other(format!(
501 "open_to target page {open_to} is out of range: the document has {page_count} pages"
502 ))
503 })?;
504 catalog.insert(
505 name("OpenAction"),
506 Object::Array(vec![
507 Object::Ref(target),
508 Object::Name(name("XYZ")),
509 Object::Null,
510 Object::Null,
511 Object::Null,
512 ]),
513 );
514 }
515 }
516 let root = w.put(Object::Dict(catalog));
517 Ok((w, root))
518 }
519
520 pub fn save(self, path: impl AsRef<Path>) -> Result<()> {
522 let path = path.as_ref();
523 let bytes = self.to_bytes()?;
524 std::fs::write(path, bytes)?;
525 Ok(())
526 }
527}
528
529fn name(text: &str) -> Name {
531 Name(text.to_string())
532}
533
534fn info_dict(meta: Metadata) -> Option<Dict> {
538 let mut dict = Dict::new();
539 let texts = [
540 ("Title", meta.title),
541 ("Author", meta.author),
542 ("Subject", meta.subject),
543 ("Keywords", meta.keywords),
544 ("Creator", meta.creator),
545 ("Producer", meta.producer),
546 ];
547 for (key, value) in texts {
548 if let Some(value) = value {
549 dict.insert(name(key), text_string(&value));
550 }
551 }
552 let dates = [
553 ("CreationDate", meta.creation_date),
554 ("ModDate", meta.modification_date),
555 ];
556 for (key, value) in dates {
557 if let Some(date) = value {
558 dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
559 }
560 }
561 if dict.is_empty() {
562 return None;
563 }
564 Some(dict)
565}
566
567const DEFAULT_ATTACHMENT_MIME: &str = "application/octet-stream";
569
570fn embedded_files_dict(w: &mut Writer, mut attachments: Vec<Attachment>) -> Result<Option<Dict>> {
576 if attachments.is_empty() {
577 return Ok(None);
578 }
579 attachments.sort_by(|a, b| a.name.cmp(&b.name));
580 for pair in attachments.windows(2) {
581 if pair[0].name == pair[1].name {
582 return Err(Error::Other(format!(
583 "duplicate attachment name: {:?}",
584 pair[0].name
585 )));
586 }
587 }
588 let mut entries = Vec::with_capacity(attachments.len() * 2);
589 for attachment in attachments {
590 let Attachment {
591 name: file_name,
592 data,
593 mime,
594 modified,
595 description,
596 } = attachment;
597 let mime = mime.unwrap_or_else(|| DEFAULT_ATTACHMENT_MIME.to_string());
598
599 let mut params = Dict::new();
600 params.insert(name("Size"), Object::Int(data.len() as i64));
601 if let Some(modified) = modified {
602 params.insert(
603 name("ModDate"),
604 Object::String(modified.to_pdf_string().into_bytes()),
605 );
606 }
607 let mut stream_dict = Dict::new();
608 stream_dict.insert(name("Type"), Object::Name(name("EmbeddedFile")));
609 stream_dict.insert(name("Subtype"), Object::Name(Name(mime)));
610 stream_dict.insert(name("Params"), Object::Dict(params));
611 let stream_ref = w.put_stream(stream_dict, data);
612
613 let mut ef = Dict::new();
614 ef.insert(name("F"), Object::Ref(stream_ref));
615
616 let mut filespec = Dict::new();
617 filespec.insert(name("Type"), Object::Name(name("Filespec")));
618 filespec.insert(name("F"), text_string(&file_name));
619 filespec.insert(name("UF"), text_string(&file_name));
620 if let Some(description) = description {
621 filespec.insert(name("Desc"), text_string(&description));
622 }
623 filespec.insert(name("EF"), Object::Dict(ef));
624 let filespec_ref = w.put(Object::Dict(filespec));
625
626 entries.push(text_string(&file_name));
627 entries.push(Object::Ref(filespec_ref));
628 }
629 let mut name_tree = Dict::new();
630 name_tree.insert(name("Names"), Object::Array(entries));
631 let mut embedded_files = Dict::new();
632 embedded_files.insert(name("EmbeddedFiles"), Object::Dict(name_tree));
633 Ok(Some(embedded_files))
634}
635
636fn page_labels_dict(mut labels: Vec<PageLabel>) -> Result<Option<Dict>> {
643 if labels.is_empty() {
644 return Ok(None);
645 }
646 for label in &labels {
647 if label.start_at == 0 {
648 return Err(Error::Other(format!(
649 "page label at page {} has start_at 0: numbering starts at 1",
650 label.first_page
651 )));
652 }
653 }
654 labels.sort_by_key(|label| label.first_page);
655 if labels[0].first_page != 0 {
656 return Err(Error::Other("page labels must start at page 0".to_string()));
657 }
658 for pair in labels.windows(2) {
659 if pair[0].first_page == pair[1].first_page {
660 return Err(Error::Other(format!(
661 "duplicate page label at page {}",
662 pair[0].first_page
663 )));
664 }
665 }
666 let mut nums = Vec::with_capacity(labels.len() * 2);
667 for label in labels {
668 let PageLabel {
669 first_page,
670 style,
671 prefix,
672 start_at,
673 } = label;
674 let mut range = Dict::new();
675 if let Some(style) = style {
676 range.insert(name("S"), Object::Name(name(style.code())));
677 }
678 if let Some(prefix) = prefix {
679 range.insert(name("P"), text_string(&prefix));
680 }
681 if start_at != 1 {
682 range.insert(name("St"), Object::Int(i64::from(start_at)));
683 }
684 nums.push(Object::Int(first_page as i64));
685 nums.push(Object::Dict(range));
686 }
687 let mut dict = Dict::new();
688 dict.insert(name("Nums"), Object::Array(nums));
689 Ok(Some(dict))
690}
691
692fn page_layout_name(layout: PageLayout) -> &'static str {
694 match layout {
695 PageLayout::SinglePage => "SinglePage",
696 PageLayout::OneColumn => "OneColumn",
697 PageLayout::TwoColumnLeft => "TwoColumnLeft",
698 PageLayout::TwoColumnRight => "TwoColumnRight",
699 PageLayout::TwoPageLeft => "TwoPageLeft",
700 PageLayout::TwoPageRight => "TwoPageRight",
701 }
702}
703
704fn page_mode_name(mode: PageMode) -> &'static str {
706 match mode {
707 PageMode::UseNone => "UseNone",
708 PageMode::UseOutlines => "UseOutlines",
709 PageMode::UseThumbs => "UseThumbs",
710 PageMode::FullScreen => "FullScreen",
711 }
712}
713
714struct BookmarkRef {
718 r: ObjRef,
719 children: Vec<BookmarkRef>,
720}
721
722fn reserve_bookmarks(w: &mut Writer, bookmarks: &[Bookmark]) -> Vec<BookmarkRef> {
727 bookmarks
728 .iter()
729 .map(|bookmark| BookmarkRef {
730 r: w.reserve(),
731 children: reserve_bookmarks(w, &bookmark.children),
732 })
733 .collect()
734}
735
736fn fill_bookmarks(
743 w: &mut Writer,
744 bookmarks: Vec<Bookmark>,
745 refs: &[BookmarkRef],
746 parent: ObjRef,
747 page_refs: &[ObjRef],
748 page_count: usize,
749) -> Result<(ObjRef, ObjRef, i64)> {
750 let last_index = bookmarks.len() - 1;
751 let mut total = 0i64;
752 for (index, bookmark) in bookmarks.into_iter().enumerate() {
753 let Bookmark {
754 title,
755 page,
756 children,
757 } = bookmark;
758 let dest = page_refs.get(page).copied().ok_or_else(|| {
759 Error::Other(format!(
760 "bookmark target page {page} is out of range: the document has {page_count} pages"
761 ))
762 })?;
763 let mut dict = Dict::new();
764 dict.insert(name("Title"), text_string(&title));
765 dict.insert(name("Parent"), Object::Ref(parent));
766 if index > 0 {
767 dict.insert(name("Prev"), Object::Ref(refs[index - 1].r));
768 }
769 if index < last_index {
770 dict.insert(name("Next"), Object::Ref(refs[index + 1].r));
771 }
772 dict.insert(
773 name("Dest"),
774 Object::Array(vec![
775 Object::Ref(dest),
776 Object::Name(name("XYZ")),
777 Object::Null,
778 Object::Null,
779 Object::Null,
780 ]),
781 );
782 let mut subtree_count = 0i64;
783 if !children.is_empty() {
784 let (first, last, count) = fill_bookmarks(
785 w,
786 children,
787 &refs[index].children,
788 refs[index].r,
789 page_refs,
790 page_count,
791 )?;
792 dict.insert(name("First"), Object::Ref(first));
793 dict.insert(name("Last"), Object::Ref(last));
794 dict.insert(name("Count"), Object::Int(count));
795 subtree_count = count;
796 }
797 w.fill(refs[index].r, Object::Dict(dict))?;
798 total += 1 + subtree_count;
799 }
800 Ok((refs[0].r, refs[last_index].r, total))
801}
802
803fn cached_font(
809 w: &mut Writer,
810 font_cache: &mut Vec<(Standard14, ObjRef)>,
811 face: &Standard14,
812) -> ObjRef {
813 if let Some((_, r)) = font_cache.iter().find(|(seen, _)| seen == face) {
814 return *r;
815 }
816 let r = w.put(Object::Dict(face.font_dict()));
817 font_cache.push((*face, r));
818 r
819}
820
821fn lower_canvas(
827 w: &mut Writer,
828 parts: CanvasParts,
829 font_cache: &mut Vec<(Standard14, ObjRef)>,
830) -> Result<(Vec<u8>, Dict)> {
831 let content = serialize_ops(&parts.ops);
832 let mut fonts = Dict::new();
833 for (index, face) in parts.fonts.iter().enumerate() {
834 let font_ref = cached_font(w, font_cache, face);
835 fonts.insert(Name(format!("F{}", index + 1)), Object::Ref(font_ref));
836 }
837 let mut xobjects = Dict::new();
838 for (index, image) in parts.images.iter().enumerate() {
839 let image_ref = image.build_xobject(w);
840 xobjects.insert(Name(format!("Im{}", index + 1)), Object::Ref(image_ref));
841 }
842 for (index, (group_parts, group_bbox)) in parts.groups.into_iter().enumerate() {
843 let group_ref = build_form(w, group_parts, group_bbox, font_cache)?;
844 xobjects.insert(Name(format!("Gp{}", index + 1)), Object::Ref(group_ref));
845 }
846 let mut ext_gstates = Dict::new();
847 for (index, state) in parts.gstates.iter().enumerate() {
848 let gstate_ref = w.put(Object::Dict(state.ext_gstate_dict()));
849 ext_gstates.insert(Name(format!("Gs{}", index + 1)), Object::Ref(gstate_ref));
850 }
851 let mut resources = Dict::new();
852 if !fonts.is_empty() {
853 resources.insert(name("Font"), Object::Dict(fonts));
854 }
855 if !xobjects.is_empty() {
856 resources.insert(name("XObject"), Object::Dict(xobjects));
857 }
858 if !ext_gstates.is_empty() {
859 resources.insert(name("ExtGState"), Object::Dict(ext_gstates));
860 }
861 Ok((content, resources))
862}
863
864fn build_form(
870 w: &mut Writer,
871 parts: CanvasParts,
872 bbox: [f32; 4],
873 font_cache: &mut Vec<(Standard14, ObjRef)>,
874) -> Result<ObjRef> {
875 let (content, resources) = lower_canvas(w, parts, font_cache)?;
876 let mut dict = Dict::new();
877 dict.insert(name("Type"), Object::Name(name("XObject")));
878 dict.insert(name("Subtype"), Object::Name(name("Form")));
879 dict.insert(
880 name("BBox"),
881 Object::Array(bbox.iter().map(|v| Object::Real(f64::from(*v))).collect()),
882 );
883 dict.insert(name("Resources"), Object::Dict(resources));
884 Ok(w.put_stream(dict, content))
885}
886
887pub(crate) fn text_string(value: &str) -> Object {
891 if value.is_ascii() {
892 return Object::String(value.as_bytes().to_vec());
893 }
894 let mut bytes = vec![0xFE, 0xFF];
895 for unit in value.encode_utf16() {
896 bytes.extend_from_slice(&unit.to_be_bytes());
897 }
898 Object::String(bytes)
899}
900
901#[cfg(test)]
902mod tests {
903 use super::*;
904
905 #[test]
906 fn dimensions_match_the_contract() {
907 assert_eq!(PageSize::A3.dimensions(), (841.89, 1190.55));
908 assert_eq!(PageSize::A4.dimensions(), (595.28, 841.89));
909 assert_eq!(PageSize::A5.dimensions(), (419.53, 595.28));
910 assert_eq!(PageSize::Letter.dimensions(), (612.0, 792.0));
911 assert_eq!(PageSize::Legal.dimensions(), (612.0, 1008.0));
912 assert_eq!(
913 PageSize::Custom {
914 width: 10.0,
915 height: 20.0
916 }
917 .dimensions(),
918 (10.0, 20.0)
919 );
920 }
921
922 #[test]
923 fn by_name_parses_the_five_named_sizes_case_insensitively() {
924 for (name, expected) in [
925 ("a3", PageSize::A3),
926 ("A4", PageSize::A4),
927 ("a5", PageSize::A5),
928 ("Letter", PageSize::Letter),
929 ("LEGAL", PageSize::Legal),
930 ] {
931 assert_eq!(PageSize::by_name(name), Some(expected), "{name}");
932 }
933 }
934
935 #[test]
936 fn by_name_rejects_anything_else() {
937 assert_eq!(PageSize::by_name("tabloid"), None);
938 assert_eq!(PageSize::by_name(""), None);
939 }
940
941 #[test]
942 fn landscape_swaps_into_custom() {
943 assert_eq!(
944 PageSize::A4.landscape(),
945 PageSize::Custom {
946 width: 841.89,
947 height: 595.28
948 }
949 );
950 assert_eq!(
951 PageSize::Custom {
952 width: 1.0,
953 height: 2.0
954 }
955 .landscape(),
956 PageSize::Custom {
957 width: 2.0,
958 height: 1.0
959 }
960 );
961 assert_eq!(PageSize::Letter.landscape().dimensions(), (792.0, 612.0));
962 }
963
964 fn two_page_doc() -> Pdf {
967 let mut first = Page::new(PageSize::A4);
968 first
969 .canvas
970 .text("Streamed parity", 72.0, 720.0, Standard14::Helvetica, 14.0)
971 .expect("ASCII encodes");
972 let image = crate::image::ImageData::gray8(2, 2, vec![0, 85, 170, 255])
973 .expect("2x2 grayscale builds");
974 let handle = first.canvas.add_image(image);
975 first.canvas.draw_image(handle, 72.0, 400.0, 144.0, 144.0);
976 let mut second = Page::new(PageSize::Letter);
977 second
978 .canvas
979 .text("Page two", 72.0, 700.0, Standard14::TimesRoman, 12.0)
980 .expect("ASCII encodes");
981 Pdf {
982 pages: vec![first, second],
983 ..Pdf::default()
984 }
985 }
986
987 #[test]
991 fn write_into_and_write_into_with_match_to_bytes() {
992 let bytes = two_page_doc().to_bytes().expect("to_bytes succeeds");
993 let mut via_io = Vec::new();
994 two_page_doc()
995 .write_into(&mut via_io)
996 .expect("write_into succeeds");
997 assert_eq!(via_io, bytes);
998 let via_sink = pdfboss_core::block_on(two_page_doc().write_into_with(Vec::new()))
999 .expect("write_into_with succeeds");
1000 assert_eq!(via_sink, bytes);
1001 }
1002
1003 #[test]
1004 fn zero_page_document_is_an_error() {
1005 let err = Pdf::default()
1006 .to_bytes()
1007 .expect_err("a page-less document must not serialize");
1008 assert!(err.to_string().contains("at least one page"), "{err}");
1009 }
1010}