rust-pdf icon indicating copy to clipboard operation
rust-pdf copied to clipboard

Font colour rendering issue

Open v-nxe opened this issue 3 years ago • 1 comments

I'm trying to write a project to convert markdown to PDF without a requirement for chrome. Part of this may require highlighting code blocks. To do this I'm converting raw code into sections of coloured code (more specifically a Vec<Vec<(String, Option<Color>)>> with each inner vertor representing a single line). I have checked this section and ensured it works as intended. The problem comes when trying to write coloured text to the PDF file. A large majority of the colours (between 80% and 90%) aren't highlighted or are highlighted incorrectly (See here for the current worse case and here for the current best case). The worse case happens when I try to reset the colour after the first text is highlighted, and the best happens when I remove that. The code for both is below and is wrapped in a Pdf.render_page with c as the &mut Canvas

let mut w = document.height - 30.0;
let margin = 10.0;
let font_size = 11.0;
let style = BTMap::<&str, Color>::new()
let font_ref = c.get_font(BuiltinFont::Helvetica);
for (k, v) in style {
    c.text(|f| {
        f.set_fill_color(v.clone())?;
        f.set_font(&font_ref, font_size)?;
        f.pos(self.pdf_opts.page.margin.x, w)?;
        f.show(k)
    })?;
    c.text(|f| {
        // This line is uncommented for the best case
        // f.set_fill_color(Color::gray(0))?;
        f.set_font(&font_ref, font_size)?;
        f.pos(margin + 50.0, w)?;
        f.show(k)
    })?;
    c.text(|f| {
        f.set_font(&font_ref, font_size)?;
        f.pos(margin + 100.0, w)?;
        f.show(&*format!("{:?}", v))
    })?;
    w -= font_size + 2.0;
}

v-nxe avatar Jan 06 '23 12:01 v-nxe

Strange, I think that should work ... And stranger, your example PDF files does not seem to be created by this crate, as your files starts with %PDF-1.3 and this crate writes files with %PDF-1.7 and this crates writes raw streams, while your example files have flate encoded streams?

Maybe the example files are "filtered" somehow (maybe you opened and saved them through a PDF viewer)? Could you show the raw files created by the rust code?

kaj avatar Jan 09 '23 09:01 kaj