You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

57 lines
1.9 KiB

use printpdf::*;
use std::path::Path;
pub fn imageToPdf(path: String) -> Result<String, String> {
let mut doc = PdfDocument::new("image_to_pdf");
let image_bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
let image = RawImage::decode_from_bytes(&image_bytes, &mut Vec::new()).unwrap();
let mut ops = Vec::new();
// In the PDF, an image is an `XObject`, identified by a unique `ImageId`
let image_xobject_id = doc.add_image(&image);
// Calculate image size in points (1 point = 1/72 inch)
// let dpi = 300.0;
// let output_width= 105.0; // A6 width in mm
// let output_height = 148.0; // A6 height in mm
// let mm_to_pt = 1.0 / 25.4; // Conversion factor
// let width_pt = output_width * mm_to_pt * dpi / image.width as f64;
// let height_pt = output_height * mm_to_pt * dpi / image.height as f64;
// println!("Image size in points: {}x{}", width_pt, height_pt);
// Place the image at (0,0) with the calculated size
ops.push(Op::UseXobject {
id: image_xobject_id.clone(),
transform: XObjectTransform {
translate_x: Some(Pt(0.0)),
translate_y: Some(Pt(0.0)),
scale_x: Some(1.0),
scale_y: Some(1.0),
dpi: Some(300.0),
..Default::default()
},
});
let page1 = PdfPage::new(Mm(105.0), Mm(148.0), ops);
let pdf_bytes: Vec<u8> = doc
.with_pages(vec![page1])
.save(&PdfSaveOptions::default(), &mut Vec::new());
let pdf_path = Path::new(&path).with_extension("pdf");
match std::fs::write(&pdf_path, pdf_bytes) {
Ok(_) => {
let abs_path = std::fs::canonicalize(&pdf_path)
.map(|p| p.display().to_string())
.unwrap_or_else(|_| pdf_path.display().to_string());
println!("PDF written successfully to {}", abs_path);
Ok(abs_path)
},
Err(e) => Err(format!("Failed to write PDF: {}", e)),
}
}