Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bookmark in Unicode #188

Open
strandenzee opened this issue Oct 23, 2024 · 1 comment
Open

Bookmark in Unicode #188

strandenzee opened this issue Oct 23, 2024 · 1 comment

Comments

@strandenzee
Copy link

strandenzee commented Oct 23, 2024

I am trying to add a bookmark in Unicode (Russian and Polish text in my case) but i only get some silly signs, not the letters i would like to have. Is there a way to use Unicode Bookmarks?

use printpdf::*;
use std::fs::File;
use std::io::{BufWriter, Seek};

fn main() {
    test_unicode_bookmark();
}

fn test_unicode_bookmark() {

    // Create a new PDF document
    let (doc, page1, layer1) = PdfDocument::new("PDF with Bookmarks", Mm(210.0), Mm(297.0), "Layer 1");

    // Create a new layer
    let layer = doc.get_page(page1).get_layer(layer1);

    // Add some text to the first page
    let font = doc.add_external_font(File::open("src/assets/fonts/RobotoMedium.ttf").unwrap()).unwrap();
    let hello = String::from("Здравствуйте");
    layer.use_text(&hello, 48.0, Mm(10.0), Mm(280.0), &font);

    // Add a bookmark with Unicode text
    let bookmark_title = "Unicode Bookmark: Здравствуйте"; // Example Unicode text
    doc.add_bookmark(bookmark_title, page1);

    // Save the document
    doc.save(&mut BufWriter::new(File::create("output.pdf").unwrap())).unwrap();
}

image

@fschutt
Copy link
Owner

fschutt commented Oct 23, 2024

I didn't write the bookmarks code but it's probably this line:

("Title", String(title.into(), Literal)),

Literal encoding means Windows-ANSI, it should be switched to Hexadecimal like this:

        let bytes = text
            .chars()
            .flat_map(|x| {
                let [b0, b1] = x.to_be_bytes();
                std::iter::once(b0).chain(std::iter::once(b1))
            })
            .collect::<Vec<u8>>();

        ("Title", String(bytes, Hexadecimal)), 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants