Image

Struct Image 

Source
pub struct Image {
    source: ImageSource,
    alignment: Alignment,
    position: Option<Position>,
    scale: Scale,
    fit_to_page_width: Option<f32>,
    fit_to_page_height: Option<f32>,
    rotation: Rotation,
    background_color: Option<Color>,
    dpi: Option<f32>,
    link: Option<String>,
}
Expand description

An image to embed in the PDF.

Only available if the images feature is enabled.

This struct supports both raster images and vector SVG graphics. Raster images are wrapped around the configurations printpdf::Image exposes, while SVG images use printpdf’s native vector graphics support without rasterization.

§Supported Raster Formats

All formats supported by the image crate should be supported by this crate. The BMP, JPEG and PNG formats are well tested and known to work.

Note that only the GIF, JPEG, PNG, PNM, TIFF and BMP formats are enabled by default. If you want to use other formats, you have to add the image crate as a dependency and activate the required feature.

§SVG Support

SVG images are embedded as vector graphics without rasterization. They are processed through printpdf’s SVG parser and rendered as XObjects in the PDF.

§Examples

Load and display a raster image:

use genpdfi_extended::elements;
let image = elements::Image::from_path("examples/images/test_image.jpg")
      .expect("Failed to load test image")
      .with_alignment(genpdfi_extended::Alignment::Center)
      .with_scale(genpdfi_extended::Scale::new(0.5, 2.0));

Fields§

§source: ImageSource§alignment: Alignment

Used for positioning if no absolute position is given.

§position: Option<Position>

The absolute position within the given area.

If no position is set, we use the Alignment.

§scale: Scale

Scaling of the image, default is 1:1.

§fit_to_page_width: Option<f32>

Resize to a fraction of the page width (0.0 < fraction <= 1.0). When set, the image will be scaled proportionally so its width equals fraction * available_page_width at render time.

§fit_to_page_height: Option<f32>

Resize to a fraction of the page height (0.0 < fraction <= 1.0). When set, the image will be scaled proportionally so its height equals fraction * available_page_height at render time.

§rotation: Rotation

The number of degrees of clockwise rotation.

§background_color: Option<Color>

Optional background color used to composite away an alpha channel when rendering. If None the page background (white) is used.

§dpi: Option<f32>

DPI override if you know better. Defaults to printpdf’s default of 300 dpi.

§link: Option<String>

Optional hyperlink URI for the image. When set, clicking the image opens this URL.

Implementations§

Source§

impl Image

Source

pub fn from_dynamic_image(data: DynamicImage) -> Result<Self, Error>

Creates a new image from an already loaded raster image.

§Arguments
  • data - A DynamicImage from the image crate containing raster pixel data.
§Returns

A new Image struct configured with default alignment, no explicit position, default scale, and no transformations.

§Errors

This function cannot fail and always returns Ok(Image).

§Examples
use genpdfi_extended::elements::Image;
let img = image::DynamicImage::new_rgb8(100, 50);
let image = Image::from_dynamic_image(img).expect("create image");
Source

pub fn from_svg_string(svg_content: &str) -> Result<Self, Error>

Creates a new image from an SVG string.

The SVG is parsed by printpdf to extract vector graphics without rasterization.

§Arguments
  • svg_content - A string containing valid SVG markup.
§Returns

A new Image struct configured with default alignment, no explicit position, default scale, and no transformations.

§Errors

Returns an error if the SVG parsing fails.

§Examples
use genpdfi_extended::elements::Image;
let svg = r#"
  <svg width="100mm" height="50mm" viewBox="0 0 100 50" xmlns="http://www.w3.org/2000/svg">
    <circle cx="25" cy="25" r="20" fill="red"/>
  </svg>
"#;
let image = Image::from_svg_string(svg).expect("parse SVG");
Source

pub fn extract_dpi_from_svg(svg_content: &str) -> Option<f32>

Extracts DPI from the data-dpi attribute in SVG content.

This function looks for the data-dpi attribute in the SVG root element, which is embedded by microtex_rs when rendering LaTeX formulas.

§Arguments
  • svg_content - The SVG string to search for the data-dpi attribute.
§Returns

Some(dpi) if the attribute is found and contains a valid integer, None otherwise.

§Examples
use genpdfi_extended::elements::Image;
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" data-dpi="720" width="100" height="50"></svg>"#;
let dpi = Image::extract_dpi_from_svg(svg);
assert_eq!(dpi, Some(720.0));
Source

fn strip_svg_masks(svg_content: &str) -> String

Workaround for printpdf SVG parsing bug.

Removes element definitions and mask=“url(#…)” attribute references from SVG content to prevent “Invalid dictionary reference” errors during parsing.

This is a temporary workaround until printpdf properly supports SVG mask elements.

Source

pub fn from_svg_bytes(svg_bytes: &[u8]) -> Result<Self, Error>

Creates a new image by reading an SVG from a byte buffer.

§Arguments
  • svg_bytes - A byte slice containing valid SVG markup in UTF-8 encoding.
§Returns

A new Image struct with default configuration.

§Errors

Returns an error if the bytes are not valid UTF-8 or if SVG parsing fails.

§Examples
use genpdfi_extended::elements::Image;
let svg_bytes = b"<svg width='100mm' height='50mm'><circle cx='25' cy='25' r='20' fill='blue'/></svg>";
let image = Image::from_svg_bytes(svg_bytes).expect("create from bytes");
Source

pub fn from_svg_path<P: AsRef<Path>>(path: P) -> Result<Self, Error>

Creates a new image by reading an SVG from a file path.

§Arguments
  • path - A path to an SVG file.
§Returns

A new Image struct with default configuration.

§Errors

Returns an error if the file cannot be read, if its contents are not valid UTF-8, or if SVG parsing fails.

§Examples
use genpdfi_extended::elements::Image;
// This example assumes an SVG file exists at the path
// In a real scenario, create such a file first
let result = Image::from_svg_path("examples/test.svg");
// The result would be Ok or Err depending on file existence
Source

pub fn from_svg_reader<R: Read>(reader: R) -> Result<Self, Error>

Creates a new image from a reader yielding SVG content.

§Arguments
  • reader - A reader that yields SVG markup as bytes.
§Returns

A new Image struct with default configuration.

§Errors

Returns an error if reading fails, if content is not valid UTF-8, or if SVG parsing fails.

§Examples
use genpdfi_extended::elements::Image;
use std::io::Cursor;
let svg_data = b"<svg width='100mm' height='50mm'><rect width='100' height='50' fill='green'/></svg>";
let cursor = Cursor::new(svg_data.to_vec());
let image = Image::from_svg_reader(cursor).expect("create from reader");
Source

fn from_image_reader<R>(reader: Reader<R>) -> Result<Self, Error>
where R: BufRead + Read + Seek,

Source

pub fn from_reader<R>(reader: R) -> Result<Self, Error>
where R: BufRead + Read + Seek,

Creates a new image from the given reader.

Source

pub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error>

Creates a new image by reading from the given path.

Source

pub fn set_position(&mut self, position: impl Into<Position>)

Translates the image over to position.

Source

pub fn with_position(self, position: impl Into<Position>) -> Self

Translates the image over to position and returns it.

Source

pub fn set_scale(&mut self, scale: impl Into<Scale>)

Scales the image.

Source

pub fn with_scale(self, scale: impl Into<Scale>) -> Self

Scales the image and returns it.

Source

pub fn set_alignment(&mut self, alignment: impl Into<Alignment>)

Sets the alignment to use for this image.

Source

pub fn with_alignment(self, alignment: impl Into<Alignment>) -> Self

Sets the alignment to use for this image and returns it.

Source

fn get_offset(&self, width: Mm, max_width: Mm) -> Position

Determines the offset from left-side based on provided Alignment.

Source

fn get_size(&self) -> Size

Calculates a guess for the size of the image based on the dpi/pixel-count/scale.

Source

pub fn get_intrinsic_size(&self) -> Size

Returns the intrinsic size (without scale) of the image in mm.

For raster images, dimensions are calculated from pixel count and DPI. For SVG images, dimensions are extracted from the SVG’s width/height attributes.

This method is public to allow calculation of proportional scaling factors based on the original SVG dimensions (useful for scale_factor-based resizing).

§Returns

A Size struct containing width and height in millimeters.

Source

fn intrinsic_size(&self) -> Size

Returns the intrinsic size (without scale) of the image in mm.

Source

fn size_with_scale(&self, scale: Scale) -> Size

Computes size in mm for a given explicit scale (without modifying self.scale).

Source

pub fn set_clockwise_rotation(&mut self, rotation: impl Into<Rotation>)

Sets the clockwise rotation of the image around the bottom left corner.

Source

pub fn with_clockwise_rotation(self, rotation: impl Into<Rotation>) -> Self

Sets the clockwise rotation of the image around the bottom left corner and then returns the image.

Source

pub fn set_dpi(&mut self, dpi: f32)

Sets the expected DPI of the encoded image.

Source

pub fn with_dpi(self, dpi: f32) -> Self

Sets the expected DPI of the encoded image and returns it.

Source

pub fn set_background_color(&mut self, color: Color)

Set the background color used to composite away an alpha channel when rendering. If not set, white is used.

Source

pub fn with_background_color(self, color: Color) -> Self

Set the background color used to composite away an alpha channel and return the image.

§Examples
use genpdfi_extended::elements::Image;
use genpdfi_extended::style::Color;
// create a small RGBA image and set a background color for compositing at render time
let img = Image::from_dynamic_image(image::DynamicImage::new_rgba8(10, 10)).unwrap()
    .with_background_color(Color::Rgb(240, 240, 240));
// background color is applied at render-time; this example verifies construction only
let _ = img;

Sets a hyperlink URI for this image. When set, clicking the image will open this URL in a PDF viewer.

Sets a hyperlink URI for this image and returns it. When set, clicking the image will open this URL in a PDF viewer.

§Examples
use genpdfi_extended::elements::Image;
let img = Image::from_path("examples/images/test_image.jpg")
    .expect("load image")
    .with_link("https://example.com");
// Image is now clickable and will open the URL when clicked in a PDF viewer
Source

pub fn resizing_page_with(self, fraction: f32) -> Self

Resize proportionally so the image width becomes exactly fraction * available_page_width. fraction is in the range (0.0, 1.0]. This is applied at render-time using the actual available area width — no page width argument is required at call site.

§Examples
use genpdfi_extended::elements::Image;
use genpdfi_extended::Scale;
// create an in-memory RGB image (2400×450 px)
let img = Image::from_dynamic_image(image::DynamicImage::new_rgb8(2400, 450))
    .expect("create")
    .resizing_page_with(0.5);

// If available width is 190mm, 50% means 95mm target width
// intrinsic width (mm) for 2400px @ 300dpi: 2400 * 25.4 / 300 = 203.2mm
let intrinsic: f32 = 2400.0_f32 * 25.4_f32 / 300.0_f32;
let target: f32 = 190.0_f32 * 0.5_f32;
let scale: f32 = target / intrinsic;
let size_width: f32 = intrinsic * scale;
assert!((size_width - target).abs() < 0.1_f32);
Source

pub fn resizing_page_height(self, fraction: f32) -> Self

Resize proportionally so the image height becomes exactly fraction * available_page_height. See resizing_page_with for semantics.

§Examples
use genpdfi_extended::elements::Image;
use genpdfi_extended::Scale;
// create an in-memory RGB image (2400×450 px)
let img = Image::from_dynamic_image(image::DynamicImage::new_rgb8(2400, 450))
    .expect("create")
    .resizing_page_height(0.3);

// If available height is 277mm, 30% means ~83.1mm target height
// intrinsic height (mm) for 450px @ 300dpi: 450 * 25.4 / 300 = 38.1mm
let intrinsic: f32 = 450.0_f32 * 25.4_f32 / 300.0_f32;
let target: f32 = 277.0_f32 * 0.3_f32;
let scale: f32 = target / intrinsic;
let size_height: f32 = intrinsic * scale;
assert!((size_height - target).abs() < 0.1_f32);

Trait Implementations§

Source§

impl Clone for Image

Source§

fn clone(&self) -> Image

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Element for Image

Source§

fn render( &mut self, _context: &Context, area: Area<'_>, _style: Style, ) -> Result<RenderResult, Error>

Renders this element to the given area using the given style and font cache. Read more
Source§

fn framed(self, line_style: impl Into<LineStyle>) -> FramedElement<Self>
where Self: Sized,

Draws a frame around this element using the given line style.
Source§

fn padded(self, padding: impl Into<Margins>) -> PaddedElement<Self>
where Self: Sized,

Adds a padding to this element.
Source§

fn styled(self, style: impl Into<Style>) -> StyledElement<Self>
where Self: Sized,

Sets the default style for this element and its children.

Auto Trait Implementations§

§

impl Freeze for Image

§

impl RefUnwindSafe for Image

§

impl Send for Image

§

impl Sync for Image

§

impl Unpin for Image

§

impl UnwindSafe for Image

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Finish for T

§

fn finish(self)

Does nothing but move self, equivalent to drop.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<E> IntoBoxedElement for E
where E: Element + 'static,

Source§

fn into_boxed_element(self) -> Box<dyn Element>

Creates a boxed element from this element.
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<U, T> ToOwnedObj<U> for T
where U: FromObjRef<T>,

§

fn to_owned_obj(&self, data: FontData<'_>) -> U

Convert this type into T, using the provided data to resolve any offsets.
§

impl<U, T> ToOwnedTable<U> for T
where U: FromTableRef<T>,

§

fn to_owned_table(&self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V