1use pdfboss_core::content::Op;
8use pdfboss_core::Point;
9
10use crate::canvas::Canvas;
11use crate::color::Color;
12use crate::error::{Error, Result};
13use crate::font::Standard14;
14use crate::image::ImageData;
15use crate::pdf::{LinkAnnotation, LinkTarget};
16
17pub trait Draw: Send {
21 fn draw(&self, canvas: &mut Canvas) -> Result<()>;
23}
24
25#[derive(Debug, Clone, PartialEq)]
27pub struct Text {
28 pub value: String,
30 pub at: Point,
32 pub font: Standard14,
34 pub size: f32,
36 pub color: Color,
38}
39
40impl Default for Text {
41 fn default() -> Text {
42 Text {
43 value: String::new(),
44 at: Point::default(),
45 font: Standard14::Helvetica,
46 size: 12.0,
47 color: Color::BLACK,
48 }
49 }
50}
51
52impl Draw for Text {
53 fn draw(&self, canvas: &mut Canvas) -> Result<()> {
54 canvas.set_fill(self.color);
55 canvas.text(&self.value, self.at.x, self.at.y, self.font, self.size)
56 }
57}
58
59#[derive(Debug, Clone, PartialEq)]
63pub struct Image {
64 pub data: ImageData,
66 pub at: Point,
69 pub width: Option<f32>,
73 pub height: Option<f32>,
77}
78
79impl Image {
80 pub fn placed_size(&self) -> (f32, f32) {
84 let natural_width = self.data.width() as f32;
85 let natural_height = self.data.height() as f32;
86 match (self.width, self.height) {
87 (Some(width), Some(height)) => (width, height),
88 (Some(width), None) => (width, width * natural_height / natural_width),
89 (None, Some(height)) => (height * natural_width / natural_height, height),
90 (None, None) => (natural_width, natural_height),
91 }
92 }
93}
94
95impl Draw for Image {
96 fn draw(&self, canvas: &mut Canvas) -> Result<()> {
97 let (width, height) = self.placed_size();
98 let handle = canvas.add_image(self.data.clone());
99 canvas.draw_image(handle, self.at.x, self.at.y, width, height);
100 Ok(())
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
106pub struct Link {
107 pub rect: [f32; 4],
109 pub target: LinkTarget,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Default)]
115pub enum ParagraphAlign {
116 #[default]
118 Left,
119 Center,
121 Right,
123 Justify,
126}
127
128#[derive(Debug, Clone, PartialEq)]
131pub struct Paragraph {
132 pub text: String,
135 pub rect: [f32; 4],
137 pub font: Standard14,
139 pub size: f32,
141 pub leading: Option<f32>,
143 pub align: ParagraphAlign,
145 pub color: Color,
147}
148
149impl Default for Paragraph {
150 fn default() -> Paragraph {
151 Paragraph {
152 text: String::new(),
153 rect: [0.0, 0.0, 0.0, 0.0],
154 font: Standard14::Helvetica,
155 size: 11.0,
156 leading: None,
157 align: ParagraphAlign::Left,
158 color: Color::BLACK,
159 }
160 }
161}
162
163fn wrap_lines(text: &str, font: Standard14, size: f32, max_width: f32) -> Result<Vec<Vec<&str>>> {
169 let mut lines = Vec::new();
170 for source_line in text.split('\n') {
171 let words: Vec<&str> = source_line.split_whitespace().collect();
172 if words.is_empty() {
173 lines.push(Vec::new());
174 continue;
175 }
176 let mut current: Vec<&str> = Vec::new();
177 let mut current_text = String::new();
178 for word in words {
179 let candidate = if current.is_empty() {
180 word.to_string()
181 } else {
182 format!("{current_text} {word}")
183 };
184 let width = font.text_width(&candidate, size)?;
185 if current.is_empty() || width <= max_width {
186 current.push(word);
187 current_text = candidate;
188 continue;
189 }
190 lines.push(std::mem::take(&mut current));
191 current_text = word.to_string();
192 current.push(word);
193 }
194 lines.push(current);
195 }
196 Ok(lines)
197}
198
199fn lines_that_fit(y0: f32, y1: f32, size: f32, leading: f32) -> usize {
203 const EPSILON: f32 = 1e-3;
204 let first_baseline = y1 - size;
205 if first_baseline < y0 - EPSILON {
206 return 0;
207 }
208 (((first_baseline - y0) / leading) + EPSILON).floor() as usize + 1
209}
210
211impl Draw for Paragraph {
216 fn draw(&self, canvas: &mut Canvas) -> Result<()> {
217 canvas.set_fill(self.color);
218 let [x0, y0, x1, y1] = self.rect;
219 let width = x1 - x0;
220 let leading = self.leading.unwrap_or(1.2 * self.size);
221 let lines = wrap_lines(&self.text, self.font, self.size, width)?;
222 let fits = lines_that_fit(y0, y1, self.size, leading);
223 if lines.len() > fits {
224 return Err(Error::Other(format!(
225 "paragraph overflows its rect: {fits} lines fit, {} needed",
226 lines.len()
227 )));
228 }
229 let last_visible = lines.iter().rposition(|words| !words.is_empty());
230 let mut stretch_active = false;
231 for (index, words) in lines.iter().enumerate() {
232 if words.is_empty() {
233 continue;
234 }
235 let baseline = y1 - self.size - index as f32 * leading;
236 let line_text = words.join(" ");
237 let line_width = self.font.text_width(&line_text, self.size)?;
238 let is_final = Some(index) == last_visible;
239 let stretch = match self.align {
240 ParagraphAlign::Justify if !is_final && words.len() >= 2 => {
241 Some((width - line_width) / (words.len() as f32 - 1.0))
242 }
243 _ => None,
244 };
245 let x = match self.align {
246 ParagraphAlign::Right => x1 - line_width,
247 ParagraphAlign::Center => x0 + (width - line_width) / 2.0,
248 ParagraphAlign::Left | ParagraphAlign::Justify => x0,
249 };
250 if stretch.is_none() && stretch_active {
251 canvas.op(Op::SetWordSpacing(0.0));
252 stretch_active = false;
253 }
254 if let Some(spacing) = stretch {
255 canvas.op(Op::SetWordSpacing(spacing));
256 stretch_active = true;
257 }
258 canvas.text(&line_text, x, baseline, self.font, self.size)?;
259 }
260 if stretch_active {
261 canvas.op(Op::SetWordSpacing(0.0));
262 }
263 Ok(())
264 }
265}
266
267pub enum Content {
269 Text(Text),
271 Image(Image),
273 Link(Link),
275 Paragraph(Paragraph),
277 Custom(Box<dyn Draw>),
279}
280
281impl std::fmt::Debug for Content {
282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283 match self {
284 Content::Text(text) => f.debug_tuple("Text").field(text).finish(),
285 Content::Image(image) => f.debug_tuple("Image").field(image).finish(),
286 Content::Link(link) => f.debug_tuple("Link").field(link).finish(),
287 Content::Paragraph(paragraph) => f.debug_tuple("Paragraph").field(paragraph).finish(),
288 Content::Custom(..) => f.write_str("Custom(..)"),
289 }
290 }
291}
292
293impl From<Text> for Content {
294 fn from(value: Text) -> Content {
295 Content::Text(value)
296 }
297}
298
299impl From<Image> for Content {
300 fn from(value: Image) -> Content {
301 Content::Image(value)
302 }
303}
304
305impl From<Link> for Content {
306 fn from(value: Link) -> Content {
307 Content::Link(value)
308 }
309}
310
311impl From<Paragraph> for Content {
312 fn from(value: Paragraph) -> Content {
313 Content::Paragraph(value)
314 }
315}
316
317impl Content {
318 pub fn custom(value: impl Draw + 'static) -> Content {
320 Content::Custom(Box::new(value))
321 }
322}
323
324pub(crate) fn lower(
327 content: Vec<Content>,
328 canvas: &mut Canvas,
329 links: &mut Vec<LinkAnnotation>,
330) -> Result<()> {
331 for item in content {
332 match item {
333 Content::Text(text) => text.draw(canvas)?,
334 Content::Image(image) => image.draw(canvas)?,
335 Content::Link(link) => links.push(LinkAnnotation {
336 rect: link.rect,
337 target: link.target,
338 }),
339 Content::Paragraph(paragraph) => paragraph.draw(canvas)?,
340 Content::Custom(drawable) => drawable.draw(canvas)?,
341 }
342 }
343 Ok(())
344}
345
346#[cfg(test)]
347mod tests {
348 use pdfboss_core::content::{parse_content, Op};
349 use pdfboss_core::{Document, Name};
350 use pdfboss_output::extract_text;
351
352 use super::*;
353 use crate::pdf::{Page, PageSize};
354 use crate::Pdf;
355
356 #[test]
357 fn elements_lower_in_sequence_order_after_canvas_ops() {
358 let mut page = Page::new(PageSize::A4);
359 page.canvas
360 .text("under", 72.0, 100.0, Standard14::Helvetica, 10.0)
361 .unwrap();
362 page.content.push(Content::from(Text {
363 value: "over".into(),
364 at: Point::new(72.0, 700.0),
365 size: 24.0,
366 ..Text::default()
367 }));
368 let ops_before = page.canvas.ops().len();
369 let bytes = Pdf {
370 pages: vec![page],
371 ..Pdf::default()
372 }
373 .to_bytes()
374 .unwrap();
375 let doc = Document::load(bytes).unwrap();
376 let loaded = doc.page(0).unwrap();
377 let text = extract_text(&doc, &loaded, pdfboss_output::ReadingOrder::Content).unwrap();
378 assert!(text.contains("under") && text.contains("over"));
379 assert!(ops_before > 0);
380
381 let stream = loaded.content(&doc).unwrap();
382 let ops = parse_content(&stream).unwrap();
383 let index_of = |needle: &[u8]| {
384 ops.iter()
385 .position(|op| matches!(op, Op::ShowText(s) if s == needle))
386 .unwrap_or_else(|| {
387 panic!(
388 "no ShowText carrying {:?} in {:?}",
389 String::from_utf8_lossy(needle),
390 ops
391 )
392 })
393 };
394 let under_index = index_of(b"under");
395 let over_index = index_of(b"over");
396 assert!(
397 under_index < over_index,
398 "expected \"under\" ({under_index}) before \"over\" ({over_index})"
399 );
400 }
401
402 #[test]
403 fn custom_draw_paints_through_the_canvas() {
404 struct Letterhead;
405 impl Draw for Letterhead {
406 fn draw(&self, canvas: &mut Canvas) -> Result<()> {
407 canvas.set_line_width(0.5);
408 canvas.move_to(72.0, 806.0);
409 canvas.line_to(523.0, 806.0);
410 canvas.stroke();
411 canvas.text("ACME GmbH", 72.0, 812.0, Standard14::Helvetica, 8.0)
412 }
413 }
414 let custom = Content::custom(Letterhead);
415 assert_eq!(format!("{custom:?}"), "Custom(..)");
416 let mut page = Page::new(PageSize::A4);
417 page.content.push(custom);
418 let bytes = Pdf {
419 pages: vec![page],
420 ..Pdf::default()
421 }
422 .to_bytes()
423 .unwrap();
424 let doc = Document::load(bytes).unwrap();
425 let loaded = doc.page(0).unwrap();
426 let text = extract_text(&doc, &loaded, pdfboss_output::ReadingOrder::Content).unwrap();
427 assert!(text.contains("ACME GmbH"));
428 }
429
430 #[test]
431 fn image_placed_size_is_natural_at_72dpi_when_both_none() {
432 let image = Image {
433 data: ImageData::gray8(16, 8, vec![0u8; 128]).unwrap(),
434 at: Point::new(10.0, 10.0),
435 width: None,
436 height: None,
437 };
438 assert_eq!(image.placed_size(), (16.0, 8.0));
439 }
440
441 #[test]
442 fn image_element_scales_by_aspect_when_one_dimension_is_given() {
443 let image = Image {
444 data: ImageData::gray8(16, 8, vec![0u8; 128]).unwrap(),
445 at: Point::new(10.0, 10.0),
446 width: Some(32.0),
447 height: None,
448 };
449 assert_eq!(image.placed_size(), (32.0, 16.0));
450 }
451
452 #[test]
453 fn image_placed_size_scales_by_aspect_when_only_height_is_given() {
454 let image = Image {
455 data: ImageData::gray8(16, 8, vec![0u8; 128]).unwrap(),
456 at: Point::new(10.0, 10.0),
457 width: None,
458 height: Some(4.0),
459 };
460 assert_eq!(image.placed_size(), (8.0, 4.0));
461 }
462
463 #[test]
464 fn image_placed_size_is_exact_when_both_dimensions_are_given() {
465 let image = Image {
466 data: ImageData::gray8(16, 8, vec![0u8; 128]).unwrap(),
467 at: Point::new(10.0, 10.0),
468 width: Some(50.0),
469 height: Some(90.0),
470 };
471 assert_eq!(image.placed_size(), (50.0, 90.0));
472 }
473
474 #[test]
476 fn text_draw_sets_fill_then_shows_text() {
477 let mut canvas = Canvas::new();
478 let text = Text {
479 value: "hi".into(),
480 at: Point::new(1.0, 2.0),
481 font: Standard14::Helvetica,
482 size: 10.0,
483 color: Color::Rgb(1.0, 0.0, 0.0),
484 };
485 text.draw(&mut canvas).unwrap();
486 assert_eq!(
487 canvas.ops(),
488 [
489 Op::SetFillRGB(1.0, 0.0, 0.0),
490 Op::BeginText,
491 Op::SetFont(Name("F1".into()), 10.0),
492 Op::TextMove(1.0, 2.0),
493 Op::ShowText(b"hi".to_vec()),
494 Op::EndText,
495 ]
496 );
497 }
498
499 #[test]
500 fn paragraph_default_is_helvetica_11_left_and_none_leading() {
501 let paragraph = Paragraph::default();
502 assert_eq!(paragraph.text, "");
503 assert_eq!(paragraph.font, Standard14::Helvetica);
504 assert_eq!(paragraph.size, 11.0);
505 assert_eq!(paragraph.leading, None);
506 assert_eq!(paragraph.align, ParagraphAlign::Left);
507 }
508
509 #[test]
510 fn content_from_paragraph_debug_prints_paragraph() {
511 let content = Content::from(Paragraph::default());
512 assert_eq!(
513 format!("{content:?}"),
514 format!("Paragraph({:?})", Paragraph::default())
515 );
516 }
517
518 #[test]
519 fn paragraph_sets_its_own_fill() {
520 let mut canvas = Canvas::new();
521 let paragraph = Paragraph {
522 text: "hi".into(),
523 rect: [0.0, 0.0, 100.0, 100.0],
524 font: Standard14::Helvetica,
525 size: 10.0,
526 color: Color::Rgb(0.0, 0.5, 0.0),
527 ..Paragraph::default()
528 };
529 paragraph.draw(&mut canvas).unwrap();
530 assert!(matches!(canvas.ops()[0], Op::SetFillRGB(0.0, 0.5, 0.0)));
531 }
532
533 #[test]
534 fn paragraph_wraps_at_word_boundaries_courier_metrics() {
535 let mut canvas = Canvas::new();
536 let mut links = Vec::new();
537 let paragraph = Paragraph {
538 text: "aaaaaaaaa bbbbbbbbbb cccccccccc".into(),
539 rect: [0.0, 0.0, 120.0, 100.0],
540 font: Standard14::Courier,
541 size: 10.0,
542 ..Paragraph::default()
543 };
544 lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap();
545 assert_eq!(
546 canvas.ops(),
547 [
548 Op::SetFillGray(0.0),
549 Op::BeginText,
550 Op::SetFont(Name("F1".into()), 10.0),
551 Op::TextMove(0.0, 90.0),
552 Op::ShowText(b"aaaaaaaaa bbbbbbbbbb".to_vec()),
553 Op::EndText,
554 Op::BeginText,
555 Op::SetFont(Name("F1".into()), 10.0),
556 Op::TextMove(0.0, 78.0),
557 Op::ShowText(b"cccccccccc".to_vec()),
558 Op::EndText,
559 ]
560 );
561 }
562
563 #[test]
564 fn paragraph_overflow_reports_lines_fit_and_needed() {
565 let mut canvas = Canvas::new();
566 let mut links = Vec::new();
567 let paragraph = Paragraph {
568 text: "aaaaaaaaa bbbbbbbbbb cccccccccc".into(),
569 rect: [0.0, 80.0, 120.0, 95.0],
570 font: Standard14::Courier,
571 size: 10.0,
572 ..Paragraph::default()
573 };
574 let err = lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap_err();
575 match err {
576 Error::Other(msg) => {
577 assert_eq!(msg, "paragraph overflows its rect: 1 lines fit, 2 needed")
578 }
579 other => panic!("expected Error::Other, got {other:?}"),
580 }
581 }
582
583 #[test]
585 fn paragraph_justify_stretches_non_final_lines_and_resets_once() {
586 let mut canvas = Canvas::new();
587 let mut links = Vec::new();
588 let paragraph = Paragraph {
589 text: "aaaaaaa bbbbbbb ddddd".into(),
590 rect: [0.0, 0.0, 120.0, 100.0],
591 font: Standard14::Courier,
592 size: 10.0,
593 align: ParagraphAlign::Justify,
594 ..Paragraph::default()
595 };
596 lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap();
597 assert_eq!(
598 canvas.ops(),
599 [
600 Op::SetFillGray(0.0),
601 Op::SetWordSpacing(30.0),
602 Op::BeginText,
603 Op::SetFont(Name("F1".into()), 10.0),
604 Op::TextMove(0.0, 90.0),
605 Op::ShowText(b"aaaaaaa bbbbbbb".to_vec()),
606 Op::EndText,
607 Op::SetWordSpacing(0.0),
608 Op::BeginText,
609 Op::SetFont(Name("F1".into()), 10.0),
610 Op::TextMove(0.0, 78.0),
611 Op::ShowText(b"ddddd".to_vec()),
612 Op::EndText,
613 ],
614 "the reset must land before the final line's BeginText, not after it \
615 (Tw is persistent text state that BeginText does not clear)"
616 );
617
618 let bytes = crate::content::serialize_ops(canvas.ops());
619 let parsed = parse_content(&bytes).unwrap();
620 let stretched: Vec<f32> = parsed
621 .iter()
622 .filter_map(|op| match op {
623 Op::SetWordSpacing(value) if *value > 0.0 => Some(*value),
624 _ => None,
625 })
626 .collect();
627 assert_eq!(stretched, [30.0]);
628 assert!(parsed.contains(&Op::SetWordSpacing(0.0)));
629 }
630
631 #[test]
632 fn paragraph_justify_final_line_with_multiple_words_gets_no_leftover_spacing() {
633 let mut canvas = Canvas::new();
634 let mut links = Vec::new();
635 let paragraph = Paragraph {
636 text: "aaaaaaa bbbbbbb ccccc dd".into(),
637 rect: [0.0, 0.0, 120.0, 100.0],
638 font: Standard14::Courier,
639 size: 10.0,
640 align: ParagraphAlign::Justify,
641 ..Paragraph::default()
642 };
643 lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap();
644 let expected = [
645 Op::SetFillGray(0.0),
646 Op::SetWordSpacing(30.0),
647 Op::BeginText,
648 Op::SetFont(Name("F1".into()), 10.0),
649 Op::TextMove(0.0, 90.0),
650 Op::ShowText(b"aaaaaaa bbbbbbb".to_vec()),
651 Op::EndText,
652 Op::SetWordSpacing(0.0),
653 Op::BeginText,
654 Op::SetFont(Name("F1".into()), 10.0),
655 Op::TextMove(0.0, 78.0),
656 Op::ShowText(b"ccccc dd".to_vec()),
657 Op::EndText,
658 ];
659 assert_eq!(
660 canvas.ops(),
661 expected,
662 "the final line has 2 words (a space glyph) — a leftover non-zero \
663 Tw here would visibly over-stretch it, which is exactly the bug"
664 );
665
666 let bytes = crate::content::serialize_ops(canvas.ops());
667 let parsed = parse_content(&bytes).unwrap();
668 let reset_index = parsed
669 .iter()
670 .position(|op| *op == Op::SetWordSpacing(0.0))
671 .expect("a zero reset must be present");
672 let final_show_index = parsed
673 .iter()
674 .position(|op| matches!(op, Op::ShowText(s) if s == b"ccccc dd"))
675 .expect("final line's ShowText must be present");
676 assert!(
677 reset_index < final_show_index,
678 "reset (index {reset_index}) must precede the final line's ShowText \
679 (index {final_show_index}): {parsed:?}"
680 );
681 let stray_nonzero_between = parsed[reset_index..final_show_index]
682 .iter()
683 .any(|op| matches!(op, Op::SetWordSpacing(value) if *value != 0.0));
684 assert!(
685 !stray_nonzero_between,
686 "no non-zero word spacing may sit between the reset and the final \
687 line's ShowText: {:?}",
688 &parsed[reset_index..final_show_index]
689 );
690 }
691
692 #[test]
693 fn paragraph_trailing_blank_line_does_not_become_the_justify_final_line() {
694 let text = "aaaaaaa bbbbbbb ccccc dd\n";
695
696 let mut canvas = Canvas::new();
697 let mut links = Vec::new();
698 let paragraph = Paragraph {
699 text: text.into(),
700 rect: [0.0, 0.0, 120.0, 100.0],
701 font: Standard14::Courier,
702 size: 10.0,
703 align: ParagraphAlign::Justify,
704 ..Paragraph::default()
705 };
706 lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap();
707 assert_eq!(
708 canvas.ops(),
709 [
710 Op::SetFillGray(0.0),
711 Op::SetWordSpacing(30.0),
712 Op::BeginText,
713 Op::SetFont(Name("F1".into()), 10.0),
714 Op::TextMove(0.0, 90.0),
715 Op::ShowText(b"aaaaaaa bbbbbbb".to_vec()),
716 Op::EndText,
717 Op::SetWordSpacing(0.0),
718 Op::BeginText,
719 Op::SetFont(Name("F1".into()), 10.0),
720 Op::TextMove(0.0, 78.0),
721 Op::ShowText(b"ccccc dd".to_vec()),
722 Op::EndText,
723 ],
724 "the trailing blank line (from the trailing \\n) must not steal the \
725 'final line never stretches' exemption from \"ccccc dd\""
726 );
727
728 let tight_rect_without_trailing_newline = Paragraph {
729 text: "aaaaaaa bbbbbbb ccccc dd".into(),
730 rect: [0.0, 0.0, 120.0, 24.0],
731 font: Standard14::Courier,
732 size: 10.0,
733 align: ParagraphAlign::Justify,
734 ..Paragraph::default()
735 };
736 let mut fits_canvas = Canvas::new();
737 lower(
738 vec![tight_rect_without_trailing_newline.into()],
739 &mut fits_canvas,
740 &mut links,
741 )
742 .expect("two visible lines fit in a rect sized for exactly two lines");
743
744 let tight_rect_with_trailing_newline = Paragraph {
745 text: text.into(),
746 rect: [0.0, 0.0, 120.0, 24.0],
747 font: Standard14::Courier,
748 size: 10.0,
749 align: ParagraphAlign::Justify,
750 ..Paragraph::default()
751 };
752 let mut overflow_canvas = Canvas::new();
753 let err = lower(
754 vec![tight_rect_with_trailing_newline.into()],
755 &mut overflow_canvas,
756 &mut links,
757 )
758 .unwrap_err();
759 match err {
760 Error::Other(msg) => assert_eq!(
761 msg, "paragraph overflows its rect: 2 lines fit, 3 needed",
762 "the trailing blank line must still count toward vertical advance"
763 ),
764 other => panic!("expected Error::Other, got {other:?}"),
765 }
766 }
767
768 #[test]
769 fn paragraph_center_and_right_align_offset_by_rect_width() {
770 let mut links = Vec::new();
771 let base = Paragraph {
772 text: "aaaaaaaaa".into(),
773 rect: [0.0, 0.0, 120.0, 50.0],
774 font: Standard14::Courier,
775 size: 10.0,
776 ..Paragraph::default()
777 };
778
779 let mut center_canvas = Canvas::new();
780 lower(
781 vec![Paragraph {
782 align: ParagraphAlign::Center,
783 ..base.clone()
784 }
785 .into()],
786 &mut center_canvas,
787 &mut links,
788 )
789 .unwrap();
790 assert_eq!(center_canvas.ops()[3], Op::TextMove(33.0, 40.0));
791
792 let mut right_canvas = Canvas::new();
793 lower(
794 vec![Paragraph {
795 align: ParagraphAlign::Right,
796 ..base
797 }
798 .into()],
799 &mut right_canvas,
800 &mut links,
801 )
802 .unwrap();
803 assert_eq!(right_canvas.ops()[3], Op::TextMove(66.0, 40.0));
804 }
805
806 #[test]
807 fn paragraph_blank_line_keeps_advance_without_drawing() {
808 let mut canvas = Canvas::new();
809 let mut links = Vec::new();
810 let paragraph = Paragraph {
811 text: "a\n\nb".into(),
812 rect: [0.0, 0.0, 100.0, 100.0],
813 font: Standard14::Helvetica,
814 size: 10.0,
815 ..Paragraph::default()
816 };
817 lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap();
818 let moves: Vec<&Op> = canvas
819 .ops()
820 .iter()
821 .filter(|op| matches!(op, Op::TextMove(..)))
822 .collect();
823 assert_eq!(
824 moves,
825 [&Op::TextMove(0.0, 90.0), &Op::TextMove(0.0, 66.0)],
826 "blank line should still consume a leading slot"
827 );
828 let shows: Vec<&Op> = canvas
829 .ops()
830 .iter()
831 .filter(|op| matches!(op, Op::ShowText(..)))
832 .collect();
833 assert_eq!(
834 shows,
835 [&Op::ShowText(b"a".to_vec()), &Op::ShowText(b"b".to_vec()),]
836 );
837 }
838
839 #[test]
840 fn paragraph_leading_override_changes_line_advance() {
841 let mut canvas = Canvas::new();
842 let mut links = Vec::new();
843 let paragraph = Paragraph {
844 text: "aaaaaaaaaa bbbbbbbbbb".into(),
845 rect: [0.0, 0.0, 60.0, 100.0],
846 font: Standard14::Courier,
847 size: 10.0,
848 leading: Some(20.0),
849 ..Paragraph::default()
850 };
851 lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap();
852 let moves: Vec<&Op> = canvas
853 .ops()
854 .iter()
855 .filter(|op| matches!(op, Op::TextMove(..)))
856 .collect();
857 assert_eq!(moves, [&Op::TextMove(0.0, 90.0), &Op::TextMove(0.0, 70.0)]);
858 }
859
860 #[test]
861 fn paragraph_propagates_unencodable_character_error_untouched() {
862 let mut canvas = Canvas::new();
863 let mut links = Vec::new();
864 let paragraph = Paragraph {
865 text: "\u{2318}".into(),
866 rect: [0.0, 0.0, 100.0, 100.0],
867 font: Standard14::Helvetica,
868 size: 10.0,
869 ..Paragraph::default()
870 };
871 let err = lower(vec![paragraph.into()], &mut canvas, &mut links).unwrap_err();
872 assert!(matches!(
873 err,
874 Error::Unencodable {
875 ch: '\u{2318}',
876 font: "Helvetica"
877 }
878 ));
879 }
880
881 #[test]
882 fn image_draw_uses_placed_size() {
883 use pdfboss_core::Matrix;
884
885 let mut canvas = Canvas::new();
886 let image = Image {
887 data: ImageData::gray8(2, 2, vec![0u8; 4]).unwrap(),
888 at: Point::new(5.0, 6.0),
889 width: Some(40.0),
890 height: None,
891 };
892 image.draw(&mut canvas).unwrap();
893 assert_eq!(
894 canvas.ops(),
895 [
896 Op::Save,
897 Op::Concat(Matrix {
898 a: 40.0,
899 b: 0.0,
900 c: 0.0,
901 d: 40.0,
902 e: 5.0,
903 f: 6.0,
904 }),
905 Op::XObject(Name("Im1".into())),
906 Op::Restore,
907 ]
908 );
909 }
910}