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
//! Defines the [PdfPageGroupObject] struct, exposing functionality related to a group of
//! page objects contained in the same `PdfPageObjects` collection.
use crate::bindgen::{FPDF_DOCUMENT, FPDF_PAGE, FPDF_PAGEOBJECT};
use crate::bindings::PdfiumLibraryBindings;
use crate::color::PdfColor;
use crate::error::PdfiumError;
use crate::page::{PdfPage, PdfPageContentRegenerationStrategy, PdfPoints, PdfRect};
use crate::page_index_cache::PdfPageIndexCache;
use crate::page_object::{
PdfPageObject, PdfPageObjectBlendMode, PdfPageObjectCommon, PdfPageObjectLineCap,
PdfPageObjectLineJoin,
};
use crate::page_object_path::PdfPathFillMode;
use crate::page_object_private::internal::PdfPageObjectPrivate;
use crate::page_objects_common::{PdfPageObjectIndex, PdfPageObjectsCommon};
use crate::pages::{PdfPageIndex, PdfPages};
use crate::pdfium::Pdfium;
use crate::prelude::PdfDocument;
use crate::transform::PdfMatrix;
use std::collections::HashMap;
/// A group of [PdfPageObject] objects contained in the same `PdfPageObjects` collection.
/// The page objects contained in the group can be manipulated and transformed together
/// as if they were a single object.
///
/// Groups are bound to specific pages in the document. To create an empty group, use either the
/// `PdfPageObjects::create_new_group()` function or the [PdfPageGroupObject::empty()] function.
/// To create a populated group, use one of the [PdfPageGroupObject::new()],
/// [PdfPageGroupObject::from_vec()], or [PdfPageGroupObject::from_slice()] functions.
pub struct PdfPageGroupObject<'a> {
object_handles: Vec<FPDF_PAGEOBJECT>,
page_handle: FPDF_PAGE,
document_handle: FPDF_DOCUMENT,
bindings: &'a dyn PdfiumLibraryBindings,
do_regenerate_page_content_after_each_change: bool,
}
impl<'a> PdfPageGroupObject<'a> {
#[inline]
pub(crate) fn from_pdfium(
page_handle: FPDF_PAGE,
document_handle: FPDF_DOCUMENT,
bindings: &'a dyn PdfiumLibraryBindings,
do_regenerate_page_content_after_each_change: bool,
) -> Self {
PdfPageGroupObject {
object_handles: Vec::new(),
page_handle,
document_handle,
bindings,
do_regenerate_page_content_after_each_change,
}
}
/// Creates a new, empty [PdfPageGroupObject] that can be used to hold any page objects
/// on the given [PdfPage].
pub fn empty(page: &'a PdfPage) -> Self {
Self::from_pdfium(
*page.handle(),
*page.document().handle(),
page.bindings(),
page.content_regeneration_strategy()
== PdfPageContentRegenerationStrategy::AutomaticOnEveryChange,
)
}
/// Creates a new [PdfPageGroupObject] that includes any page objects on the given [PdfPage]
/// matching the given predicate function.
pub fn new<F>(page: &'a PdfPage, predicate: F) -> Result<Self, PdfiumError>
where
F: FnMut(&PdfPageObject) -> bool,
{
let mut result = Self::from_pdfium(
*page.handle(),
*page.document().handle(),
page.bindings(),
page.content_regeneration_strategy()
== PdfPageContentRegenerationStrategy::AutomaticOnEveryChange,
);
for mut object in page.objects().iter().filter(predicate) {
result.push(&mut object)?;
}
Ok(result)
}
/// Creates a new [PdfPageGroupObject] that includes the given page objects on the
/// given [PdfPage].
#[inline]
pub fn from_vec(
page: &PdfPage<'a>,
mut objects: Vec<PdfPageObject<'a>>,
) -> Result<Self, PdfiumError> {
Self::from_slice(page, objects.as_mut_slice())
}
/// Creates a new [PdfPageGroupObject] that includes the given page objects on the
/// given [PdfPage].
pub fn from_slice(
page: &PdfPage<'a>,
objects: &mut [PdfPageObject<'a>],
) -> Result<Self, PdfiumError> {
let mut result = Self::from_pdfium(
*page.handle(),
*page.document().handle(),
page.bindings(),
page.content_regeneration_strategy()
== PdfPageContentRegenerationStrategy::AutomaticOnEveryChange,
);
for object in objects.iter_mut() {
result.push(object)?;
}
Ok(result)
}
/// Returns the number of page objects in this group.
#[inline]
pub fn len(&self) -> usize {
self.object_handles.len()
}
/// Returns `true` if this group contains no page objects.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns `true` if this group already contains the given page object.
#[inline]
pub fn contains(&self, object: &PdfPageObject) -> bool {
self.object_handles.contains(object.get_object_handle())
}
/// Adds a single [PdfPageObject] to this group.
pub fn push(&mut self, object: &mut PdfPageObject<'a>) -> Result<(), PdfiumError> {
let was_object_already_attached_to_group_page =
if let Some(page_handle) = object.get_page_handle() {
if *page_handle != self.page_handle {
// The object is attached to a different page.
// In theory, transferring ownership of the page object from its current
// page to the page referenced by this group should be possible:
// object.remove_object_from_page()?;
// object.add_object_to_page_handle(self.page)?;
// But in practice, as per https://github.com/ajrcarey/pdfium-render/issues/18,
// transferring memory ownership of a page object from one page to another
// generally segfaults Pdfium. Instead, return an error.
return Err(PdfiumError::PageObjectAlreadyAttachedToDifferentPage);
} else {
// The object is already attached to this group's parent page.
true
}
} else {
// The object isn't attached to a page.
object.add_object_to_page_handle(self.page_handle)?;
false
};
self.object_handles.push(*object.get_object_handle());
if !was_object_already_attached_to_group_page
&& self.do_regenerate_page_content_after_each_change
{
PdfPage::regenerate_content_immut_for_handle(self.page_handle, self.bindings)?;
}
Ok(())
}
/// Adds all the given [PdfPageObject] objects to this group.
pub fn append(&mut self, objects: &mut [PdfPageObject<'a>]) -> Result<(), PdfiumError> {
// Hold off regenerating page content until all objects have been processed.
let do_regenerate_page_content_after_each_change =
self.do_regenerate_page_content_after_each_change;
self.do_regenerate_page_content_after_each_change = false;
for object in objects.iter_mut() {
self.push(object)?;
}
// Regenerate page content now, if necessary.
self.do_regenerate_page_content_after_each_change =
do_regenerate_page_content_after_each_change;
if self.do_regenerate_page_content_after_each_change {
PdfPage::regenerate_content_immut_for_handle(self.page_handle, self.bindings)?;
}
Ok(())
}
/// Removes every [PdfPageObject] in this group from the group's containing [PdfPage]
/// and from this group, consuming the group.
///
/// Each object's memory ownership will be removed from the `PdfPageObjects` collection for
/// this group's containing [PdfPage]. The objects will also be removed from this group,
/// and the memory owned by each object will be freed.
///
/// If the containing [PdfPage] has a content regeneration strategy of
/// `PdfPageContentRegenerationStrategy::AutomaticOnEveryChange` then content regeneration
/// will be triggered on the page.
#[inline]
pub fn remove_objects_from_page(mut self) -> Result<(), PdfiumError> {
// Hold off regenerating page content until all objects have been processed.
let do_regenerate_page_content_after_each_change =
self.do_regenerate_page_content_after_each_change;
self.do_regenerate_page_content_after_each_change = false;
// Remove the selected objects from the source page.
self.apply_to_each(|object| object.remove_object_from_page())?;
self.object_handles.clear();
// A curious upstream bug in Pdfium means that any objects _not_ removed from the page
// may be vertically reflected and translated. Attempt to mitigate this.
// For more details, see: https://github.com/ajrcarey/pdfium-render/issues/60
let page_height = PdfPoints::new(self.bindings.FPDF_GetPageHeightF(self.page_handle));
for index in 0..self.bindings.FPDFPage_CountObjects(self.page_handle) {
let mut object = PdfPageObject::from_pdfium(
self.bindings.FPDFPage_GetObject(self.page_handle, index),
Some(self.page_handle),
None,
self.bindings,
);
// Undo the reflection effect.
// TODO: AJRC - 28/1/23 - it is not clear that _all_ objects need to be unreflected.
// The challenge here is detecting which objects, if any, have been affected by
// the Pdfium reflection bug. Testing suggests that comparing object transformation matrices
// before and after object removal doesn't result in any detectable change to the matrices,
// so that approach doesn't work.
object.flip_vertically()?;
object.translate(PdfPoints::ZERO, page_height)?;
}
// Regenerate page content now, if necessary.
self.do_regenerate_page_content_after_each_change =
do_regenerate_page_content_after_each_change;
if self.do_regenerate_page_content_after_each_change {
PdfPage::regenerate_content_immut_for_handle(self.page_handle, self.bindings)?;
}
Ok(())
}
/// Returns a single [PdfPageObject] from this group.
#[inline]
pub fn get(&self, index: PdfPageObjectIndex) -> Result<PdfPageObject, PdfiumError> {
if let Some(handle) = self.object_handles.get(index) {
Ok(self.get_object_from_handle(handle))
} else {
Err(PdfiumError::PageObjectIndexOutOfBounds)
}
}
/// Retains only the [PdfPageObject] objects in this group specified by the given predicate function.
///
/// Unretained objects are only removed from this group. They remain on the source [PdfPage] that
/// currently contains them.
pub fn retain<F>(&mut self, f: F)
where
F: Fn(&PdfPageObject) -> bool,
{
// The naive approach of using self.object_handles.retain() directly like so:
// self.object_handles.retain(|handle| f(&self.get_object_from_handle(handle)));
// does not work, due to self being borrowed both mutably and immutably simultaneously.
// Instead, we build a separate list indicating whether each object should be retained
// or discarded ...
let mut do_retain = vec![false; self.object_handles.len()];
for (index, handle) in self.object_handles.iter().enumerate() {
do_retain[index] = f(&self.get_object_from_handle(handle));
}
// ... and then we use that marker list in our call to self.object_handles.retain().
let mut index = 0;
self.object_handles.retain(|_| {
// Should the object at index position |index| be retained?
let do_retain = do_retain[index];
index += 1;
do_retain
});
}
/// Retains only the [PdfPageObject] objects in this group that can be copied.
///
/// Objects that cannot be copied are only removed from this group. They remain on the source
/// [PdfPage] that currently contains them.
#[inline]
pub fn retain_if_copyable(&mut self) {
self.retain(|object| object.is_copyable());
}
/// Returns `true` if all the [PdfPageObject] objects in this group can be copied.
#[inline]
pub fn is_copyable(&self) -> bool {
self.iter().all(|object| object.is_copyable())
}
/// Attempts to copy all the [PdfPageObject] objects in this group, placing the copied objects
/// onto the given existing destination [PdfPage].
///
/// This function can only copy page objects supported by the [PdfPageObjectCommon::try_copy()]
/// method. For a different approach that supports more page object types but is more limited
/// in where the copied objects can be placed, see the [PdfPageGroupObject::copy_onto_new_page_at_start()],
/// [PdfPageGroupObject::copy_onto_new_page_at_end()], and
/// [PdfPageGroupObject::copy_onto_new_page_at_index()] functions.
///
/// If all objects were copied successfully, then a new [PdfPageGroupObject] containing the clones
/// is returned, allowing the new objects to be manipulated as a group.
pub fn try_copy_onto_existing_page<'b>(
&self,
destination: &mut PdfPage<'b>,
) -> Result<PdfPageGroupObject<'b>, PdfiumError> {
if !self.is_copyable() {
return Err(PdfiumError::GroupContainsNonCloneablePageObjects);
}
let mut group = destination.objects_mut().create_empty_group();
for handle in self.object_handles.iter() {
let source = self.get_object_from_handle(handle);
let clone = source.try_copy(destination.document())?;
group.push(&mut destination.objects_mut().add_object(clone)?)?;
}
Ok(group)
}
/// Copies all the [PdfPageObject] objects in this group by copying the page containing the
/// objects in this group into a new page at the start of the given destination [PdfDocument]
/// then removing all objects from the new page _not_ in this group.
///
/// This function differs internally from [PdfPageGroupObject::try_copy_onto_existing_page()]
/// in that it uses `Pdfium` to copy page objects instead of the [PdfPageObjectCommon::try_copy()]
/// method provided by `pdfium-render`. As a result, this function can copy some objects that
/// [PdfPageGroupObject::try_copy_onto_existing_page()] cannot; for example, it can copy
/// path objects containing Bézier curves. However, it can only copy objects onto a new page,
/// not an existing page, and it cannot return a new [PdfPageGroupObject] containing the
/// newly created objects.
///
/// The new page will have the same size and bounding box configuration as the page containing
/// the objects in this group.
#[inline]
pub fn copy_onto_new_page_at_start(
&self,
destination: &PdfDocument,
) -> Result<(), PdfiumError> {
self.copy_onto_new_page_at_index(0, destination)
}
/// Copies all the [PdfPageObject] objects in this group by copying the page containing the
/// objects in this group into a new page at the end of the given destination [PdfDocument]
/// then removing all objects from the new page _not_ in this group.
///
/// This function differs internally from [PdfPageGroupObject::try_copy_onto_existing_page()]
/// in that it uses `Pdfium` to copy page objects instead of the [PdfPageObjectCommon::try_copy()]
/// method provided by `pdfium-render`. As a result, this function can copy some objects that
/// [PdfPageGroupObject::try_copy_onto_existing_page()] cannot; for example, it can copy
/// path objects containing Bézier curves. However, it can only copy objects onto a new page,
/// not an existing page, and it cannot return a new [PdfPageGroupObject] containing the
/// newly created objects.
///
/// The new page will have the same size and bounding box configuration as the page containing
/// the objects in this group.
#[inline]
pub fn copy_onto_new_page_at_end(&self, destination: &PdfDocument) -> Result<(), PdfiumError> {
self.copy_onto_new_page_at_index(destination.pages().len(), destination)
}
/// Copies all the [PdfPageObject] objects in this group by copying the page containing the
/// objects in this group into a new page in the given destination [PdfDocument] at the given
/// page index, then removing all objects from the new page _not_ in this group.
///
/// This function differs internally from [PdfPageGroupObject::try_copy_onto_existing_page()]
/// in that it uses `Pdfium` to copy page objects instead of the [PdfPageObjectCommon::try_copy()]
/// method provided by `pdfium-render`. As a result, this function can copy some objects that
/// [PdfPageGroupObject::try_copy_onto_existing_page()] cannot; for example, it can copy
/// path objects containing Bézier curves. However, it can only copy objects onto a new page,
/// not an existing page, and it cannot return a new [PdfPageGroupObject] containing the
/// newly created objects.
///
/// The new page will have the same size and bounding box configuration as the page containing
/// the objects in this group.
#[inline]
pub fn copy_onto_new_page_at_index(
&self,
index: PdfPageIndex,
destination: &PdfDocument,
) -> Result<(), PdfiumError> {
// Pdfium provides the FPDF_ImportPages() function for copying one or more pages
// from one document into another. Using this function as a substitute for true
// page object cloning allows us to clone some objects (such as path objects containing
// Bézier curves) that PdfPageObject::try_clone() cannot.
// To use FPDF_ImportPages() as a cloning substitute, we take the following approach:
// First, we create a new in-memory document and import the source page for this
// page object group into that new document.
let cache = Pdfium::pdfium_document_handle_to_result(
self.bindings.FPDF_CreateNewDocument(),
self.bindings,
)?;
if let Some(source_page_index) =
PdfPageIndexCache::get_index_for_page(self.document_handle, self.page_handle)
{
PdfPages::copy_page_range_between_documents(
self.document_handle,
source_page_index..=source_page_index,
*cache.handle(),
0,
self.bindings,
)?;
} else {
return Err(PdfiumError::GroupCannotLocateSourcePageIndex);
}
// Next, we remove all page objects from the in-memory document _except_ the ones in this group.
// We cannot compare object references across documents. Instead, we build a map of
// the types of objects, their positions, their bounds, and their transformation matrices,
// and use this map to determine which objects should be removed from the in-memory page.
let mut objects_to_discard = HashMap::new();
for index in 0..self.bindings.FPDFPage_CountObjects(self.page_handle) {
let object = PdfPageObject::from_pdfium(
self.bindings.FPDFPage_GetObject(self.page_handle, index),
Some(self.page_handle),
None,
self.bindings,
);
if !self.contains(&object) {
objects_to_discard.insert(
(object.bounds()?, object.matrix()?, object.object_type()),
true,
);
}
}
// We now have a map of objects that should be removed from the in-memory page; after
// we remove them, only the clones of the objects in this group will remain on the page.
cache
.pages()
.get(0)?
.objects()
.create_group(|object| {
objects_to_discard.contains_key(&(
object.bounds().unwrap_or(PdfRect::ZERO),
object.matrix().unwrap_or(PdfMatrix::IDENTITY),
object.object_type(),
))
})?
.remove_objects_from_page()?;
// Finally, with only the clones of the objects in this group left on the in-memory page,
// we now copy the page back into the given destination.
PdfPages::copy_page_range_between_documents(
*cache.handle(),
0..=0,
*destination.handle(),
index,
self.bindings,
)?;
Ok(())
}
/// Returns an iterator over all the [PdfPageObject] objects in this group.
#[inline]
pub fn iter(&'a self) -> PdfPageGroupObjectIterator<'a> {
PdfPageGroupObjectIterator::new(self)
}
/// Returns the text contained within all `PdfPageTextObject` objects in this group.
#[inline]
pub fn text(&self) -> String {
self.text_separated("")
}
/// Returns the text contained within all `PdfPageTextObject` objects in this group,
/// separating each text fragment with the given separator.
pub fn text_separated(&self, separator: &str) -> String {
let mut strings = Vec::with_capacity(self.len());
self.for_each(|object| {
if let Some(object) = object.as_text_object() {
strings.push(object.text());
}
});
strings.join(separator)
}
/// Returns `true` if any [PdfPageObject] in this group contains transparency.
#[inline]
pub fn has_transparency(&self) -> bool {
self.object_handles.iter().any(|object_handle| {
PdfPageObject::from_pdfium(*object_handle, Some(self.page_handle), None, self.bindings)
.has_transparency()
})
}
/// Returns the bounding box of this group of objects. Since the bounds of every object in the
/// group must be considered, this function has runtime complexity of O(n).
pub fn bounds(&self) -> Result<PdfRect, PdfiumError> {
let mut bounds: Option<PdfRect> = None;
self.object_handles.iter().for_each(|object_handle| {
if let Ok(object_bounds) = PdfPageObject::from_pdfium(
*object_handle,
Some(self.page_handle),
None,
self.bindings,
)
.bounds()
{
if let Some(bounds) = bounds.as_mut() {
if object_bounds.bottom < bounds.bottom {
bounds.bottom = object_bounds.bottom;
}
if object_bounds.left < bounds.left {
bounds.left = object_bounds.left;
}
if object_bounds.top > bounds.top {
bounds.top = object_bounds.top;
}
if object_bounds.right > bounds.right {
bounds.right = object_bounds.right;
}
} else {
bounds = Some(object_bounds);
}
}
});
bounds.ok_or(PdfiumError::EmptyPageObjectGroup)
}
/// Applies the given transformation, expressed as six values representing the six configurable
/// elements of a nine-element 3x3 PDF transformation matrix, to every [PdfPageObject] in this group.
///
/// To move, scale, rotate, or skew the page objects in this group, consider using one or more of the
/// following functions. Internally they all use [PdfPageGroupObject::transform()], but are
/// probably easier to use (and certainly clearer in their intent) in most situations.
///
/// * [PdfPageGroupObject::translate()]: changes the position of every [PdfPageObject] in this group.
/// * [PdfPageGroupObject::scale()]: changes the size of every [PdfPageObject] in this group.
/// * [PdfPageGroupObject::rotate_clockwise_degrees()], [PdfPageGroupObject::rotate_counter_clockwise_degrees()],
/// [PdfPageGroupObject::rotate_clockwise_radians()], [PdfPageGroupObject::rotate_counter_clockwise_radians()]:
/// rotates every [PdfPageObject] in this group around its origin.
/// * [PdfPageGroupObject::skew_degrees()], [PdfPageGroupObject::skew_radians()]: skews every
/// [PdfPageObject] in this group relative to its axes.
///
/// **The order in which transformations are applied to a page object is significant.**
/// For example, the result of rotating _then_ translating a page object may be vastly different
/// from translating _then_ rotating the same page object.
///
/// An overview of PDF transformation matrices can be found in the PDF Reference Manual
/// version 1.7 on page 204; a detailed description can be founded in section 4.2.3 on page 207.
#[inline]
pub fn transform(
&mut self,
a: f64,
b: f64,
c: f64,
d: f64,
e: f64,
f: f64,
) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.transform(a, b, c, d, e, f))
}
/// Moves the origin of every [PdfPageObject] in this group by the given horizontal and vertical
/// delta distances.
#[inline]
pub fn translate(&mut self, delta_x: PdfPoints, delta_y: PdfPoints) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.translate(delta_x, delta_y))
}
/// Changes the size of every [PdfPageObject] in this group, scaling them by the given
/// horizontal and vertical scale factors.
#[inline]
pub fn scale(
&mut self,
horizontal_scale_factor: f64,
vertical_scale_factor: f64,
) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.scale(horizontal_scale_factor, vertical_scale_factor))
}
/// Rotates every [PdfPageObject] in this group counter-clockwise by the given number of degrees.
#[inline]
pub fn rotate_counter_clockwise_degrees(&mut self, degrees: f32) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.rotate_counter_clockwise_degrees(degrees))
}
/// Rotates every [PdfPageObject] in this group clockwise by the given number of degrees.
#[inline]
pub fn rotate_clockwise_degrees(&mut self, degrees: f32) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.rotate_clockwise_degrees(degrees))
}
/// Rotates every [PdfPageObject] in this group counter-clockwise by the given number of radians.
#[inline]
pub fn rotate_counter_clockwise_radians(&mut self, radians: f32) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.rotate_counter_clockwise_radians(radians))
}
/// Rotates every [PdfPageObject] in this group clockwise by the given number of radians.
#[inline]
pub fn rotate_clockwise_radians(&mut self, radians: f32) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.rotate_clockwise_radians(radians))
}
/// Skews the axes of every [PdfPageObject] in this group by the given angles in degrees.
#[inline]
pub fn skew_degrees(&mut self, x_axis_skew: f32, y_axis_skew: f32) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.skew_degrees(x_axis_skew, y_axis_skew))
}
/// Skews the axes of every [PdfPageObject] in this group by the given angles in radians.
#[inline]
pub fn skew_radians(&mut self, x_axis_skew: f32, y_axis_skew: f32) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.skew_radians(x_axis_skew, y_axis_skew))
}
/// Sets the blend mode that will be applied when painting every [PdfPageObject] in this group.
#[inline]
pub fn set_blend_mode(
&mut self,
blend_mode: PdfPageObjectBlendMode,
) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.set_blend_mode(blend_mode))
}
/// Sets the color of any filled paths in every [PdfPageObject] in this group.
#[inline]
pub fn set_fill_color(&mut self, fill_color: PdfColor) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.set_fill_color(fill_color))
}
/// Sets the color of any stroked lines in every [PdfPageObject] in this group.
///
/// Even if an object's path is set with a visible color and a non-zero stroke width,
/// the object's stroke mode must be set in order for strokes to actually be visible.
#[inline]
pub fn set_stroke_color(&mut self, stroke_color: PdfColor) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.set_stroke_color(stroke_color))
}
/// Sets the width of any stroked lines in every [PdfPageObject] in this group.
///
/// A line width of 0 denotes the thinnest line that can be rendered at device resolution:
/// 1 device pixel wide. However, some devices cannot reproduce 1-pixel lines,
/// and on high-resolution devices, they are nearly invisible. Since the results of rendering
/// such zero-width lines are device-dependent, their use is not recommended.
///
/// Even if an object's path is set with a visible color and a non-zero stroke width,
/// the object's stroke mode must be set in order for strokes to actually be visible.
#[inline]
pub fn set_stroke_width(&mut self, stroke_width: PdfPoints) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.set_stroke_width(stroke_width))
}
/// Sets the line join style that will be used when painting stroked path segments
/// in every [PdfPageObject] in this group.
#[inline]
pub fn set_line_join(&mut self, line_join: PdfPageObjectLineJoin) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.set_line_join(line_join))
}
/// Sets the line cap style that will be used when painting stroked path segments
/// in every [PdfPageObject] in this group.
#[inline]
pub fn set_line_cap(&mut self, line_cap: PdfPageObjectLineCap) -> Result<(), PdfiumError> {
self.apply_to_each(|object| object.set_line_cap(line_cap))
}
/// Sets the method used to determine which sub-paths of any path in a [PdfPageObject]
/// should be filled, and whether or not any path in a [PdfPageObject] should be stroked,
/// for every [PdfPageObject] in this group.
///
/// Even if an object's path is set to be stroked, the stroke must be configured with
/// a visible color and a non-zero width in order to actually be visible.
#[inline]
pub fn set_fill_and_stroke_mode(
&mut self,
fill_mode: PdfPathFillMode,
do_stroke: bool,
) -> Result<(), PdfiumError> {
self.apply_to_each(|object| {
if let Some(object) = object.as_path_object_mut() {
object.set_fill_and_stroke_mode(fill_mode, do_stroke)
} else {
Ok(())
}
})
}
/// Applies the given closure to each [PdfPageObject] in this group.
#[inline]
pub(crate) fn apply_to_each<F, T>(&mut self, f: F) -> Result<(), PdfiumError>
where
F: Fn(&mut PdfPageObject<'a>) -> Result<T, PdfiumError>,
{
let mut error = None;
self.object_handles.iter().for_each(|handle| {
if let Err(err) = f(&mut self.get_object_from_handle(handle)) {
error = Some(err)
}
});
match error {
Some(err) => Err(err),
None => Ok(()),
}
}
/// Calls the given closure on each [PdfPageObject] in this group.
#[inline]
pub(crate) fn for_each<F>(&self, mut f: F)
where
F: FnMut(&mut PdfPageObject<'a>),
{
self.object_handles.iter().for_each(|handle| {
f(&mut self.get_object_from_handle(handle));
});
}
/// Inflates an internal `FPDF_PAGEOBJECT` handle into a [PdfPageObject].
#[inline]
pub(crate) fn get_object_from_handle(&self, handle: &FPDF_PAGEOBJECT) -> PdfPageObject<'a> {
PdfPageObject::from_pdfium(*handle, Some(self.page_handle), None, self.bindings)
}
}
/// An iterator over all the [PdfPageObject] objects in a [PdfPageGroupObject] group.
pub struct PdfPageGroupObjectIterator<'a> {
group: &'a PdfPageGroupObject<'a>,
next_index: PdfPageObjectIndex,
}
impl<'a> PdfPageGroupObjectIterator<'a> {
#[inline]
pub(crate) fn new(group: &'a PdfPageGroupObject<'a>) -> Self {
PdfPageGroupObjectIterator {
group,
next_index: 0,
}
}
}
impl<'a> Iterator for PdfPageGroupObjectIterator<'a> {
type Item = PdfPageObject<'a>;
fn next(&mut self) -> Option<Self::Item> {
let next = self.group.get(self.next_index);
self.next_index += 1;
next.ok()
}
}
#[cfg(test)]
mod test {
use crate::page_object_group::PdfPageGroupObject;
use crate::prelude::*;
use crate::utils::test::test_bind_to_pdfium;
#[test]
fn test_group_bounds() -> Result<(), PdfiumError> {
let pdfium = test_bind_to_pdfium();
let document = pdfium.load_pdf_from_file("./test/export-test.pdf", None)?;
// Form a group of all text objects in the top half of the first page of music ...
let page = document.pages().get(2)?;
let mut group = page.objects().create_empty_group();
group.append(
page.objects()
.iter()
.filter(|object| {
object.object_type() == PdfPageObjectType::Text
&& object.bounds().unwrap().bottom > page.height() / 2.0
})
.collect::<Vec<_>>()
.as_mut_slice(),
)?;
// ... and confirm the group's bounds are restricted to the top half of the page.
let bounds = group.bounds()?;
assert_eq!(bounds.bottom.value, 428.3103);
assert_eq!(bounds.left.value, 62.60526);
assert_eq!(bounds.top.value, 807.8812);
assert_eq!(bounds.right.value, 544.4809);
Ok(())
}
#[test]
fn test_group_text() -> Result<(), PdfiumError> {
let pdfium = test_bind_to_pdfium();
let document = pdfium.load_pdf_from_file("./test/export-test.pdf", None)?;
// Form a group of all text objects in the bottom half of the last page of music ...
let page = document.pages().get(5)?;
let mut group = page.objects().create_empty_group();
group.append(
page.objects()
.iter()
.filter(|object| {
object.object_type() == PdfPageObjectType::Text
&& object.bounds().unwrap().bottom < page.height() / 2.0
})
.collect::<Vec<_>>()
.as_mut_slice(),
)?;
// ... and extract the text from the group.
assert_eq!(group.text_separated(" "), "Cento Concerti Ecclesiastici a Una, a Due, a Tre, e a Quattro voci Giacomo Vincenti, Venice, 1605 Edited by Alastair Carey Source is the 1605 reprint of the original 1602 publication. Item #2 in the source. Folio pages f5r (binding B1) in both Can to and Basso partbooks. The Basso partbook is barred; the Canto par tbook is not. The piece is marked ™Canto solo, Û Tenoreº in the Basso partbook, indicating it can be sung either by a Soprano or by a Tenor down an octave. V. Quem vidistis, pastores, dicite, annuntiate nobis: in terris quis apparuit? R. Natum vidimus, et choros angelorum collaudantes Dominum. Alleluia. What did you see, shepherds, speak, tell us: who has appeared on earth? We saw the new-born, and choirs of angels praising the Lord. Alleluia. Third responsory at Matins on Christmas Day 2 Basso, bar 47: one tone lower in source.");
Ok(())
}
#[test]
fn test_group_apply() -> Result<(), PdfiumError> {
// Measure the bounds of a group of objects, translate the group, and confirm the
// bounds have changed.
let pdfium = test_bind_to_pdfium();
let document = pdfium.create_new_pdf()?;
let mut page = document
.pages()
.create_page_at_start(PdfPagePaperSize::a4())?;
page.objects_mut().create_path_object_rect(
PdfRect::new_from_values(100.0, 100.0, 200.0, 200.0),
None,
None,
Some(PdfColor::SOLID_RED),
)?;
page.objects_mut().create_path_object_rect(
PdfRect::new_from_values(150.0, 150.0, 250.0, 250.0),
None,
None,
Some(PdfColor::SOLID_GREEN),
)?;
page.objects_mut().create_path_object_rect(
PdfRect::new_from_values(200.0, 200.0, 300.0, 300.0),
None,
None,
Some(PdfColor::SOLID_BLUE),
)?;
let mut group = PdfPageGroupObject::new(&page, |_| true)?;
let bounds = group.bounds()?;
assert_eq!(bounds.bottom.value, 100.0);
assert_eq!(bounds.left.value, 100.0);
assert_eq!(bounds.top.value, 300.0);
assert_eq!(bounds.right.value, 300.0);
group.translate(PdfPoints::new(150.0), PdfPoints::new(200.0))?;
let bounds = group.bounds()?;
assert_eq!(bounds.bottom.value, 300.0);
assert_eq!(bounds.left.value, 250.0);
assert_eq!(bounds.top.value, 500.0);
assert_eq!(bounds.right.value, 450.0);
Ok(())
}
}