Skip to main content

pdf_min/
image.rs

1use crate::BasicPdfWriter;
2use crate::page::Page;
3use format_bytes::write_bytes as wb;
4
5/// PDF image - byte data and attributes that describe how image is encoded.
6pub struct Image<'a> {
7    /// obj id
8    pub obj: usize,
9    /// Image data - size is width * height * (bits_per_component/8) * 3 (for RGB).
10    pub data: &'a [u8],
11    /// Width
12    pub width: usize,
13    /// Height
14    pub height: usize,
15    /// Bits per component, usually 8
16    pub bits_per_component: u8,
17    /// Color space, such as b"/DeviceGray", b"/DeviceRGB", b"/DeviceCMYK"
18    pub color_space: &'a [u8],
19    /// Any other attributes, e.g. b"/Filter/DCT" for a jpeg
20    pub other: &'a [u8],
21}
22
23impl<'a> Image<'a>
24{
25    /// Set the obj number, write the image attributes and data to the PDF.
26    pub fn init(&mut self, w: &mut BasicPdfWriter) {
27        self.obj = w.begin();
28        let _ = wb!(
29            &mut w.b,
30            b"<</Type/XObject/Subtype/Image/Width {}/Height {}/ColorSpace{}/BitsPerComponent {}/Length {}{}>>stream\n",
31            self.width, self.height, self.color_space, self.bits_per_component, self.data.len(), self.other
32        );
33        w.b.extend_from_slice(&self.data);
34        w.b.extend_from_slice(b"\nendstream");
35        w.end();
36    }
37
38    /// Draw image on page.
39    pub fn draw(&self, page: &mut Page, x: f32, y: f32, scale:f32)
40    {
41       let obj = self.obj;
42       let w = (self.width as f32) * scale;
43       let h = (self.height as f32) * scale;
44       page.xobjs.insert(obj);
45       let _ = wb!(&mut page.os, b"\nq {} 0 0 {} {} {} cm /X{} Do Q", w,h,x,y,obj);
46    }
47}