fschutt / printpdf

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

Use differents layer to put text #165

Closed Tienda-Electrofum closed 6 months ago

Tienda-Electrofum commented 11 months ago

I'm trying to insert text on different layers but I can only insert text on the first layer. When I try to insert text into other layers, the text does not appear. I am doing something wrong?

use printpdf::*;
use std::fs::File;
use std::io::BufWriter;

fn main() {
    let text = "Lorem ipsum";
    let text2 = "Lorem Layer 2";
    // To prevent empty documents, you must specify at least one page with one layer
    // You can later on add more pages with the add_page() function
    // You also have to specify the title of the PDF and the document creator
    let (doc, page_1, layer_1) =
        PdfDocument::new("printpdf page test", Mm(210.0), Mm(297.0), "Layer 1");

        let bold_font = doc.add_builtin_font(BuiltinFont::TimesBold).unwrap();

        let current_layer = doc.get_page(page_1).get_layer(layer_1); // This is the only layer that works for text
        let next_layer = doc.get_page(page_1).add_layer("Layer 2");

        let x = 10.0;
        let y = 285.0;

        /* current_layer.begin_text_section();

        current_layer.set_font(&bold_font, 20.0);
        current_layer.set_text_cursor(Mm(x), Mm(y));

        current_layer.write_text(text, &bold_font);
        current_layer.add_line_break();

        current_layer.end_text_section(); */

        next_layer.begin_text_section();
        next_layer.set_text_cursor(Mm(x), Mm(270.0));

        next_layer.write_text(text2, &bold_font); // This text not appear
        next_layer.add_line_break();
        next_layer.end_text_section();

    // If this is successful, you should see a PDF with two blank A4 pages
    doc.save(&mut BufWriter::new(File::create("test_pages.pdf").unwrap()))
        .unwrap();
}

If I uncomment the lines of the current_layer, text does appear, but only from the current_layer. The text I put in next_layer never appears no matter what I do

obreidenich commented 9 months ago

Apparently write_text() always needs set_font() to be set.

Alternatively you may use use_text() as an all-in-one solution as shown here. For your example: next_layer.use_text(text2, 20.0 , Mm(x), Mm(270.0), &bold_font);

Tienda-Electrofum commented 6 months ago

Thank you very much for your answer @obreidenich I have tried your suggestion and it works