Debian Codegraph @

podofo/test/unit/PainterTest.cpp

raw
1 // SPDX-FileCopyrightText: 2011 Dominik Seichter <[email protected]>
2 // SPDX-FileCopyrightText: 2021 Francesco Pretto <[email protected]>
3 // SPDX-License-Identifier: MIT-0
4
5 #include <PdfTest.h>
6
7 using namespace std;
8 using namespace PoDoFo;
9
10 namespace
11 {
12 class FakeCanvas : public PdfCanvas
13 {
14 public:
15 FakeCanvas()
16 : m_Resources(m_doc.GetPages().CreatePage().GetResources())
17 {
18 }
19
20 public:
21 PdfObjectStream& GetOrCreateContentsStream(PdfStreamAppendFlags flags) override
22 {
23 (void)flags;
24 return m_resourceObj.GetOrCreateStream();
25 }
26
27 PdfObjectStream& ResetContentsStream() override
28 {
29 PODOFO_RAISE_ERROR(PdfErrorCode::InternalLogic);
30 }
31
32 PdfResources& GetOrCreateResources() override
33 {
34 // NOTE: Return a dummy resource
35 return m_Resources;
36 }
37
38 Corners GetRectRaw() const override
39 {
40 PODOFO_RAISE_ERROR(PdfErrorCode::InternalLogic);
41 }
42
43 void CopyContentsTo(OutputStream& stream) const override
44 {
45 auto objStream = m_resourceObj.GetStream();
46 if (objStream == nullptr)
47 return;
48
49 objStream->CopyTo(stream);
50 }
51
52 bool TryGetRotationRadians(double& teta) const override
53 {
54 teta = 0;
55 return false;
56 }
57
58 protected:
59 PdfObject* getContentsObject() override
60 {
61 PODOFO_RAISE_ERROR(PdfErrorCode::InternalLogic);
62 }
63 PdfResources* getResources() override
64 {
65 PODOFO_RAISE_ERROR(PdfErrorCode::InternalLogic);
66 }
67 PdfDictionaryElement& getElement() override
68 {
69 PODOFO_RAISE_ERROR(PdfErrorCode::InternalLogic);
70 }
71
72 private:
73 PdfObject m_resourceObj;
74 PdfMemDocument m_doc;
75 PdfResources& m_Resources;
76 };
77 }
78
79 static string getContents(const PdfPage& page);
80 static void compareStreamContent(PdfObjectStream& stream, const string_view& expected);
81 static void drawSample(PdfPainter& painter);
82 static void drawSquareWithCross(PdfPainter& painter, double x, double y);
83
84 auto s_expected = R"(q
85 120 500 m
86 120 511.045695 111.045695 520 100 520 c
87 88.954305 520 80 511.045695 80 500 c
88 80 488.954305 88.954305 480 100 480 c
89 111.045695 480 120 488.954305 120 500 c
90 h
91 f
92 Q
93 )"sv;
94
95 TEST_CASE("TestPainter1")
96 {
97 FakeCanvas canvas;
98 PdfPainter painter;
99 painter.SetCanvas(canvas);
100 drawSample(painter);
101 painter.FinishDrawing();
102 auto copy = canvas.GetContentsCopy();
103 REQUIRE(copy == s_expected);
104 }
105
106 TEST_CASE("TestPainter2")
107 {
108 PdfMemDocument doc;
109 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
110 PdfPainter painter;
111 painter.SetCanvas(page);
112 drawSample(painter);
113 painter.FinishDrawing();
114 doc.Save(TestUtils::GetTestOutputFilePath("TestPainter2.pdf"));
115
116 auto out = getContents(page);
117 REQUIRE(out == s_expected);
118 }
119
120 TEST_CASE("TestPainter3")
121 {
122 PdfMemDocument doc;
123 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
124 PdfPainter painter;
125 painter.SetCanvas(page);
126 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::TimesRoman);
127 painter.TextState.SetFont(font, 15);
128 painter.DrawText("Hello world", 100, 500, PdfDrawTextStyle::StrikeThrough | PdfDrawTextStyle::Underline);
129 painter.FinishDrawing();
130 doc.Save(TestUtils::GetTestOutputFilePath("TestPainter3.pdf"));
131
132 #ifdef PODOFO_ENABLE_AFDKO
133 auto expectedContent = R"(q
134 q
135 BT
136 /Ft0 15 Tf
137 0.75 w
138 100 500 Td
139 <0203040405010605070408> Tj
140 ET
141 100 498.74 m
142 172.075 498.74 l
143 S
144 100 503.075 m
145 172.075 503.075 l
146 S
147 Q
148 Q
149 )"sv;
150 auto out = getContents(page);
151 REQUIRE(out == expectedContent);
152
153 auto expectedW = R"([ 0[ 1000 250 722 444 278 500 722 333 500]]
154 )"sv;
155 auto& wObj = font.GetDescendantFontObject().GetDictionary().MustFindKey("W");
156 REQUIRE(wObj.ToString() == expectedW);
157
158 auto expectedToUnicode = R"(/CIDInit /ProcSet findresource begin
159 12 dict begin
160 begincmap
161 /CIDSystemInfo <<
162 /Registry (Adobe)
163 /Ordering (UCS)
164 /Supplement 0
165 >> def
166 /CMapName /Adobe-Identity-UCS def
167 /CMapType 2 def
168 1 begincodespacerange
169 <00><7F>
170 endcodespacerange
171 8 beginbfchar
172 <01> <0020>
173 <02> <0048>
174 <03> <0065>
175 <04> <006C>
176 <05> <006F>
177 <06> <0077>
178 <07> <0072>
179 <08> <0064>
180 endbfchar
181 endcmap
182 CMapName currentdict /CMap defineresource pop
183 end
184 end)";
185 auto& toUnicodeObj = font.GetDictionary().MustFindKey("ToUnicode");
186 REQUIRE(toUnicodeObj.MustGetStream().GetCopy() == expectedToUnicode);
187
188 auto expectedEncoding = R"(/CIDInit /ProcSet findresource begin
189 12 dict begin
190 begincmap
191 /CIDSystemInfo <<
192 /Registry (PoDoFo)
193 /Ordering (BAAAAA+Times-Roman-subset)
194 /Supplement 0
195 >> def
196 /CMapName /CMap-BAAAAA+Times-Roman-subset def
197 /CMapType 1 def
198 1 begincodespacerange
199 <00><7F>
200 endcodespacerange
201 8 begincidchar
202 <01> 1
203 <02> 2
204 <03> 3
205 <04> 4
206 <05> 5
207 <06> 6
208 <07> 7
209 <08> 8
210 endcidchar
211 endcmap
212 CMapName currentdict /CMap defineresource pop
213 end
214 end)";
215 auto& encodingObj = font.GetDictionary().MustFindKey("Encoding");
216 REQUIRE(encodingObj.MustGetStream().GetCopy() == expectedEncoding);
217
218 #else PODOFO_ENABLE_AFDKO
219 auto expectedContent = R"(q
220 q
221 BT
222 /Ft0 15 Tf
223 0.75 w
224 100 500 Td
225 <0001020203040503060207> Tj
226 ET
227 100 498.74 m
228 172.075 498.74 l
229 S
230 100 503.075 m
231 172.075 503.075 l
232 S
233 Q
234 Q
235 )"sv;
236 auto out = getContents(page);
237 REQUIRE(out == expectedContent);
238
239 auto expectedW = R"([ 0[ 1000] 41[ 722] 70[ 444] 77[ 278] 80[ 500] 1[ 250] 88[ 722] 83[ 333] 69[ 500]]
240 )"sv;
241 auto& wObj = font.GetDescendantFontObject().GetDictionary().MustFindKey("W");
242 REQUIRE(wObj.ToString() == expectedW);
243
244 auto expectedToUnicode = R"(/CIDInit /ProcSet findresource begin
245 12 dict begin
246 begincmap
247 /CIDSystemInfo <<
248 /Registry (Adobe)
249 /Ordering (UCS)
250 /Supplement 0
251 >> def
252 /CMapName /Adobe-Identity-UCS def
253 /CMapType 2 def
254 1 begincodespacerange
255 <00><7F>
256 endcodespacerange
257 8 beginbfchar
258 <00> <0048>
259 <01> <0065>
260 <02> <006C>
261 <03> <006F>
262 <04> <0020>
263 <05> <0077>
264 <06> <0072>
265 <07> <0064>
266 endbfchar
267 endcmap
268 CMapName currentdict /CMap defineresource pop
269 end
270 end)";
271
272 auto& toUnicodeObj = font.GetDictionary().MustFindKey("ToUnicode");
273 REQUIRE(toUnicodeObj.MustGetStream().GetCopy() == expectedToUnicode);
274
275 auto expectedEncoding = R"(/CIDInit /ProcSet findresource begin
276 12 dict begin
277 begincmap
278 /CIDSystemInfo <<
279 /Registry (PoDoFo)
280 /Ordering (Times-Roman)
281 /Supplement 0
282 >> def
283 /CMapName /CMap-Times-Roman def
284 /CMapType 1 def
285 1 begincodespacerange
286 <00><7F>
287 endcodespacerange
288 8 begincidchar
289 <00> 41
290 <01> 70
291 <02> 77
292 <03> 80
293 <04> 1
294 <05> 88
295 <06> 83
296 <07> 69
297 endcidchar
298 endcmap
299 CMapName currentdict /CMap defineresource pop
300 end
301 end)";
302
303 auto& encodingObj = font.GetDictionary().MustFindKey("Encoding");
304 REQUIRE(encodingObj.MustGetStream().GetCopy() == expectedEncoding);
305 #endif // PODOFO_ENABLE_AFDKO
306 }
307
308 TEST_CASE("TestPainter4")
309 {
310 PdfMemDocument doc;
311 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
312
313 PdfFontCreateParams params;
314 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
315 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
316
317 PdfPainter painter;
318 auto& operators = static_cast<PdfContentStreamOperators&>(painter);
319 painter.SetCanvas(page);
320 painter.TextState.SetFont(font, 15);
321 painter.TextObject.Begin();
322 painter.TextObject.MoveTo(100, 500);
323 painter.TextObject.AddText("Test1");
324 // Some low level operations
325 operators.TJ_Operator_Begin();
326 operators.TJ_Operator_Glyphs("_W", false);
327 operators.TJ_Operator_Delta(-500);
328 operators.TJ_Operator_Glyphs("orld", false);
329 operators.TJ_Operator_End();
330 painter.TextObject.End();
331 painter.DrawText("Test2", 100, 600, PdfDrawTextStyle::StrikeThrough);
332
333 PdfPainterPath path;
334 path.MoveTo(20, 20);
335 path.AddArcTo(150, 20, 150, 70, 50);
336 path.AddLineTo(150, 120);
337 path.AddArc(200, 120, 50, numbers::pi, numbers::pi/8, true);
338
339 auto currPoint1 = path.GetCurrentPoint();
340
341 PdfPainterPath path2;
342 path2.MoveTo(250, 120);
343 path2.AddLineTo(250, 80);
344 path.AddPath(path2, true);
345
346 auto currPoint2 = path.GetCurrentPoint();
347 painter.DrawPath(path, PdfPathDrawMode::Stroke);
348 path.Reset();
349 path.MoveTo(40, 40);
350 path.AddLineTo(100, 40);
351 path.AddLineTo(70, 80);
352 path.AddLineTo(40, 40);
353 path.AddCircle(200, 300, 60);
354 painter.DrawPath(path, PdfPathDrawMode::Fill);
355
356 drawSquareWithCross(painter, 100, 20);
357 drawSquareWithCross(painter, 100, 70);
358 drawSquareWithCross(painter, 150, 70);
359 drawSquareWithCross(painter, currPoint1.X, currPoint1.Y);
360 drawSquareWithCross(painter, currPoint2.X, currPoint2.Y);
361
362 painter.FinishDrawing();
363 doc.Save(TestUtils::GetTestOutputFilePath("TestPainter4.pdf"));
364
365 auto expected = R"(q
366 BT
367 /Ft0 15 Tf
368 100 500 Td
369 (Test1) Tj
370 [ (_W) -500 (orld) ] TJ
371
372 ET
373 q
374 BT
375 0.75 w
376 100 600 Td
377 (Test2) Tj
378 ET
379 100 603.885 m
380 137.515 603.885 l
381 S
382 Q
383 20 20 m
384 100 20 l
385 127.614237 20 150 42.385763 150 70 c
386 150 120 l
387 150 120 l
388 150 143.853715 166.850112 164.385635 190.245484 169.039264 c
389 213.640856 173.692893 237.065555 161.17213 246.193977 139.134172 c
390 250 120 l
391 250 120 m
392 250 80 l
393 S
394 40 40 m
395 100 40 l
396 70 80 l
397 40 40 l
398 260 300 m
399 260 333.137085 233.137085 360 200 360 c
400 166.862915 360 140 333.137085 140 300 c
401 140 266.862915 166.862915 240 200 240 c
402 233.137085 240 260 266.862915 260 300 c
403 h
404 f
405 q
406 0.6 w
407 97 17 6 6 re
408 S
409 0 w
410 100 17 m
411 100 23 l
412 S
413 97 20 m
414 103 20 l
415 S
416 Q
417 q
418 0.6 w
419 97 67 6 6 re
420 S
421 0 w
422 100 67 m
423 100 73 l
424 S
425 97 70 m
426 103 70 l
427 S
428 Q
429 q
430 0.6 w
431 147 67 6 6 re
432 S
433 0 w
434 150 67 m
435 150 73 l
436 S
437 147 70 m
438 153 70 l
439 S
440 Q
441 q
442 0.6 w
443 243.193977 136.134172 6 6 re
444 S
445 0 w
446 246.193977 136.134172 m
447 246.193977 142.134172 l
448 S
449 243.193977 139.134172 m
450 249.193977 139.134172 l
451 S
452 Q
453 q
454 0.6 w
455 247 77 6 6 re
456 S
457 0 w
458 250 77 m
459 250 83 l
460 S
461 247 80 m
462 253 80 l
463 S
464 Q
465 Q
466 )";
467 auto out = getContents(page);
468 REQUIRE(out == expected);
469 }
470
471 TEST_CASE("TestPainter5")
472 {
473 PdfMemDocument doc;
474 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
475
476 PdfFontCreateParams params;
477 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
478 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
479
480 PdfPainter painter;
481 painter.SetCanvas(page);
482 painter.TextState.SetFont(font, 15);
483 painter.DrawTextMultiLine("Hello\nWorld", 100, 600, 100, 40);
484 painter.DrawRectangle(Rect(100, 600, 100, 40));
485
486 painter.FinishDrawing();
487 doc.Save(TestUtils::GetTestOutputFilePath("TestPainter5.pdf"));
488
489 auto expected = R"(q
490 q
491 100 600 100 40 re
492 W
493 n
494 BT
495 /Ft0 15 Tf
496 100 629.08 Td
497 (Hello) Tj
498 0 -14.07 Td
499 (World) Tj
500 ET
501 Q
502 100 600 100 40 re
503 S
504 Q
505 )";
506
507 auto out = getContents(page);
508 REQUIRE(out == expected);
509 }
510
511 TEST_CASE("TestPainter6")
512 {
513 PdfMemDocument doc;
514 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
515
516 PdfFontCreateParams params;
517 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
518
519 PdfPainter painter;
520 painter.SetCanvas(page);
521 REQUIRE(painter.GetStateStack().Current->CurrentPoint == nullptr);
522 PdfPainterPath path;
523 path.AddRectangle(Rect(10,10, 100, 50));
524 painter.Save();
525 painter.DrawPath(path);
526 REQUIRE(path.GetCurrentPoint() == Vector2(10, 10));
527 REQUIRE(painter.GetStateStack().Current->CurrentPoint == nullptr);
528 painter.Save();
529 auto& operators = static_cast<PdfContentStreamOperators&>(painter);
530 operators.n_Operator();
531 REQUIRE(painter.GetStateStack().Current->CurrentPoint == nullptr);
532 painter.FinishDrawing();
533 doc.Save(TestUtils::GetTestOutputFilePath("TestPainter6.pdf"));
534
535 auto expected = R"(q
536 q
537 10 10 100 50 re
538 S
539 q
540 n
541 Q
542 )";
543
544 auto out = getContents(page);
545 REQUIRE(out == expected);
546 }
547
548 TEST_CASE("TestAppend")
549 {
550 string_view example = "BT (Hello) Tj ET";
551
552 PdfMemDocument doc;
553 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
554
555 auto& contents = page.GetOrCreateContents();
556 auto& stream = contents.CreateStreamForAppending();
557 stream.SetData(example);
558
559 compareStreamContent(stream, example);
560
561 PdfPainter painter;
562 painter.SetCanvas(page);
563 painter.GraphicsState.SetNonStrokingColor(PdfColor(1.0, 1.0, 1.0));
564 painter.FinishDrawing();
565
566 auto out = getContents(page);
567 REQUIRE(out == "q\nBT (Hello) Tj ET\nQ\nq\n1 1 1 rg\nQ\n");
568 }
569
570 TEST_CASE("TestRotate")
571 {
572 unordered_map<int, Matrix> matrices = {
573 { 90, Matrix(6.1232339957367660e-17, 1, -1, 6.1232339957367660e-17, 9.9999999999999982, 0) },
574 { 270, Matrix(-1.8369701987210297e-16, -1, 1, -1.8369701987210297e-16, 0, 20.000000000000004) },
575 };
576
577 auto test = [&](int angle)
578 {
579 PdfMemDocument doc;
580 doc.Load(TestUtils::GetTestInputFilePath(utls::Format("blank-rotated-{}.pdf", angle)));
581 auto& page = doc.GetPages().GetPageAt(0);
582 page.SetRect(Rect(0, 0, 5, 7));
583
584 auto& signature = page.CreateField<PdfSignature>("Test", Rect(2, 1, 2, 1));
585 auto xobj = doc.CreateXObjectForm(Rect(0, 0, 20, 10));
586 PdfPainter painter;
587 painter.SetCanvas(*xobj);
588 PdfPainterPath path;
589 path.MoveTo(1, 1);
590 path.AddLineTo(19, 1);
591 path.AddLineTo(10, 9);
592 path.Close();
593 painter.DrawPath(path, PdfPathDrawMode::Fill);
594 painter.FinishDrawing();
595 signature.MustGetWidget().SetAppearanceStream(*xobj);
596 auto apObj = signature.MustGetWidget().GetAppearanceStream();
597 unique_ptr<PdfXObjectForm> form;
598 (void)PdfXObject::TryCreateFromObject(*apObj, form);
599 REQUIRE(form->GetMatrix() == matrices[angle]);
600 doc.Save(TestUtils::GetTestOutputFilePath(utls::Format("Rotated-{}.pdf", angle)));
601 };
602
603 test(90);
604 test(270);
605 }
606
607 // Test coming from https://github.com/podofo/podofo/issues/137
608 TEST_CASE("BigDynamicCMAPTest")
609 {
610 string_view textOver255 = "12345糟姨集鞋南槍痕痰林托入笑為潮立碰慘紡命窯舒喬檔脊吸渣誘餓躁強瓣倚扣拼襯裙凈錄釀薯憂擇十肅亭宰都愉冬乃考摟償老居題釣盯侵臣騾購標搬輛映納銷蜂宋頭號鄭藝駛斥鏟遵饑絨挨草保示她房礙宜扶涼困供探濫裁鴨膏橫坦傍愧蜓山儀辜略機評疑寸浩韻挪墻含帆由化里肌目淹誤匹枕浸有協斯名哥其香響逼裂油館慰七狹置露河樓弊增熱懂劇難盞拘罵撇芽胡慧關準補必舌遼晴奏愛江掏疲番走芬秩撤搭饅槐伸填灣蝦載簾哄寫急病攤田惕次泡捏糧附刷李鉆解阿違嫁天塌句善訊夠衰唇險學欠堆弟貪爆徐太孤鎮膛婆褲傷謹憶鵝踢贈擔仗膀挽兄扔基窩幕裹血暴米政覆柴力豎悼劫肥書翁屑";
611
612 auto outputFile = TestUtils::GetTestOutputFilePath("BigDynamicCMAPTest.pdf");
613 {
614 PdfMemDocument document;
615
616 auto& fontManager = document.GetFonts();
617 auto metrics = PdfFontMetrics::Create(TestUtils::GetTestInputFilePath("Fonts", "NotoSansTC-Regular.ttf"));
618 auto& font = fontManager.GetOrCreateFont(std::move(metrics));
619
620 // Draw a XObjectForm
621 unique_ptr<PdfXObjectForm> xObjectPtr = document.CreateXObjectForm(Rect(0, 0, 720, 1280));
622 PdfXObjectForm* xObject = xObjectPtr.get();
623
624 {
625 PdfPainter painter;
626 painter.SetCanvas(*xObject);
627
628 painter.GraphicsState.SetNonStrokingColor(PdfColor(0, 0, 0));
629 painter.GraphicsState.SetStrokingColor(PdfColor(0, 0, 0));
630
631 painter.TextState.SetFont(font, 12);
632
633 painter.DrawTextMultiLine(textOver255, 0, 0, 720, 1280);
634
635 painter.FinishDrawing();
636 }
637
638 // Draw XObjectForm to Page
639 auto& pages = document.GetPages();
640 auto& page = pages.CreatePage(Rect(0, 0, 720, 1280));
641
642 {
643 PdfPainter painter;
644 painter.SetCanvas(page);
645 painter.DrawXObject(*xObject, 0, 0, 1.0, 1.0);
646
647 painter.FinishDrawing();
648 }
649
650 document.Save(outputFile);
651 }
652
653 {
654 PdfMemDocument document;
655 document.Load(outputFile);
656 auto& page = document.GetPages().GetPageAt(0);
657 vector<PdfTextEntry> entries;
658 page.ExtractTextTo(entries);
659 REQUIRE(entries.size() == 5);
660 REQUIRE(entries[0].Text == "12345糟姨集鞋南槍痕痰林托入笑為潮立碰慘紡命窯舒喬檔脊吸渣誘餓躁強瓣倚扣拼襯裙凈錄釀薯憂擇十肅亭宰都愉冬乃考摟償老居題釣");
661 REQUIRE(entries[1].Text == "盯侵臣騾購標搬輛映納銷蜂宋頭號鄭藝駛斥鏟遵饑絨挨草保示她房礙宜扶涼困供探濫裁鴨膏橫坦傍愧蜓山儀辜略機評疑寸浩韻挪墻含帆由");
662 REQUIRE(entries[2].Text == "化里肌目淹誤匹枕浸有協斯名哥其香響逼裂油館慰七狹置露河樓弊增熱懂劇難盞拘罵撇芽胡慧關準補必舌遼晴奏愛江掏疲番走芬秩撤搭饅");
663 REQUIRE(entries[3].Text == "槐伸填灣蝦載簾哄寫急病攤田惕次泡捏糧附刷李鉆解阿違嫁天塌句善訊夠衰唇險學欠堆弟貪爆徐太孤鎮膛婆褲傷謹憶鵝踢贈擔仗膀挽兄扔");
664 REQUIRE(entries[4].Text == "基窩幕裹血暴米政覆柴力豎悼劫肥書翁屑");
665 }
666 }
667
668 TEST_CASE("TestDrawTextMultipleTimes")
669 {
670 PdfMemDocument document;
671 auto font = document.GetFonts().SearchFont("Arial");
672 auto& page = document.GetPages().CreatePage(PoDoFo::PdfPageSize::A4);
673 for (int i = 0; i < 3; i++)
674 {
675 PdfPainter painter;
676 painter.SetCanvas(page);
677 painter.TextState.SetFont(*font, 10);
678 painter.DrawText("M", 0, 0);
679 painter.FinishDrawing();
680 }
681
682 PdfContent data;
683 PdfContentStreamReader reader(page);
684 while (reader.TryReadNext(data))
685 REQUIRE((!data.HasErrors() && !data.HasWarnings()));
686 }
687
688 // Helper: count non-overlapping occurrences of a substring
689 static size_t countOccurrences(const string& haystack, const string& needle)
690 {
691 size_t count = 0;
692 size_t pos = 0;
693 while ((pos = haystack.find(needle, pos)) != string::npos)
694 {
695 count++;
696 pos += needle.length();
697 }
698 return count;
699 }
700
701 // DrawText with unencodable characters must throw without orphaning BT/q
702 // in the stream. Before the fix, ConvertToEncoded() was called after BT was
703 // already written, leaving the content stream permanently corrupted.
704 TEST_CASE("DrawTextExceptionSafety_StreamClean")
705 {
706 PdfMemDocument doc;
707 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
708
709 PdfFontCreateParams params;
710 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
711 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
712
713 PdfPainter painter;
714 painter.SetCanvas(page);
715 painter.TextState.SetFont(font, 12);
716
717 // CJK characters are outside WinAnsi — triggers PdfErrorCode::InvalidFontData
718 ASSERT_THROW_WITH_ERROR_CODE(
719 painter.DrawText("Hello \xe4\xb8\x96\xe7\x95\x8c", 100, 500),
720 PdfErrorCode::InvalidFontData);
721
722 painter.FinishDrawing();
723 auto out = getContents(page);
724
725 // Stream must be clean: only the FinishDrawing q/Q wrapper, no orphan BT or inner q
726 REQUIRE(out == "q\nQ\n"sv);
727 }
728
729 // After a failed DrawText, a subsequent valid DrawText must produce a well-formed
730 // content stream. Before the fix, the orphaned BT from the first call would nest
731 // inside the second call's BT/ET block, producing invalid PDF.
732 TEST_CASE("DrawTextExceptionSafety_SubsequentDrawSucceeds")
733 {
734 PdfMemDocument doc;
735 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
736
737 PdfFontCreateParams params;
738 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
739 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
740
741 PdfPainter painter;
742 painter.SetCanvas(page);
743 painter.TextState.SetFont(font, 12);
744
745 try
746 {
747 painter.DrawText("Hello \xe4\xb8\x96\xe7\x95\x8c", 100, 500);
748 }
749 catch (const PdfError&) { }
750
751 REQUIRE_NOTHROW(painter.DrawText("Hello", 100, 500));
752 painter.FinishDrawing();
753 auto out = getContents(page);
754
755 // Every BT must have a matching ET — no orphans
756 REQUIRE(countOccurrences(out, "BT") == countOccurrences(out, "ET"));
757 REQUIRE(countOccurrences(out, "BT") == 1);
758 }
759
760 // DrawTextAligned with unencodable characters must not corrupt the stream
761 TEST_CASE("DrawTextAlignedExceptionSafety_StreamClean")
762 {
763 PdfMemDocument doc;
764 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
765
766 PdfFontCreateParams params;
767 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
768 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
769
770 PdfPainter painter;
771 painter.SetCanvas(page);
772 painter.TextState.SetFont(font, 12);
773
774 ASSERT_THROW_WITH_ERROR_CODE(
775 painter.DrawTextAligned("Hello \xe4\xb8\x96\xe7\x95\x8c", 100, 500, 200,
776 PdfHorizontalAlignment::Left),
777 PdfErrorCode::InvalidFontData);
778
779 painter.FinishDrawing();
780 auto out = getContents(page);
781 REQUIRE(out == "q\nQ\n"sv);
782 }
783
784 // DrawTextMultiLine with unencodable characters must not corrupt the stream
785 TEST_CASE("DrawTextMultiLineExceptionSafety_StreamClean")
786 {
787 PdfMemDocument doc;
788 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
789
790 PdfFontCreateParams params;
791 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
792 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
793
794 PdfPainter painter;
795 painter.SetCanvas(page);
796 painter.TextState.SetFont(font, 12);
797
798 ASSERT_THROW_WITH_ERROR_CODE(
799 painter.DrawTextMultiLine("Hello \xe4\xb8\x96\xe7\x95\x8c", 100, 500, 200, 100),
800 PdfErrorCode::InvalidFontData);
801
802 painter.FinishDrawing();
803 auto out = getContents(page);
804 REQUIRE(out == "q\nQ\n"sv);
805 }
806
807 // TextObject.AddText with unencodable characters must not write partial operators
808 // to the stream. The BT block remains open (user-managed), and a subsequent valid
809 // AddText must succeed.
810 TEST_CASE("TextObjectAddTextExceptionSafety_Usable")
811 {
812 PdfMemDocument doc;
813 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
814
815 PdfFontCreateParams params;
816 params.Encoding = PdfEncoding(PdfEncodingMapFactory::GetWinAnsiEncodingInstancePtr());
817 auto& font = doc.GetFonts().GetStandard14Font(PdfStandard14FontType::Helvetica, params);
818
819 PdfPainter painter;
820 painter.SetCanvas(page);
821 painter.TextState.SetFont(font, 12);
822 painter.TextObject.Begin();
823 painter.TextObject.MoveTo(100, 500);
824
825 ASSERT_THROW_WITH_ERROR_CODE(
826 painter.TextObject.AddText("Hello \xe4\xb8\x96\xe7\x95\x8c"),
827 PdfErrorCode::InvalidFontData);
828
829 // After the throw, the BT is still open — user must call End() to close it.
830 // A subsequent valid AddText should succeed without corrupting the stream.
831 REQUIRE_NOTHROW(painter.TextObject.AddText("Hello"));
832 painter.TextObject.End();
833 painter.FinishDrawing();
834 auto out = getContents(page);
835
836 REQUIRE(countOccurrences(out, "BT") == countOccurrences(out, "ET"));
837 REQUIRE(out.find("Hello") != string::npos);
838 }
839
840 static void drawSample(PdfPainter& painter)
841 {
842 painter.DrawCircle(100, 500, 20, PdfPathDrawMode::Fill);
843 }
844
845 void compareStreamContent(PdfObjectStream& stream, const string_view& expected)
846 {
847 charbuff buffer;
848 stream.CopyTo(buffer);
849 REQUIRE(buffer == expected);
850 }
851
852 string getContents(const PdfPage& page)
853 {
854 PdfCanvasInputDevice input(page);
855 string ret;
856 StringStreamDevice output(ret);
857 input.CopyTo(output);
858 return ret;
859 }
860
861 void drawSquareWithCross(PdfPainter& painter, double x, double y)
862 {
863 painter.Save();
864 const double SquareSize = 6;
865 painter.GraphicsState.SetLineWidth(0.6);
866 painter.DrawRectangle(x - SquareSize / 2, y - SquareSize / 2, SquareSize, SquareSize);
867
868 painter.GraphicsState.SetLineWidth(0);
869 painter.DrawLine(x, y - SquareSize / 2, x, y + SquareSize / 2);
870 painter.DrawLine(x - SquareSize / 2, y, x + SquareSize / 2, y);
871 painter.Restore();
872 }