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: AlignmentUsed 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: ScaleScaling 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: RotationThe 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
impl Image
Sourcepub fn from_dynamic_image(data: DynamicImage) -> Result<Self, Error>
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 theimagecrate 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");Sourcepub fn from_svg_string(svg_content: &str) -> Result<Self, Error>
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");Sourcepub fn extract_dpi_from_svg(svg_content: &str) -> Option<f32>
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 thedata-dpiattribute.
§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));Sourcefn strip_svg_masks(svg_content: &str) -> String
fn strip_svg_masks(svg_content: &str) -> String
Workaround for printpdf SVG
Removes
This is a temporary workaround until printpdf properly supports SVG mask elements.
Sourcepub fn from_svg_bytes(svg_bytes: &[u8]) -> Result<Self, Error>
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");Sourcepub fn from_svg_path<P: AsRef<Path>>(path: P) -> Result<Self, Error>
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 existenceSourcepub fn from_svg_reader<R: Read>(reader: R) -> Result<Self, Error>
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");fn from_image_reader<R>(reader: Reader<R>) -> Result<Self, Error>
Sourcepub fn from_reader<R>(reader: R) -> Result<Self, Error>
pub fn from_reader<R>(reader: R) -> Result<Self, Error>
Creates a new image from the given reader.
Sourcepub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error>
pub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error>
Creates a new image by reading from the given path.
Sourcepub fn set_position(&mut self, position: impl Into<Position>)
pub fn set_position(&mut self, position: impl Into<Position>)
Translates the image over to position.
Sourcepub fn with_position(self, position: impl Into<Position>) -> Self
pub fn with_position(self, position: impl Into<Position>) -> Self
Translates the image over to position and returns it.
Sourcepub fn with_scale(self, scale: impl Into<Scale>) -> Self
pub fn with_scale(self, scale: impl Into<Scale>) -> Self
Scales the image and returns it.
Sourcepub fn set_alignment(&mut self, alignment: impl Into<Alignment>)
pub fn set_alignment(&mut self, alignment: impl Into<Alignment>)
Sets the alignment to use for this image.
Sourcepub fn with_alignment(self, alignment: impl Into<Alignment>) -> Self
pub fn with_alignment(self, alignment: impl Into<Alignment>) -> Self
Sets the alignment to use for this image and returns it.
Sourcefn get_offset(&self, width: Mm, max_width: Mm) -> Position
fn get_offset(&self, width: Mm, max_width: Mm) -> Position
Determines the offset from left-side based on provided Alignment.
Sourcefn get_size(&self) -> Size
fn get_size(&self) -> Size
Calculates a guess for the size of the image based on the dpi/pixel-count/scale.
Sourcepub fn get_intrinsic_size(&self) -> Size
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.
Sourcefn intrinsic_size(&self) -> Size
fn intrinsic_size(&self) -> Size
Returns the intrinsic size (without scale) of the image in mm.
Sourcefn size_with_scale(&self, scale: Scale) -> Size
fn size_with_scale(&self, scale: Scale) -> Size
Computes size in mm for a given explicit scale (without modifying self.scale).
Sourcepub fn set_clockwise_rotation(&mut self, rotation: impl Into<Rotation>)
pub fn set_clockwise_rotation(&mut self, rotation: impl Into<Rotation>)
Sets the clockwise rotation of the image around the bottom left corner.
Sourcepub fn with_clockwise_rotation(self, rotation: impl Into<Rotation>) -> Self
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.
Sourcepub fn with_dpi(self, dpi: f32) -> Self
pub fn with_dpi(self, dpi: f32) -> Self
Sets the expected DPI of the encoded image and returns it.
Sourcepub fn set_background_color(&mut self, color: Color)
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.
Sourcepub fn with_background_color(self, color: Color) -> Self
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;Sourcepub fn set_link(&mut self, uri: impl Into<String>)
pub fn set_link(&mut self, uri: impl Into<String>)
Sets a hyperlink URI for this image. When set, clicking the image will open this URL in a PDF viewer.
Sourcepub fn with_link(self, uri: impl Into<String>) -> Self
pub fn with_link(self, uri: impl Into<String>) -> Self
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 viewerSourcepub fn resizing_page_with(self, fraction: f32) -> Self
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);Sourcepub fn resizing_page_height(self, fraction: f32) -> Self
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 Element for Image
impl Element for Image
Source§fn render(
&mut self,
_context: &Context,
area: Area<'_>,
_style: Style,
) -> Result<RenderResult, Error>
fn render( &mut self, _context: &Context, area: Area<'_>, _style: Style, ) -> Result<RenderResult, Error>
Source§fn framed(self, line_style: impl Into<LineStyle>) -> FramedElement<Self>where
Self: Sized,
fn framed(self, line_style: impl Into<LineStyle>) -> FramedElement<Self>where
Self: Sized,
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<E> IntoBoxedElement for Ewhere
E: Element + 'static,
impl<E> IntoBoxedElement for Ewhere
E: Element + 'static,
Source§fn into_boxed_element(self) -> Box<dyn Element>
fn into_boxed_element(self) -> Box<dyn Element>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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
impl<T> Pointable for T
§impl<U, T> ToOwnedObj<U> for Twhere
U: FromObjRef<T>,
impl<U, T> ToOwnedObj<U> for Twhere
U: FromObjRef<T>,
§fn to_owned_obj(&self, data: FontData<'_>) -> U
fn to_owned_obj(&self, data: FontData<'_>) -> U
T, using the provided data to resolve any offsets.