fschutt / printpdf

An easy-to-use library for writing PDF in Rust
https://docs.rs/printpdf/
MIT License
777 stars 95 forks source link

How can i end a pdf line before it overflows #161

Closed Necoo33 closed 7 months ago

Necoo33 commented 7 months ago

Hi, i'm a rust developer which started to figure out that crate new. And i've an issue about line endings.

I'm trying to take texts from a .txt file and put it on a .pdf file with some styling and modification. When i wrote a text that bigger than a pdf line it overflows to right. Here is my code:


   let mut file = File::open("./assets/input-1.txt").expect("File Not Found");

    let mut content = String::new();

    file.read_to_string(&mut content).expect("Unable To Read");

    let (doc, page1, layer1) = PdfDocument::new("sample-1 title", Mm(210.0), Mm(300.0), "Layer 1");

    let times_roman_font = doc.add_builtin_font(BuiltinFont::TimesRoman).expect("Failed To Add Font");

    let actual_layer = doc.get_page(page1).get_layer(layer1);

    let mut y_position = Mm(265.0); 

    for (index, value) in content.split("#*").into_iter().enumerate() {
        let add_new_paragraph = format!("{} \n\n", value);

        actual_layer.use_text(&add_new_paragraph, 10.0, Mm(10.0), y_position, &times_roman_font);

        y_position = Mm(265.0 - (index + 1) as f32 * 10.0);
    };

    doc.save(&mut BufWriter::new(File::create("output-1.pdf").unwrap())).unwrap();

So how can i prevent overflowing a text to right when it's bigger than a pdf line?

And also i need to know how to justify texts to the both left and right.

here is my input and output files for your inspection:

output-1.pdf input-1.txt

fschutt commented 7 months ago

You have to do text layouting, which isn't part of this crate intentionally - see https://github.com/fschutt/printpdf/issues/39#issuecomment-559118743