fschutt / printpdf

A fully-featured PDF library for Rust, WASM-ready
https://fschutt.github.io/printpdf/
MIT License
829 stars 98 forks source link

Issue with PNG transparent background being black #178

Closed Degubi closed 4 months ago

Degubi commented 4 months ago

I have this small code creating a PDF and embedding a png image:

use std::{fs, fs::File};
use image_crate::codecs::png::PngDecoder;
use printpdf::*;

fn main() {
    fs::write("test.pdf", create_test_pdf());
}

fn create_test_pdf() -> Vec<u8> {
    let page_width = 297f32;
    let page_height = 210f32;
    let (doc, page1, layer1) = PdfDocument::new("Test PDF", Mm(page_width), Mm(page_height), "Layer 1");

    draw_image("trolley.png", 48f32, 48f32, page_height, &doc, &page1, &layer1);

    doc.save_to_bytes().unwrap()
}

fn draw_image(path: &str, x: f32, y: f32, page_height: f32, doc: &PdfDocumentReference, page: &PdfPageIndex, layer: &PdfLayerIndex) {
    let image = Image::try_from(PngDecoder::new(File::open(path).unwrap()).unwrap()).unwrap();
    let image_height = image.image.height.into_pt(300f32);

    println!("{:?}", image.image.color_space);

    image.add_to_layer(doc.get_page(*page).get_layer(*layer), ImageTransform {
        dpi: None,
        rotate: None,
        scale_x: None,
        scale_y: None,
        translate_x: Some(Mm(x)),
        translate_y: Some(Mm(page_height - y - Mm::from(image_height).0))
    });
}

After opening the PDF file in Chrome it looks like this:

image

My issue is: The transparency gets lost and instead it has a full black background instead. Is this a bug or am I doing something wrong? (I have a println in draw_image printing the color_space of the image, it prints Rgb, not Rgba) Are there any workarounds for this?

printpdf from Cargo.toml:

printpdf = { version = "=0.7.0", default-features = false, features = [ "embedded_images" ] }

Thank you in advance!

(I attached the image in a .zip file, I don't know if Github compresses/modifies uploaded images, so I wrapped it in a zip)

trolley.zip

Degubi commented 4 months ago

This is interesting I was like 'I can check this out, this can't be that difficult to fix' Went home from work, and now I can't reproduce the black background on this computer...

Edit: So, the black background disappeared because it seems this was already fixed, but the fix was not pushed to crates.io In this case I'm gonna wait for a new release. Sorry for not checking out beforehand! Also, thank you for your great work! Have a nice day.

Edit2: Was fixed by #158 and #171

fschutt commented 4 months ago

Ok, I'll see if I can do a new release.