Debian Codegraph @

debian/missing-sources/lopdf/tests/unicode.rs

raw
1 use lopdf::content::{Content, Operation};
2 use lopdf::{dictionary, Document, Object, Stream, StringFormat};
3
4 #[test]
5 fn unicode_can_be_written_to_pdf_and_read() {
6 let mut doc = Document::new();
7
8 // literal corresponds to the chars:
9 // U+1F600
10 // U+1F527
11 // U+1F528
12 // which are encoded in font cmap with the following hex
13 // <005F>
14 // <0060>
15 // <0061>
16 // please mind that indicated BaseFont might not contain
17 // those unicode emojis in practice
18 let unicode_literal = "😀🔧🔨";
19 let literal_encoded_with_cmap = [0x00, 0x5F, 0x00, 0x60, 0x00, 0x61];
20
21 // majority of below code correspond to create document example
22 // we are just inserting an appropriate unicode text
23 // and Type0 font with approriate characters encoding
24 let pages_id = doc.new_object_id();
25
26 let cmap_stream_id = doc.add_object(Stream::new(
27 dictionary! {
28 "Length" => 437
29 },
30 b"/CIDInit /ProcSet findresource begin
31 12 dict begin
32 begincmap
33 /CIDSystemInfo
34 << /Registry (Adobe)
35 /Ordering (UCS)
36 /Supplement 0
37 >> def
38 /CMapName /Adobe-Identity-UCS def
39 /CMapType 2 def
40 1 begincodespacerange
41 <0000> <FFFF>
42 endcodespacerange
43 2 beginbfrange
44 <0000> <005E> <0020>
45 <005F> <0061> [<D83DDE00> <D83DDD27> <D83DDD28>]
46 endbfrange
47 1 beginbfchar
48 <3A51> <D840DC3E>
49 endbfchar
50 endcmap
51 CMapName currentdict /CMap defineresource pop
52 end
53 end"
54 .to_vec(),
55 ));
56
57 let font_id = doc.add_object(dictionary! {
58 "Type" => "Font",
59 "Subtype" => "Type0",
60 "BaseFont" => "Ryumin-Light",
61 "Encoding" => "Identity-H",
62 "ToUnicode" => Object::Reference(cmap_stream_id)
63 });
64
65 let resources_id = doc.add_object(dictionary! {
66 "Font" => dictionary! {
67 "F1" => font_id,
68 },
69 });
70
71 // Create content with the prepared emoji string encoded according to values in our font cmap
72 let content = Content {
73 operations: vec![
74 Operation::new("BT", vec![]),
75 Operation::new("Tf", vec!["F1".into(), 48.into()]),
76 Operation::new("Td", vec![100.into(), 600.into()]),
77 Operation::new(
78 "Tj",
79 vec![Object::String(
80 literal_encoded_with_cmap.to_vec(),
81 StringFormat::Hexadecimal,
82 )],
83 ),
84 Operation::new("ET", vec![]),
85 ],
86 };
87
88 let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
89
90 let page_id = doc.add_object(dictionary! {
91 "Type" => "Page",
92 "Parent" => pages_id,
93 "Contents" => content_id,
94 });
95
96 let pages = dictionary! {
97 "Type" => "Pages",
98 "Kids" => vec![page_id.into()],
99 "Count" => 1,
100 "Resources" => resources_id,
101 "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
102 };
103
104 // using insert() here, instead of add_object() since the id is already known.
105 doc.objects.insert(pages_id, Object::Dictionary(pages));
106
107 let catalog_id = doc.add_object(dictionary! {
108 "Type" => "Catalog",
109 "Pages" => pages_id,
110 });
111
112 doc.trailer.set("Root", catalog_id);
113 doc.compress();
114
115 let extracted_text = get_text_from_first_page(&doc);
116
117 assert_eq!(extracted_text.trim_end(), unicode_literal);
118 }
119
120 fn get_text_from_first_page(doc: &Document) -> String {
121 let mut pages = doc.get_pages();
122 let first_page = pages.first_entry().expect("Expected pages to be non empty");
123 let extracted_text = doc
124 .extract_text(&[*first_page.key()])
125 .expect("Expected to find text on the first page");
126 extracted_text
127 }
128
129 #[cfg(not(feature = "async"))]
130 #[test]
131 fn unicode_can_be_extracted_from_loaded_pdf() -> lopdf::Result<()> {
132 let doc = Document::load("assets/unicode.pdf")?;
133 let extracted_text = get_text_from_first_page(&doc);
134 // extract text can currently map a consecutive fragment of text
135 // to one divided into multiple lines, therefore we have to remove the
136 // new lines
137 assert_eq!(extracted_text.replace("\n", ""), "😀🔧🔨");
138 Ok(())
139 }
140
141 #[cfg(feature = "async")]
142 #[tokio::test]
143 async fn unicode_can_be_extracted_from_loaded_pdf() -> lopdf::Result<()> {
144 let doc = Document::load("assets/unicode.pdf").await?;
145 let extracted_text = get_text_from_first_page(&doc);
146 assert_eq!(extracted_text.replace("\n", ""), "😀🔧🔨");
147 Ok(())
148 }