How do I centre image in the middle of page

⚓ Rust    📅 2026-03-27    👤 surdeus    👁️ 1      

surdeus

I have this code using printpdf: https://docs.rs/printpdf/0.9.1/printpdf/xobject/struct.XObjectTransform.html:

    // In the PDF, an image is an `XObject`, identified by a unique `ImageId`
    let image_xobject_id = doc.add_image(image);

    let page1_contents = vec![
        Op::UseXobject { 
            id: image_xobject_id.clone(), 
            transform: XObjectTransform::default() 
        }
    ];

    let page1 = PdfPage::new(Mm(10.0), Mm(250.0), page1_contents);
    let pdf_bytes: Vec<u8> = doc
        .with_pages(vec![page1])
        .save(&PdfSaveOptions::default());

However the image appears on the left nearly bottom hand side. I want it to appear in the centre. I know I can use translate_x and translate_y but I don't know how would I get the image's height and width and use that to centre it in the middle of the page, especially when the page uses mm vs px?

1 post - 1 participant

Read full topic

🏷️ Rust_feed