Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
pdfium_test.cc
Go to the documentation of this file.
1// Copyright 2010 The PDFium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <locale.h>
6#include <stddef.h>
7#include <stdint.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include <algorithm>
13#include <functional>
14#include <iterator>
15#include <map>
16#include <memory>
17#include <optional>
18#include <sstream>
19#include <string>
20#include <vector>
21
22#if defined(PDF_ENABLE_SKIA) && !defined(PDF_USE_SKIA)
23#define PDF_USE_SKIA
24#endif
25
26#include "core/fxcrt/check_op.h"
27#include "core/fxcrt/compiler_specific.h"
28#include "core/fxcrt/span.h"
29#include "public/cpp/fpdf_scopers.h"
30#include "public/fpdf_annot.h"
31#include "public/fpdf_attachment.h"
32#include "public/fpdf_dataavail.h"
33#include "public/fpdf_edit.h"
34#include "public/fpdf_ext.h"
35#include "public/fpdf_formfill.h"
36#include "public/fpdf_progressive.h"
37#include "public/fpdf_structtree.h"
38#include "public/fpdf_text.h"
39#include "public/fpdfview.h"
40#include "testing/command_line_helpers.h"
41#include "testing/font_renamer.h"
42#include "testing/fx_string_testhelpers.h"
43#include "testing/helpers/dump.h"
44#include "testing/helpers/event.h"
45#include "testing/helpers/page_renderer.h"
46#include "testing/helpers/write.h"
47#include "testing/test_loader.h"
48#include "testing/utils/file_util.h"
49#include "testing/utils/hash.h"
50#include "testing/utils/path_service.h"
51
52#ifdef _WIN32
53#include <crtdbg.h>
54#include <errhandlingapi.h>
55#include <io.h>
56#include <wingdi.h>
57
58#include "testing/helpers/win32/com_factory.h"
59#else
60#include <unistd.h>
61#endif // _WIN32
62
63#ifdef ENABLE_CALLGRIND
64#include <valgrind/callgrind.h>
65#endif // ENABLE_CALLGRIND
66
67#if defined(PDF_USE_PARTITION_ALLOC)
68#include "testing/allocator_shim_config.h"
69#endif
70
71#ifdef PDF_ENABLE_SKIA
72#include "third_party/skia/include/core/SkCanvas.h" // nogncheck
73#include "third_party/skia/include/core/SkColor.h" // nogncheck
74#include "third_party/skia/include/core/SkDocument.h" // nogncheck
75#include "third_party/skia/include/core/SkPicture.h" // nogncheck
76#include "third_party/skia/include/core/SkPictureRecorder.h" // nogncheck
77#include "third_party/skia/include/core/SkPixmap.h" // nogncheck
78#include "third_party/skia/include/core/SkRefCnt.h" // nogncheck
79#include "third_party/skia/include/core/SkStream.h" // nogncheck
80#include "third_party/skia/include/core/SkSurface.h" // nogncheck
81
82#ifdef _WIN32
83#include "third_party/skia/include/docs/SkXPSDocument.h" // nogncheck
84#endif
85
86#ifdef BUILD_WITH_CHROMIUM
87#include "testing/chromium_support/discardable_memory_allocator.h" // nogncheck
88#endif
89#endif // PDF_ENABLE_SKIA
90
91#ifdef PDF_ENABLE_V8
92#include "testing/v8_initializer.h"
93#include "v8/include/libplatform/libplatform.h"
94#include "v8/include/v8-array-buffer.h"
95#include "v8/include/v8-isolate.h"
96#include "v8/include/v8-platform.h"
97#include "v8/include/v8-snapshot.h"
98#endif // PDF_ENABLE_V8
99
100#ifdef _WIN32
101#define access _access
102#define snprintf _snprintf
103#define R_OK 4
104#endif
105
106// wordexp is a POSIX function that is only available on macOS and non-Android
107// Linux platforms.
108#if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
109#define WORDEXP_AVAILABLE
110#endif
111
112#ifdef WORDEXP_AVAILABLE
113#include <wordexp.h>
114#endif // WORDEXP_AVAILABLE
115
116namespace {
117
118enum class RendererType {
119 kDefault,
120 kAgg,
121#ifdef _WIN32
122 kGdi,
123#endif // _WIN32
124#if defined(PDF_ENABLE_SKIA)
125 kSkia,
126#endif // defined(PDF_ENABLE_SKIA)
127};
128
129enum class OutputFormat {
130 kNone,
131 kPageInfo,
132 kStructure,
133 kText,
134 kPpm,
135 kPng,
136 kAnnot,
137#ifdef _WIN32
138 kBmp,
139 kEmf,
140 kPs2,
141 kPs3,
142 kPs3Type42,
143#endif
144#ifdef PDF_ENABLE_SKIA
145 kSkp,
146#ifdef _WIN32
147 kXps,
148#endif // _WIN32
149#endif // PDF_ENABLE_SKIA
150};
151
152struct Options {
153 Options() = default;
154
155 bool show_config = false;
156 bool show_metadata = false;
157 bool send_events = false;
158 bool use_load_mem_document = false;
159 bool render_oneshot = false;
160 bool lcd_text = false;
161 bool no_nativetext = false;
162 bool grayscale = false;
163 bool forced_color = false;
164 bool fill_to_stroke = false;
165 bool limit_cache = false;
166 bool force_halftone = false;
167 bool printing = false;
168 bool no_smoothtext = false;
169 bool no_smoothimage = false;
170 bool no_smoothpath = false;
171 bool reverse_byte_order = false;
172 bool save_attachments = false;
173 bool save_images = false;
174 bool save_rendered_images = false;
175 bool save_thumbnails = false;
176 bool save_thumbnails_decoded = false;
177 bool save_thumbnails_raw = false;
178 RendererType use_renderer_type = RendererType::kDefault;
179#ifdef PDF_ENABLE_V8
180 bool disable_javascript = false;
181 std::string js_flags; // Extra flags to pass to v8 init.
182#ifdef PDF_ENABLE_XFA
183 bool disable_xfa = false;
184#endif // PDF_ENABLE_XFA
185#endif // PDF_ENABLE_V8
186 bool pages = false;
187 bool md5 = false;
188#ifdef ENABLE_CALLGRIND
189 bool callgrind_delimiters = false;
190#endif
191#if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
192 bool linux_no_system_fonts = false;
193#endif
194 bool croscore_font_names = false;
195 OutputFormat output_format = OutputFormat::kNone;
196 std::string password;
197 std::string scale_factor_as_string;
198 std::string exe_path;
199 std::string bin_directory;
200 std::string font_directory;
201 int first_page = 0; // First 0-based page number to renderer.
202 int last_page = 0; // Last 0-based page number to renderer.
203 time_t time = -1;
204};
205
206int PageRenderFlagsFromOptions(const Options& options) {
207 int flags = FPDF_ANNOT;
208 if (options.lcd_text)
209 flags |= FPDF_LCD_TEXT;
210 if (options.no_nativetext)
211 flags |= FPDF_NO_NATIVETEXT;
212 if (options.grayscale)
213 flags |= FPDF_GRAYSCALE;
214 if (options.fill_to_stroke)
216 if (options.limit_cache)
218 if (options.force_halftone)
220 if (options.printing)
221 flags |= FPDF_PRINTING;
222 if (options.no_smoothtext)
224 if (options.no_smoothimage)
226 if (options.no_smoothpath)
228 if (options.reverse_byte_order)
230 return flags;
231}
232
233std::optional<std::string> ExpandDirectoryPath(const std::string& path) {
234#if defined(WORDEXP_AVAILABLE)
235 wordexp_t expansion;
236 if (wordexp(path.c_str(), &expansion, 0) != 0 || expansion.we_wordc < 1) {
237 wordfree(&expansion);
238 return {};
239 }
240 // Need to contruct the return value before hand, since wordfree will
241 // deallocate |expansion|.
242 std::optional<std::string> ret_val = {expansion.we_wordv[0]};
243 wordfree(&expansion);
244 return ret_val;
245#else
246 return {path};
247#endif // WORDEXP_AVAILABLE
248}
249
250std::optional<const char*> GetCustomFontPath(const Options& options) {
251#if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
252 // Set custom font path to an empty path. This avoids the fallback to default
253 // font paths.
254 if (options.linux_no_system_fonts)
255 return nullptr;
256#endif
257
258 // No custom font path. Use default.
259 if (options.font_directory.empty())
260 return std::nullopt;
261
262 // Set custom font path to |options.font_directory|.
263 return options.font_directory.c_str();
264}
265
266struct FPDF_FORMFILLINFO_PDFiumTest final : public FPDF_FORMFILLINFO {
267 // Hold a map of the currently loaded pages in order to avoid them
268 // to get loaded twice.
269 std::map<int, ScopedFPDFPage> loaded_pages;
270
271 // Hold a pointer of FPDF_FORMHANDLE so that PDFium app hooks can
272 // make use of it.
273 FPDF_FORMHANDLE form_handle;
274};
275
276FPDF_FORMFILLINFO_PDFiumTest* ToPDFiumTestFormFillInfo(
277 FPDF_FORMFILLINFO* form_fill_info) {
278 return static_cast<FPDF_FORMFILLINFO_PDFiumTest*>(form_fill_info);
279}
280
281void OutputMD5Hash(const char* file_name, pdfium::span<const uint8_t> output) {
282 // Get the MD5 hash and write it to stdout.
283 std::string hash = GenerateMD5Base16(output);
284 printf("MD5:%s:%s\n", file_name, hash.c_str());
285}
286
287#ifdef PDF_ENABLE_V8
288
289struct V8IsolateDeleter {
290 inline void operator()(v8::Isolate* ptr) { ptr->Dispose(); }
291};
292
293// These example JS platform callback handlers are entirely optional,
294// and exist here to show the flow of information from a document back
295// to the embedder.
296int ExampleAppAlert(IPDF_JSPLATFORM*,
297 FPDF_WIDESTRING msg,
298 FPDF_WIDESTRING title,
299 int type,
300 int icon) {
301 printf("%ls", GetPlatformWString(title).c_str());
302 if (icon || type)
303 printf("[icon=%d,type=%d]", icon, type);
304 printf(": %ls\n", GetPlatformWString(msg).c_str());
305 return 0;
306}
307
308void ExampleAppBeep(IPDF_JSPLATFORM*, int type) {
309 printf("BEEP!!! %d\n", type);
310}
311
312int ExampleAppResponse(IPDF_JSPLATFORM*,
313 FPDF_WIDESTRING question,
314 FPDF_WIDESTRING title,
315 FPDF_WIDESTRING default_value,
316 FPDF_WIDESTRING label,
317 FPDF_BOOL is_password,
318 void* response,
319 int length) {
320 printf("%ls: %ls, defaultValue=%ls, label=%ls, isPassword=%d, length=%d\n",
321 GetPlatformWString(title).c_str(),
322 GetPlatformWString(question).c_str(),
323 GetPlatformWString(default_value).c_str(),
324 GetPlatformWString(label).c_str(), is_password, length);
325
326 // UTF-16, always LE regardless of platform.
327 auto* ptr = static_cast<uint8_t*>(response);
328 ptr[0] = 'N';
329 ptr[1] = 0;
330 ptr[2] = 'o';
331 ptr[3] = 0;
332 return 4;
333}
334
335int ExampleDocGetFilePath(IPDF_JSPLATFORM*, void* file_path, int length) {
336 static const char kPath[] = "myfile.pdf";
337 constexpr int kRequired = static_cast<int>(sizeof(kPath));
338 if (file_path && length >= kRequired)
339 memcpy(file_path, kPath, kRequired);
340 return kRequired;
341}
342
343void ExampleDocMail(IPDF_JSPLATFORM*,
344 void* mailData,
345 int length,
346 FPDF_BOOL UI,
347 FPDF_WIDESTRING To,
348 FPDF_WIDESTRING Subject,
349 FPDF_WIDESTRING CC,
350 FPDF_WIDESTRING BCC,
351 FPDF_WIDESTRING Msg) {
352 printf("Mail Msg: %d, to=%ls, cc=%ls, bcc=%ls, subject=%ls, body=%ls\n", UI,
353 GetPlatformWString(To).c_str(), GetPlatformWString(CC).c_str(),
354 GetPlatformWString(BCC).c_str(), GetPlatformWString(Subject).c_str(),
355 GetPlatformWString(Msg).c_str());
356}
357
358void ExampleDocPrint(IPDF_JSPLATFORM*,
359 FPDF_BOOL bUI,
360 int nStart,
361 int nEnd,
362 FPDF_BOOL bSilent,
363 FPDF_BOOL bShrinkToFit,
364 FPDF_BOOL bPrintAsImage,
365 FPDF_BOOL bReverse,
366 FPDF_BOOL bAnnotations) {
367 printf("Doc Print: %d, %d, %d, %d, %d, %d, %d, %d\n", bUI, nStart, nEnd,
368 bSilent, bShrinkToFit, bPrintAsImage, bReverse, bAnnotations);
369}
370
371void ExampleDocSubmitForm(IPDF_JSPLATFORM*,
372 void* formData,
373 int length,
374 FPDF_WIDESTRING url) {
375 printf("Doc Submit Form: url=%ls + %d data bytes:\n",
376 GetPlatformWString(url).c_str(), length);
377 uint8_t* ptr = reinterpret_cast<uint8_t*>(formData);
378 for (int i = 0; i < length; ++i)
379 printf(" %02x", ptr[i]);
380 printf("\n");
381}
382
383void ExampleDocGotoPage(IPDF_JSPLATFORM*, int page_number) {
384 printf("Goto Page: %d\n", page_number);
385}
386
387int ExampleFieldBrowse(IPDF_JSPLATFORM*, void* file_path, int length) {
388 static const char kPath[] = "selected.txt";
389 constexpr int kRequired = static_cast<int>(sizeof(kPath));
390 if (file_path && length >= kRequired)
391 memcpy(file_path, kPath, kRequired);
392 return kRequired;
393}
394#endif // PDF_ENABLE_V8
395
396#ifdef PDF_ENABLE_XFA
397FPDF_BOOL ExamplePopupMenu(FPDF_FORMFILLINFO* pInfo,
398 FPDF_PAGE page,
399 FPDF_WIDGET always_null,
400 int flags,
401 float x,
402 float y) {
403 printf("Popup: x=%2.1f, y=%2.1f, flags=0x%x\n", x, y, flags);
404 return true;
405}
406#endif // PDF_ENABLE_XFA
407
408void ExampleNamedAction(FPDF_FORMFILLINFO* pInfo, FPDF_BYTESTRING name) {
409 printf("Execute named action: %s\n", name);
410}
411
412void ExampleUnsupportedHandler(UNSUPPORT_INFO*, int type) {
413 std::string feature = "Unknown";
414 switch (type) {
416 feature = "XFA";
417 break;
419 feature = "Portfolios_Packages";
420 break;
423 feature = "Attachment";
424 break;
426 feature = "Rights_Management";
427 break;
429 feature = "Shared_Review";
430 break;
434 feature = "Shared_Form";
435 break;
437 feature = "3D";
438 break;
440 feature = "Movie";
441 break;
443 feature = "Sound";
444 break;
447 feature = "Screen";
448 break;
450 feature = "Digital_Signature";
451 break;
452 }
453 printf("Unsupported feature: %s.\n", feature.c_str());
454}
455
456bool ParseCommandLine(const std::vector<std::string>& args,
457 Options* options,
458 std::vector<std::string>* files) {
459 if (args.empty())
460 return false;
461
462 options->exe_path = args[0];
463 size_t cur_idx = 1;
464 std::string value;
465 for (; cur_idx < args.size(); ++cur_idx) {
466 const std::string& cur_arg = args[cur_idx];
467 if (cur_arg == "--show-config") {
468 options->show_config = true;
469 } else if (cur_arg == "--show-metadata") {
470 options->show_metadata = true;
471 } else if (cur_arg == "--send-events") {
472 options->send_events = true;
473 } else if (cur_arg == "--mem-document") {
474 options->use_load_mem_document = true;
475 } else if (cur_arg == "--render-oneshot") {
476 options->render_oneshot = true;
477 } else if (cur_arg == "--lcd-text") {
478 options->lcd_text = true;
479 } else if (cur_arg == "--no-nativetext") {
480 options->no_nativetext = true;
481 } else if (cur_arg == "--grayscale") {
482 options->grayscale = true;
483 } else if (cur_arg == "--forced-color") {
484 options->forced_color = true;
485 } else if (cur_arg == "--fill-to-stroke") {
486 options->fill_to_stroke = true;
487 } else if (cur_arg == "--limit-cache") {
488 options->limit_cache = true;
489 } else if (cur_arg == "--force-halftone") {
490 options->force_halftone = true;
491 } else if (cur_arg == "--printing") {
492 options->printing = true;
493 } else if (cur_arg == "--no-smoothtext") {
494 options->no_smoothtext = true;
495 } else if (cur_arg == "--no-smoothimage") {
496 options->no_smoothimage = true;
497 } else if (cur_arg == "--no-smoothpath") {
498 options->no_smoothpath = true;
499 } else if (cur_arg == "--reverse-byte-order") {
500 options->reverse_byte_order = true;
501 } else if (cur_arg == "--save-attachments") {
502 options->save_attachments = true;
503 } else if (cur_arg == "--save-images") {
504 if (options->save_rendered_images) {
505 fprintf(stderr,
506 "--save-rendered-images conflicts with --save-images\n");
507 return false;
508 }
509 options->save_images = true;
510 } else if (cur_arg == "--save-rendered-images") {
511 if (options->save_images) {
512 fprintf(stderr,
513 "--save-images conflicts with --save-rendered-images\n");
514 return false;
515 }
516 options->save_rendered_images = true;
517 } else if (cur_arg == "--save-thumbs") {
518 options->save_thumbnails = true;
519 } else if (cur_arg == "--save-thumbs-dec") {
520 options->save_thumbnails_decoded = true;
521 } else if (cur_arg == "--save-thumbs-raw") {
522 options->save_thumbnails_raw = true;
523 } else if (ParseSwitchKeyValue(cur_arg, "--use-renderer=", &value)) {
524 if (options->use_renderer_type != RendererType::kDefault) {
525 fprintf(stderr, "Duplicate --use-renderer argument\n");
526 return false;
527 }
528 if (value == "agg") {
529 options->use_renderer_type = RendererType::kAgg;
530#ifdef _WIN32
531 } else if (value == "gdi") {
532 options->use_renderer_type = RendererType::kGdi;
533#endif // _WIN32
534#if defined(PDF_ENABLE_SKIA)
535 } else if (value == "skia") {
536 options->use_renderer_type = RendererType::kSkia;
537#endif // defined(PDF_ENABLE_SKIA)
538 } else {
539 fprintf(stderr, "Invalid --use-renderer argument\n");
540 return false;
541 }
542#ifdef PDF_ENABLE_V8
543 } else if (cur_arg == "--disable-javascript") {
544 options->disable_javascript = true;
545 } else if (ParseSwitchKeyValue(cur_arg, "--js-flags=", &value)) {
546 if (!options->js_flags.empty()) {
547 fprintf(stderr, "Duplicate --js-flags argument\n");
548 return false;
549 }
550 options->js_flags = value;
551#ifdef PDF_ENABLE_XFA
552 } else if (cur_arg == "--disable-xfa") {
553 options->disable_xfa = true;
554#endif // PDF_ENABLE_XFA
555#endif // PDF_ENABLE_V8
556#ifdef ENABLE_CALLGRIND
557 } else if (cur_arg == "--callgrind-delim") {
558 options->callgrind_delimiters = true;
559#endif
560#if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
561 } else if (cur_arg == "--no-system-fonts") {
562 options->linux_no_system_fonts = true;
563#endif
564 } else if (cur_arg == "--croscore-font-names") {
565 options->croscore_font_names = true;
566 } else if (cur_arg == "--ppm") {
567 if (options->output_format != OutputFormat::kNone) {
568 fprintf(stderr, "Duplicate or conflicting --ppm argument\n");
569 return false;
570 }
571 options->output_format = OutputFormat::kPpm;
572 } else if (cur_arg == "--png") {
573 if (options->output_format != OutputFormat::kNone) {
574 fprintf(stderr, "Duplicate or conflicting --png argument\n");
575 return false;
576 }
577 options->output_format = OutputFormat::kPng;
578 } else if (cur_arg == "--txt") {
579 if (options->output_format != OutputFormat::kNone) {
580 fprintf(stderr, "Duplicate or conflicting --txt argument\n");
581 return false;
582 }
583 options->output_format = OutputFormat::kText;
584 } else if (cur_arg == "--annot") {
585 if (options->output_format != OutputFormat::kNone) {
586 fprintf(stderr, "Duplicate or conflicting --annot argument\n");
587 return false;
588 }
589 options->output_format = OutputFormat::kAnnot;
590#ifdef PDF_ENABLE_SKIA
591 } else if (cur_arg == "--skp") {
592 if (options->output_format != OutputFormat::kNone) {
593 fprintf(stderr, "Duplicate or conflicting --skp argument\n");
594 return false;
595 }
596 options->output_format = OutputFormat::kSkp;
597#ifdef _WIN32
598 } else if (cur_arg == "--xps") {
599 if (options->output_format != OutputFormat::kNone) {
600 fprintf(stderr, "Duplicate or conflicting --xps argument\n");
601 return false;
602 }
603 options->output_format = OutputFormat::kXps;
604#endif // _WIN32
605#endif // PDF_ENABLE_SKIA
606 } else if (ParseSwitchKeyValue(cur_arg, "--font-dir=", &value)) {
607 if (!options->font_directory.empty()) {
608 fprintf(stderr, "Duplicate --font-dir argument\n");
609 return false;
610 }
611 std::string path = value;
612 std::optional<std::string> expanded_path = ExpandDirectoryPath(path);
613 if (!expanded_path.has_value()) {
614 fprintf(stderr, "Failed to expand --font-dir, %s\n", path.c_str());
615 return false;
616 }
617
618 if (!PathService::DirectoryExists(expanded_path.value())) {
619 fprintf(stderr, "--font-dir, %s, appears to not be a directory\n",
620 path.c_str());
621 return false;
622 }
623
624 options->font_directory = expanded_path.value();
625
626#ifdef _WIN32
627 } else if (cur_arg == "--emf") {
628 if (options->output_format != OutputFormat::kNone) {
629 fprintf(stderr, "Duplicate or conflicting --emf argument\n");
630 return false;
631 }
632 options->output_format = OutputFormat::kEmf;
633 } else if (cur_arg == "--ps2") {
634 if (options->output_format != OutputFormat::kNone) {
635 fprintf(stderr, "Duplicate or conflicting --ps2 argument\n");
636 return false;
637 }
638 options->output_format = OutputFormat::kPs2;
639 } else if (cur_arg == "--ps3") {
640 if (options->output_format != OutputFormat::kNone) {
641 fprintf(stderr, "Duplicate or conflicting --ps3 argument\n");
642 return false;
643 }
644 options->output_format = OutputFormat::kPs3;
645 } else if (cur_arg == "--ps3-type42") {
646 if (options->output_format != OutputFormat::kNone) {
647 fprintf(stderr, "Duplicate or conflicting --ps3-type42 argument\n");
648 return false;
649 }
650 options->output_format = OutputFormat::kPs3Type42;
651 } else if (cur_arg == "--bmp") {
652 if (options->output_format != OutputFormat::kNone) {
653 fprintf(stderr, "Duplicate or conflicting --bmp argument\n");
654 return false;
655 }
656 options->output_format = OutputFormat::kBmp;
657#endif // _WIN32
658
659#ifdef PDF_ENABLE_V8
660#ifdef V8_USE_EXTERNAL_STARTUP_DATA
661 } else if (ParseSwitchKeyValue(cur_arg, "--bin-dir=", &value)) {
662 if (!options->bin_directory.empty()) {
663 fprintf(stderr, "Duplicate --bin-dir argument\n");
664 return false;
665 }
666 std::string path = value;
667 std::optional<std::string> expanded_path = ExpandDirectoryPath(path);
668 if (!expanded_path.has_value()) {
669 fprintf(stderr, "Failed to expand --bin-dir, %s\n", path.c_str());
670 return false;
671 }
672 options->bin_directory = expanded_path.value();
673#endif // V8_USE_EXTERNAL_STARTUP_DATA
674#endif // PDF_ENABLE_V8
675
676 } else if (ParseSwitchKeyValue(cur_arg, "--password=", &value)) {
677 if (!options->password.empty()) {
678 fprintf(stderr, "Duplicate --password argument\n");
679 return false;
680 }
681 options->password = value;
682 } else if (ParseSwitchKeyValue(cur_arg, "--scale=", &value)) {
683 if (!options->scale_factor_as_string.empty()) {
684 fprintf(stderr, "Duplicate --scale argument\n");
685 return false;
686 }
687 options->scale_factor_as_string = value;
688 } else if (cur_arg == "--show-pageinfo") {
689 if (options->output_format != OutputFormat::kNone) {
690 fprintf(stderr, "Duplicate or conflicting --show-pageinfo argument\n");
691 return false;
692 }
693 options->output_format = OutputFormat::kPageInfo;
694 } else if (cur_arg == "--show-structure") {
695 if (options->output_format != OutputFormat::kNone) {
696 fprintf(stderr, "Duplicate or conflicting --show-structure argument\n");
697 return false;
698 }
699 options->output_format = OutputFormat::kStructure;
700 } else if (ParseSwitchKeyValue(cur_arg, "--pages=", &value)) {
701 if (options->pages) {
702 fprintf(stderr, "Duplicate --pages argument\n");
703 return false;
704 }
705 options->pages = true;
706 const std::string pages_string = value;
707 size_t first_dash = pages_string.find('-');
708 if (first_dash == std::string::npos) {
709 std::stringstream(pages_string) >> options->first_page;
710 options->last_page = options->first_page;
711 } else {
712 std::stringstream(pages_string.substr(0, first_dash)) >>
713 options->first_page;
714 std::stringstream(pages_string.substr(first_dash + 1)) >>
715 options->last_page;
716 }
717 } else if (cur_arg == "--md5") {
718 options->md5 = true;
719 } else if (ParseSwitchKeyValue(cur_arg, "--time=", &value)) {
720 if (options->time > -1) {
721 fprintf(stderr, "Duplicate --time argument\n");
722 return false;
723 }
724 const std::string time_string = value;
725 std::stringstream(time_string) >> options->time;
726 if (options->time < 0) {
727 fprintf(stderr, "Invalid --time argument, must be non-negative\n");
728 return false;
729 }
730 } else if (cur_arg.size() >= 2 && cur_arg[0] == '-' && cur_arg[1] == '-') {
731 fprintf(stderr, "Unrecognized argument %s\n", cur_arg.c_str());
732 return false;
733 } else {
734 break;
735 }
736 }
737 for (size_t i = cur_idx; i < args.size(); i++)
738 files->push_back(args[i]);
739
740 return true;
741}
742
743void PrintLastError() {
744 unsigned long err = FPDF_GetLastError();
745 fprintf(stderr, "Load pdf docs unsuccessful: ");
746 switch (err) {
747 case FPDF_ERR_SUCCESS:
748 fprintf(stderr, "Success");
749 break;
750 case FPDF_ERR_UNKNOWN:
751 fprintf(stderr, "Unknown error");
752 break;
753 case FPDF_ERR_FILE:
754 fprintf(stderr, "File not found or could not be opened");
755 break;
756 case FPDF_ERR_FORMAT:
757 fprintf(stderr, "File not in PDF format or corrupted");
758 break;
760 fprintf(stderr, "Password required or incorrect password");
761 break;
763 fprintf(stderr, "Unsupported security scheme");
764 break;
765 case FPDF_ERR_PAGE:
766 fprintf(stderr, "Page not found or content error");
767 break;
768 default:
769 fprintf(stderr, "Unknown error %ld", err);
770 }
771 fprintf(stderr, ".\n");
772}
773
774FPDF_BOOL Is_Data_Avail(FX_FILEAVAIL* avail, size_t offset, size_t size) {
775 return true;
776}
777
778void Add_Segment(FX_DOWNLOADHINTS* hints, size_t offset, size_t size) {}
779
780FPDF_PAGE GetPageForIndex(FPDF_FORMFILLINFO* param,
781 FPDF_DOCUMENT doc,
782 int index) {
783 FPDF_FORMFILLINFO_PDFiumTest* form_fill_info =
784 ToPDFiumTestFormFillInfo(param);
785 auto& loaded_pages = form_fill_info->loaded_pages;
786 auto iter = loaded_pages.find(index);
787 if (iter != loaded_pages.end())
788 return iter->second.get();
789
790 ScopedFPDFPage page(FPDF_LoadPage(doc, index));
791 if (!page)
792 return nullptr;
793
794 // Mark the page as loaded first to prevent infinite recursion.
795 FPDF_PAGE page_ptr = page.get();
796 loaded_pages[index] = std::move(page);
797
798 FPDF_FORMHANDLE& form_handle = form_fill_info->form_handle;
799 FORM_OnAfterLoadPage(page_ptr, form_handle);
801 return page_ptr;
802}
803
804// Note, for a client using progressive rendering you'd want to determine if you
805// need the rendering to pause instead of always saying |true|. This is for
806// testing to force the renderer to break whenever possible.
807FPDF_BOOL NeedToPauseNow(IFSDK_PAUSE* p) {
808 return true;
809}
810
811class Processor final {
812 public:
813 Processor(const Options* options, const std::function<void()>* idler)
814 : options_(options), idler_(idler) {
815 DCHECK(options_);
816 DCHECK(idler_);
817 }
818
819 const Options& options() const { return *options_; }
820 const std::function<void()>& idler() const { return *idler_; }
821
822#ifdef _WIN32
823 ComFactory& com_factory() { return com_factory_; }
824#endif // _WIN32
825
826 // Invokes `idler()`.
827 void Idle() const { idler()(); }
828
829 void ProcessPdf(const std::string& name,
830 pdfium::span<const uint8_t> data,
831 const std::string& events);
832
833 private:
834 const Options* options_;
835 const std::function<void()>* idler_;
836
837#ifdef _WIN32
838 ComFactory com_factory_;
839#endif // _WIN32
840};
841
842class PdfProcessor final {
843 public:
844 PdfProcessor(Processor* processor,
845 const std::string* name,
846 const std::string* events,
847 FPDF_DOCUMENT doc,
848 FPDF_FORMHANDLE form,
849 FPDF_FORMFILLINFO_PDFiumTest* form_fill_info)
850 : processor_(processor),
851 name_(name),
852 events_(events),
853 doc_(doc),
854 form_(form),
855 form_fill_info_(form_fill_info) {
856 DCHECK(processor_);
857 DCHECK(name_);
858 DCHECK(events_);
859 DCHECK(doc_);
860 DCHECK(form_);
861 DCHECK(form_fill_info_);
862 }
863
864 bool ProcessPage(int page_index);
865
866 private:
867 // Per processor state.
868 const Options& options() const { return processor_->options(); }
869 const std::function<void()>& idler() const { return processor_->idler(); }
870
871#ifdef _WIN32
872 ComFactory& com_factory() { return processor_->com_factory(); }
873#endif // _WIN32
874
875 // Per PDF state.
876 const std::string& name() const { return *name_; }
877 const std::string& events() const { return *events_; }
878 FPDF_DOCUMENT doc() const { return doc_; }
879 FPDF_FORMHANDLE form() const { return form_; }
880
881 // Invokes `idler()`.
882 void Idle() const { idler()(); }
883
884 FPDF_PAGE GetPage(int page_index) const {
885 return GetPageForIndex(form_fill_info_, doc_, page_index);
886 }
887
888 Processor* processor_;
889 const std::string* name_;
890 const std::string* events_;
891 FPDF_DOCUMENT doc_;
892 FPDF_FORMHANDLE form_;
893 FPDF_FORMFILLINFO_PDFiumTest* form_fill_info_;
894};
895
896// Page renderer with bitmap output.
897class BitmapPageRenderer : public PageRenderer {
898 public:
899 // Function type that writes rendered output to a file, returning `false` on
900 // failure.
901 //
902 // Intended to wrap functions from `pdfium_test_write_helper.h`.
903 using PageWriter = std::function<bool(BitmapPageRenderer& renderer,
904 const std::string& name,
905 int page_index,
906 bool md5)>;
907
908 // Wraps a `PageWriter` around a function pointer that writes the text page.
909 static PageWriter WrapPageWriter(
910 void (*text_page_writer)(FPDF_TEXTPAGE text_page,
911 const char* pdf_name,
912 int num)) {
913 return [text_page_writer](BitmapPageRenderer& renderer,
914 const std::string& name, int page_index,
915 bool /*md5*/) {
916 ScopedFPDFTextPage text_page(FPDFText_LoadPage(renderer.page()));
917 if (!text_page) {
918 return false;
919 }
920
921 text_page_writer(text_page.get(), name.c_str(), page_index);
922 return true;
923 };
924 }
925
926 // Wraps a `PageWriter` around a function pointer that writes the page.
927 static PageWriter WrapPageWriter(void (*page_writer)(FPDF_PAGE page,
928 const char* pdf_name,
929 int num)) {
930 return [page_writer](BitmapPageRenderer& renderer, const std::string& name,
931 int page_index, bool /*md5*/) {
932 page_writer(renderer.page(), name.c_str(), page_index);
933 return true;
934 };
935 }
936
937 // Wraps a `PageWriter` around a function pointer that writes the rasterized
938 // bitmap to an image file.
939 static PageWriter WrapPageWriter(
940 std::string (*bitmap_writer)(const char* pdf_name,
941 int num,
942 void* buffer,
943 int stride,
944 int width,
945 int height)) {
946 return [bitmap_writer](BitmapPageRenderer& renderer,
947 const std::string& name, int page_index, bool md5) {
948 int stride = FPDFBitmap_GetStride(renderer.bitmap());
949 void* buffer = FPDFBitmap_GetBuffer(renderer.bitmap());
950 std::string image_file_name = bitmap_writer(
951 name.c_str(), page_index, buffer, /*stride=*/stride,
952 /*width=*/renderer.width(), /*height=*/renderer.height());
953 if (image_file_name.empty()) {
954 return false;
955 }
956
957 if (md5) {
958 // Write the filename and the MD5 of the buffer to stdout.
959 OutputMD5Hash(image_file_name.c_str(),
960 UNSAFE_TODO(pdfium::make_span(
961 static_cast<const uint8_t*>(buffer),
962 static_cast<size_t>(stride) * renderer.height())));
963 }
964 return true;
965 };
966 }
967
968 bool HasOutput() const override { return !!bitmap_; }
969
970 void Finish(FPDF_FORMHANDLE form) override {
971 FPDF_FFLDraw(form, bitmap(), page(), /*start_x=*/0, /*start_y=*/0,
972 /*size_x=*/width(), /*size_y=*/height(), /*rotate=*/0,
973 /*flags=*/flags());
974 Idle();
975 }
976
977 bool Write(const std::string& name, int page_index, bool md5) override {
978 return writer_ && writer_(*this, name, page_index, md5);
979 }
980
981 protected:
982 BitmapPageRenderer(FPDF_PAGE page,
983 int width,
984 int height,
985 int flags,
986 const std::function<void()>& idler,
987 PageWriter writer)
988 : PageRenderer(page, /*width=*/width, /*height=*/height, /*flags=*/flags),
989 idler_(idler),
990 writer_(std::move(writer)) {}
991
992 bool InitializeBitmap(void* first_scan) {
993 bool alpha = FPDFPage_HasTransparency(page());
994 bitmap_.reset(FPDFBitmap_CreateEx(
995 /*width=*/width(), /*height=*/height(),
996 /*format=*/alpha ? FPDFBitmap_BGRA : FPDFBitmap_BGRx, first_scan,
997 /*stride=*/width() * sizeof(uint32_t)));
998 if (!bitmap()) {
999 return false;
1000 }
1001
1002 FPDF_DWORD fill_color = alpha ? 0x00000000 : 0xFFFFFFFF;
1003 return FPDFBitmap_FillRect(bitmap(), /*left=*/0, /*top=*/0,
1004 /*width=*/width(),
1005 /*height=*/height(), /*color=*/fill_color);
1006 }
1007
1008 void ResetBitmap() { bitmap_.reset(); }
1009
1010 void Idle() const { idler_(); }
1011 FPDF_BITMAP bitmap() { return bitmap_.get(); }
1012
1013 private:
1014 const std::function<void()>& idler_;
1015 PageWriter writer_;
1016 ScopedFPDFBitmap bitmap_;
1017};
1018
1019// Bitmap page renderer completing in a single operation.
1020class OneShotBitmapPageRenderer : public BitmapPageRenderer {
1021 public:
1022 OneShotBitmapPageRenderer(FPDF_PAGE page,
1023 int width,
1024 int height,
1025 int flags,
1026 const std::function<void()>& idler,
1027 PageWriter writer)
1028 : BitmapPageRenderer(page,
1029 /*width=*/width,
1030 /*height=*/height,
1031 /*flags=*/flags,
1032 idler,
1033 std::move(writer)) {}
1034
1035 bool Start() override {
1036 if (!InitializeBitmap(/*first_scan=*/nullptr)) {
1037 return false;
1038 }
1039
1040 // Note, client programs probably want to use this method instead of the
1041 // progressive calls. The progressive calls are if you need to pause the
1042 // rendering to update the UI, the PDF renderer will break when possible.
1043 FPDF_RenderPageBitmap(bitmap(), page(), /*start_x=*/0, /*start_y=*/0,
1044 /*size_x=*/width(), /*size_y=*/height(), /*rotate=*/0,
1045 /*flags=*/flags());
1046 return true;
1047 }
1048};
1049
1050// Bitmap page renderer completing over multiple operations.
1051class ProgressiveBitmapPageRenderer : public BitmapPageRenderer {
1052 public:
1053 ProgressiveBitmapPageRenderer(FPDF_PAGE page,
1054 int width,
1055 int height,
1056 int flags,
1057 const std::function<void()>& idler,
1058 PageWriter writer,
1059 const FPDF_COLORSCHEME* color_scheme)
1060 : BitmapPageRenderer(page,
1061 /*width=*/width,
1062 /*height=*/height,
1063 /*flags=*/flags,
1064 idler,
1065 std::move(writer)),
1066 color_scheme_(color_scheme) {
1067 pause_.version = 1;
1068 pause_.NeedToPauseNow = &NeedToPauseNow;
1069 }
1070
1071 bool Start() override {
1072 if (!InitializeBitmap(/*first_scan=*/nullptr)) {
1073 return false;
1074 }
1075
1076 if (FPDF_RenderPageBitmapWithColorScheme_Start(
1077 bitmap(), page(), /*start_x=*/0, /*start_y=*/0, /*size_x=*/width(),
1078 /*size_y=*/height(), /*rotate=*/0, /*flags=*/flags(), color_scheme_,
1079 &pause_) == FPDF_RENDER_TOBECONTINUED) {
1080 to_be_continued_ = true;
1081 }
1082 return true;
1083 }
1084
1085 bool Continue() override {
1086 if (to_be_continued_) {
1087 to_be_continued_ = (FPDF_RenderPage_Continue(page(), &pause_) ==
1089 }
1090 return to_be_continued_;
1091 }
1092
1093 void Finish(FPDF_FORMHANDLE form) override {
1094 BitmapPageRenderer::Finish(form);
1095 FPDF_RenderPage_Close(page());
1096 Idle();
1097 }
1098
1099 private:
1100 const FPDF_COLORSCHEME* color_scheme_;
1101 IFSDK_PAUSE pause_;
1102 bool to_be_continued_ = false;
1103};
1104
1105#ifdef _WIN32
1106class ScopedGdiDc final {
1107 public:
1108 ~ScopedGdiDc() { Reset(nullptr); }
1109
1110 void Reset(HDC dc) {
1111 if (dc_) {
1112 [[maybe_unused]] BOOL success = DeleteDC(dc_);
1113 DCHECK(success);
1114 }
1115 dc_ = dc;
1116 }
1117
1118 HDC Get() const { return dc_; }
1119
1120 private:
1121 HDC dc_ = nullptr;
1122};
1123
1124class ScopedGdiObject final {
1125 public:
1126 ~ScopedGdiObject() { Reset(nullptr); }
1127
1128 void Reset(HGDIOBJ object) {
1129 if (object_) {
1130 [[maybe_unused]] BOOL success = DeleteObject(object_);
1131 DCHECK(success);
1132 }
1133 object_ = object;
1134 }
1135
1136 HGDIOBJ Get() const { return object_; }
1137
1138 private:
1139 HGDIOBJ object_ = nullptr;
1140};
1141
1142class GdiDisplayPageRenderer : public BitmapPageRenderer {
1143 public:
1144 GdiDisplayPageRenderer(FPDF_PAGE page,
1145 int width,
1146 int height,
1147 int flags,
1148 const std::function<void()>& idler,
1149 PageWriter writer)
1150 : BitmapPageRenderer(page,
1151 /*width=*/width,
1152 /*height=*/height,
1153 /*flags=*/flags,
1154 idler,
1155 std::move(writer)) {}
1156
1157 ~GdiDisplayPageRenderer() override {
1158 // Need to free `bitmap()` first, in case it points at `dib_` memory.
1159 ResetBitmap();
1160 }
1161
1162 bool Start() override {
1163 // Create an in-memory DC compatible with the display.
1164 dc_.Reset(CreateCompatibleDC(/*hdc=*/nullptr));
1165 if (!dc_.Get()) {
1166 return false;
1167 }
1168
1169 // Create a BGRA DIB and select it into the in-memory DC.
1170 BITMAPINFO dib_info;
1171 memset(&dib_info, 0, sizeof(BITMAPINFO));
1172 dib_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1173 dib_info.bmiHeader.biWidth = width();
1174 dib_info.bmiHeader.biHeight = -height(); // top-down
1175 dib_info.bmiHeader.biPlanes = 1;
1176 dib_info.bmiHeader.biBitCount = 32;
1177 dib_info.bmiHeader.biCompression = BI_RGB;
1178
1179 VOID* dib_pixels;
1180 dib_.Reset(CreateDIBSection(dc_.Get(), &dib_info, DIB_RGB_COLORS,
1181 &dib_pixels, /*hSection=*/nullptr,
1182 /*offset=*/0));
1183 if (!dib_.Get() || !InitializeBitmap(dib_pixels)) {
1184 return false;
1185 }
1186
1187 HGDIOBJ old_obj = SelectObject(dc_.Get(), dib_.Get());
1188 CHECK(old_obj);
1189 CHECK_NE(old_obj, HGDI_ERROR);
1190
1191 // Render into the in-memory DC.
1192 FPDF_RenderPage(dc_.Get(), page(), /*start_x=*/0, /*start_y=*/0,
1193 /*size_x=*/width(), /*size_y=*/height(), /*rotate=*/0,
1194 /*flags=*/flags());
1195
1196 bool result = !!GdiFlush();
1197 HGDIOBJ dib_obj = SelectObject(dc_.Get(), old_obj);
1198 CHECK((GetObjectType(old_obj) != OBJ_REGION && dib_obj) ||
1199 (GetObjectType(old_obj) == OBJ_REGION && dib_obj != HGDI_ERROR));
1200 return result;
1201 }
1202
1203 void Finish(FPDF_FORMHANDLE /*form*/) override {
1204 // Note that `fpdf_formfill.h` does not support GDI.
1205
1206 // The GDI backend doesn't support alpha and clears the alpha component to
1207 // transparent, so clear the alpha component back to opaque.
1208 const int stride = FPDFBitmap_GetStride(bitmap());
1209 DCHECK_EQ(width() * sizeof(uint32_t), static_cast<size_t>(stride));
1210 const int pixel_stride = stride / sizeof(uint32_t);
1211
1212 uint32_t* scanline =
1213 reinterpret_cast<uint32_t*>(FPDFBitmap_GetBuffer(bitmap()));
1214 for (int row = 0; row < height(); ++row) {
1215 for (int column = 0; column < width(); ++column) {
1216 scanline[column] |= 0xFF000000;
1217 }
1218 scanline += pixel_stride;
1219 }
1220 }
1221
1222 private:
1223 ScopedGdiDc dc_;
1224 ScopedGdiObject dib_;
1225};
1226#endif // _WIN32
1227
1228#ifdef PDF_ENABLE_SKIA
1229class SkCanvasPageRenderer : public PageRenderer {
1230 public:
1231 bool Start() override {
1232 FPDF_RenderPageSkia(reinterpret_cast<FPDF_SKIA_CANVAS>(canvas()), page(),
1233 width(), height());
1234 return true;
1235 }
1236
1237 void Finish(FPDF_FORMHANDLE form) override {
1238 FPDF_FFLDrawSkia(form, reinterpret_cast<FPDF_SKIA_CANVAS>(canvas()), page(),
1239 /*start_x=*/0, /*start_y=*/0, width(), height(),
1240 /*rotate=*/0, flags());
1241 }
1242
1243 protected:
1244 SkCanvasPageRenderer(FPDF_PAGE page, int width, int height, int flags)
1245 : PageRenderer(page, width, height, flags) {}
1246
1247 virtual SkCanvas* canvas() = 0;
1248};
1249
1250class SkPicturePageRenderer final : public SkCanvasPageRenderer {
1251 public:
1252 SkPicturePageRenderer(FPDF_PAGE page, int width, int height, int flags)
1253 : SkCanvasPageRenderer(page, width, height, flags) {}
1254
1255 bool HasOutput() const override { return !!picture_; }
1256
1257 bool Start() override {
1258 recorder_ = std::make_unique<SkPictureRecorder>();
1259 recorder_->beginRecording(width(), height());
1260 return SkCanvasPageRenderer::Start();
1261 }
1262
1263 void Finish(FPDF_FORMHANDLE form) override {
1264 SkCanvasPageRenderer::Finish(form);
1265 picture_ = recorder_->finishRecordingAsPicture();
1266 recorder_.reset();
1267 }
1268
1269 bool Write(const std::string& name, int page_index, bool md5) override {
1270 std::string image_file_name = WriteSkp(name.c_str(), page_index, *picture_);
1271 if (image_file_name.empty())
1272 return false;
1273
1274 if (md5) {
1275 // Play back the `SkPicture` so we can take a hash of the result.
1276 sk_sp<SkSurface> surface = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(
1277 /*width=*/width(), /*height=*/height()));
1278 if (!surface)
1279 return false;
1280
1281 // Must clear to white before replay to match initial `CFX_DIBitmap`.
1282 surface->getCanvas()->clear(SK_ColorWHITE);
1283 surface->getCanvas()->drawPicture(picture_);
1284
1285 // Write the filename and the MD5 of the buffer to stdout.
1286 SkPixmap pixmap;
1287 if (!surface->peekPixels(&pixmap))
1288 return false;
1289
1290 OutputMD5Hash(image_file_name.c_str(),
1291 UNSAFE_TODO(pdfium::make_span(
1292 static_cast<const uint8_t*>(pixmap.addr()),
1293 pixmap.computeByteSize())));
1294 }
1295 return true;
1296 }
1297
1298 protected:
1299 SkCanvas* canvas() override { return recorder_->getRecordingCanvas(); }
1300
1301 private:
1302 std::unique_ptr<SkPictureRecorder> recorder_;
1303 sk_sp<SkPicture> picture_;
1304};
1305
1306class SkDocumentPageRenderer final : public SkCanvasPageRenderer {
1307 public:
1308 SkDocumentPageRenderer(std::unique_ptr<SkWStream> stream,
1309 sk_sp<SkDocument> document,
1310 FPDF_PAGE page,
1311 int width,
1312 int height,
1313 int flags)
1314 : SkCanvasPageRenderer(page, width, height, flags),
1315 stream_(std::move(stream)),
1316 document_(std::move(document)) {
1317 DCHECK(stream_);
1318 DCHECK(document_);
1319 }
1320
1321 bool HasOutput() const override { return has_output_; }
1322
1323 bool Start() override {
1324 if (!document_) {
1325 return false;
1326 }
1327
1328 DCHECK(!canvas_);
1329 canvas_ = document_->beginPage(width(), height());
1330 if (!canvas_) {
1331 return false;
1332 }
1333
1334 return SkCanvasPageRenderer::Start();
1335 }
1336
1337 void Finish(FPDF_FORMHANDLE form) override {
1338 SkCanvasPageRenderer::Finish(form);
1339
1340 DCHECK(canvas_);
1341 canvas_ = nullptr;
1342 document_->endPage();
1343
1344 has_output_ = true;
1345 }
1346
1347 bool Write(const std::string& /*name*/,
1348 int /*page_index*/,
1349 bool /*md5*/) override {
1350 bool success = HasOutput();
1351 if (success) {
1352 document_->close();
1353 } else {
1354 document_->abort();
1355 }
1356
1357 document_.reset();
1358 stream_.reset();
1359 return success;
1360 }
1361
1362 protected:
1363 SkCanvas* canvas() override { return canvas_; }
1364
1365 private:
1366 std::unique_ptr<SkWStream> stream_;
1367 sk_sp<SkDocument> document_;
1368
1369 SkCanvas* canvas_ = nullptr;
1370 bool has_output_ = false;
1371};
1372#endif // PDF_ENABLE_SKIA
1373
1374bool PdfProcessor::ProcessPage(const int page_index) {
1375 FPDF_PAGE page = GetPage(page_index);
1376 if (!page) {
1377 return false;
1378 }
1379
1380 if (options().send_events) {
1381 SendPageEvents(form(), page, events(), idler());
1382 }
1383 if (options().save_images) {
1384 WriteImages(page, name().c_str(), page_index);
1385 }
1386 if (options().save_rendered_images) {
1387 WriteRenderedImages(doc(), page, name().c_str(), page_index);
1388 }
1389 if (options().save_thumbnails) {
1390 WriteThumbnail(page, name().c_str(), page_index);
1391 }
1392 if (options().save_thumbnails_decoded) {
1393 WriteDecodedThumbnailStream(page, name().c_str(), page_index);
1394 }
1395 if (options().save_thumbnails_raw) {
1396 WriteRawThumbnailStream(page, name().c_str(), page_index);
1397 }
1398 if (options().output_format == OutputFormat::kPageInfo) {
1399 DumpPageInfo(page, page_index);
1400 return true;
1401 }
1402 if (options().output_format == OutputFormat::kStructure) {
1403 DumpPageStructure(page, page_index);
1404 return true;
1405 }
1406
1407 ScopedFPDFTextPage text_page(FPDFText_LoadPage(page));
1408 double scale = 1.0;
1409 if (!options().scale_factor_as_string.empty()) {
1410 std::stringstream(options().scale_factor_as_string) >> scale;
1411 }
1412
1413 int width = static_cast<int>(FPDF_GetPageWidthF(page) * scale);
1414 int height = static_cast<int>(FPDF_GetPageHeightF(page) * scale);
1415 int flags = PageRenderFlagsFromOptions(options());
1416
1417 std::unique_ptr<PageRenderer> renderer;
1418 BitmapPageRenderer::PageWriter writer;
1419 switch (options().output_format) {
1420 case OutputFormat::kText:
1421 writer = BitmapPageRenderer::WrapPageWriter(WriteText);
1422 break;
1423
1424 case OutputFormat::kAnnot:
1425 writer = BitmapPageRenderer::WrapPageWriter(WriteAnnot);
1426 break;
1427
1428 case OutputFormat::kPpm:
1429 writer = BitmapPageRenderer::WrapPageWriter(WritePpm);
1430 break;
1431
1432 case OutputFormat::kPng:
1433 writer = BitmapPageRenderer::WrapPageWriter(WritePng);
1434 break;
1435
1436#ifdef _WIN32
1437 case OutputFormat::kBmp:
1438 writer = BitmapPageRenderer::WrapPageWriter(WriteBmp);
1439 break;
1440
1441 case OutputFormat::kEmf:
1442 // TODO(crbug.com/pdfium/2054): Render directly to DC.
1443 writer = BitmapPageRenderer::WrapPageWriter(WriteEmf);
1444 break;
1445
1446 case OutputFormat::kPs2:
1447 case OutputFormat::kPs3:
1448 // TODO(crbug.com/pdfium/2054): Render directly to DC.
1449 writer = BitmapPageRenderer::WrapPageWriter(WritePS);
1450 break;
1451#endif // _WIN32
1452
1453#ifdef PDF_ENABLE_SKIA
1454 case OutputFormat::kSkp:
1455 renderer = std::make_unique<SkPicturePageRenderer>(
1456 page, /*width=*/width, /*height=*/height, /*flags=*/flags);
1457 break;
1458
1459#ifdef _WIN32
1460 case OutputFormat::kXps: {
1461 IXpsOMObjectFactory* xps_factory = com_factory().GetXpsOMObjectFactory();
1462 if (!xps_factory) {
1463 break;
1464 }
1465
1466 std::unique_ptr<SkWStream> stream =
1467 WriteToSkWStream(name(), page_index, "xps");
1468 if (!stream) {
1469 break;
1470 }
1471
1472 sk_sp<SkDocument> document =
1473 SkXPS::MakeDocument(stream.get(), xps_factory);
1474 if (!document) {
1475 break;
1476 }
1477
1478 renderer = std::make_unique<SkDocumentPageRenderer>(
1479 std::move(stream), std::move(document), page, width, height, flags);
1480 break;
1481 }
1482#endif // _WIN32
1483#endif // PDF_ENABLE_SKIA
1484
1485 default:
1486 // Other formats won't write the output to a file, but still rasterize.
1487 break;
1488 }
1489
1490#ifdef _WIN32
1491 if (!renderer && options().use_renderer_type == RendererType::kGdi) {
1492 renderer = std::make_unique<GdiDisplayPageRenderer>(
1493 page, /*width=*/width, /*height=*/height, /*flags=*/flags, idler(),
1494 std::move(writer));
1495 }
1496#endif // _WIN32
1497
1498 if (!renderer) {
1499 // Use a rasterizing page renderer by default.
1500 if (options().render_oneshot) {
1501 renderer = std::make_unique<OneShotBitmapPageRenderer>(
1502 page, /*width=*/width, /*height=*/height, /*flags=*/flags, idler(),
1503 std::move(writer));
1504 } else {
1505 // Client programs will be setting these values when rendering.
1506 // This is a sample color scheme with distinct colors.
1507 // Used only when `options().forced_color` is true.
1508 FPDF_COLORSCHEME color_scheme;
1509 color_scheme.path_fill_color = 0xFFFF0000;
1510 color_scheme.path_stroke_color = 0xFF00FF00;
1511 color_scheme.text_fill_color = 0xFF0000FF;
1512 color_scheme.text_stroke_color = 0xFF00FFFF;
1513
1514 renderer = std::make_unique<ProgressiveBitmapPageRenderer>(
1515 page, /*width=*/width, /*height=*/height, /*flags=*/flags, idler(),
1516 std::move(writer), options().forced_color ? &color_scheme : nullptr);
1517 }
1518 }
1519
1520 if (renderer->Start()) {
1521 while (renderer->Continue())
1522 continue;
1523 renderer->Finish(form());
1524 renderer->Write(name(), page_index, /*md5=*/options().md5);
1525 } else {
1526 fprintf(stderr, "Page was too large to be rendered.\n");
1527 }
1528
1530 Idle();
1531
1532 FORM_OnBeforeClosePage(page, form());
1533 Idle();
1534
1535 return renderer->HasOutput();
1536}
1537
1538void Processor::ProcessPdf(const std::string& name,
1539 pdfium::span<const uint8_t> data,
1540 const std::string& events) {
1541 TestLoader loader(data);
1542
1543 FPDF_FILEACCESS file_access = {};
1544 file_access.m_FileLen = static_cast<unsigned long>(data.size());
1545 file_access.m_GetBlock = TestLoader::GetBlock;
1546 file_access.m_Param = &loader;
1547
1548 FX_FILEAVAIL file_avail = {};
1549 file_avail.version = 1;
1550 file_avail.IsDataAvail = Is_Data_Avail;
1551
1552 FX_DOWNLOADHINTS hints = {};
1553 hints.version = 1;
1554 hints.AddSegment = Add_Segment;
1555
1556 // |pdf_avail| must outlive |doc|.
1557 ScopedFPDFAvail pdf_avail(FPDFAvail_Create(&file_avail, &file_access));
1558
1559 // |doc| must outlive |form_callbacks.loaded_pages|.
1560 ScopedFPDFDocument doc;
1561
1562 const char* password =
1563 options().password.empty() ? nullptr : options().password.c_str();
1564 bool is_linearized = false;
1565 if (options().use_load_mem_document) {
1566 doc.reset(FPDF_LoadMemDocument(data.data(), data.size(), password));
1567 } else {
1568 if (FPDFAvail_IsLinearized(pdf_avail.get()) == PDF_LINEARIZED) {
1569 int avail_status = PDF_DATA_NOTAVAIL;
1570 doc.reset(FPDFAvail_GetDocument(pdf_avail.get(), password));
1571 if (doc) {
1572 while (avail_status == PDF_DATA_NOTAVAIL)
1573 avail_status = FPDFAvail_IsDocAvail(pdf_avail.get(), &hints);
1574
1575 if (avail_status == PDF_DATA_ERROR) {
1576 fprintf(stderr, "Unknown error in checking if doc was available.\n");
1577 return;
1578 }
1579 avail_status = FPDFAvail_IsFormAvail(pdf_avail.get(), &hints);
1580 if (avail_status == PDF_FORM_ERROR ||
1581 avail_status == PDF_FORM_NOTAVAIL) {
1582 fprintf(stderr,
1583 "Error %d was returned in checking if form was available.\n",
1584 avail_status);
1585 return;
1586 }
1587 is_linearized = true;
1588 }
1589 } else {
1590 doc.reset(FPDF_LoadCustomDocument(&file_access, password));
1591 }
1592 }
1593
1594 if (!doc) {
1595 PrintLastError();
1596 return;
1597 }
1598
1599 if (!FPDF_DocumentHasValidCrossReferenceTable(doc.get()))
1600 fprintf(stderr, "Document has invalid cross reference table\n");
1601
1602 if (options().show_metadata) {
1603 DumpMetaData(doc.get());
1604 }
1605
1606 if (options().save_attachments) {
1607 WriteAttachments(doc.get(), name);
1608 }
1609
1610#ifdef PDF_ENABLE_V8
1611 IPDF_JSPLATFORM platform_callbacks = {};
1612 platform_callbacks.version = 3;
1613 platform_callbacks.app_alert = ExampleAppAlert;
1614 platform_callbacks.app_beep = ExampleAppBeep;
1615 platform_callbacks.app_response = ExampleAppResponse;
1616 platform_callbacks.Doc_getFilePath = ExampleDocGetFilePath;
1617 platform_callbacks.Doc_mail = ExampleDocMail;
1618 platform_callbacks.Doc_print = ExampleDocPrint;
1619 platform_callbacks.Doc_submitForm = ExampleDocSubmitForm;
1620 platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
1621 platform_callbacks.Field_browse = ExampleFieldBrowse;
1622#endif // PDF_ENABLE_V8
1623
1624 FPDF_FORMFILLINFO_PDFiumTest form_callbacks = {};
1625#ifdef PDF_ENABLE_XFA
1626 form_callbacks.version = 2;
1627 form_callbacks.xfa_disabled =
1628 options().disable_xfa || options().disable_javascript;
1629 form_callbacks.FFI_PopupMenu = ExamplePopupMenu;
1630#else // PDF_ENABLE_XFA
1631 form_callbacks.version = 1;
1632#endif // PDF_ENABLE_XFA
1633 form_callbacks.FFI_ExecuteNamedAction = ExampleNamedAction;
1634 form_callbacks.FFI_GetPage = GetPageForIndex;
1635
1636#ifdef PDF_ENABLE_V8
1637 if (!options().disable_javascript) {
1638 form_callbacks.m_pJsPlatform = &platform_callbacks;
1639 }
1640#endif // PDF_ENABLE_V8
1641
1642 ScopedFPDFFormHandle form(
1643 FPDFDOC_InitFormFillEnvironment(doc.get(), &form_callbacks));
1644 form_callbacks.form_handle = form.get();
1645
1646#ifdef PDF_ENABLE_XFA
1647 if (!options().disable_xfa && !options().disable_javascript) {
1648 int doc_type = FPDF_GetFormType(doc.get());
1649 if (doc_type == FORMTYPE_XFA_FULL || doc_type == FORMTYPE_XFA_FOREGROUND) {
1650 if (!FPDF_LoadXFA(doc.get()))
1651 fprintf(stderr, "LoadXFA unsuccessful, continuing anyway.\n");
1652 }
1653 }
1654#endif // PDF_ENABLE_XFA
1655
1656 FPDF_SetFormFieldHighlightColor(form.get(), FPDF_FORMFIELD_UNKNOWN, 0xFFE4DD);
1657 FPDF_SetFormFieldHighlightAlpha(form.get(), 100);
1658 FORM_DoDocumentJSAction(form.get());
1659 FORM_DoDocumentOpenAction(form.get());
1660
1661#if _WIN32
1662 if (options().output_format == OutputFormat::kPs2) {
1663 FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT2);
1664 } else if (options().output_format == OutputFormat::kPs3) {
1665 FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT3);
1666 } else if (options().output_format == OutputFormat::kPs3Type42) {
1667 FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT3_TYPE42);
1668 }
1669#endif
1670
1671 int page_count = FPDF_GetPageCount(doc.get());
1672 int processed_pages = 0;
1673 int bad_pages = 0;
1674 int first_page = options().pages ? options().first_page : 0;
1675 int last_page = options().pages ? options().last_page + 1 : page_count;
1676 PdfProcessor pdf_processor(this, &name, &events, doc.get(), form.get(),
1677 &form_callbacks);
1678 for (int i = first_page; i < last_page; ++i) {
1679 if (is_linearized) {
1680 int avail_status = PDF_DATA_NOTAVAIL;
1681 while (avail_status == PDF_DATA_NOTAVAIL)
1682 avail_status = FPDFAvail_IsPageAvail(pdf_avail.get(), i, &hints);
1683
1684 if (avail_status == PDF_DATA_ERROR) {
1685 fprintf(stderr, "Unknown error in checking if page %d is available.\n",
1686 i);
1687 return;
1688 }
1689 }
1690 if (pdf_processor.ProcessPage(i)) {
1691 ++processed_pages;
1692 } else {
1693 ++bad_pages;
1694 }
1695 Idle();
1696 }
1697
1698 FORM_DoDocumentAAction(form.get(), FPDFDOC_AACTION_WC);
1699 Idle();
1700
1701 fprintf(stderr, "Processed %d pages.\n", processed_pages);
1702 if (bad_pages)
1703 fprintf(stderr, "Skipped %d bad pages.\n", bad_pages);
1704}
1705
1706void ShowConfig() {
1707 std::string config;
1708 [[maybe_unused]] auto append_config = [&config](const char* name) {
1709 if (!config.empty())
1710 config += ',';
1711 config += name;
1712 };
1713
1714#ifdef PDF_ENABLE_V8
1715 append_config("V8");
1716#endif
1717#ifdef V8_USE_EXTERNAL_STARTUP_DATA
1718 append_config("V8_EXTERNAL");
1719#endif
1720#ifdef PDF_ENABLE_XFA
1721 append_config("XFA");
1722#endif
1723#ifdef PDF_ENABLE_ASAN
1724 append_config("ASAN");
1725#endif
1726#ifdef PDF_ENABLE_SKIA
1727 append_config("SKIA");
1728#endif
1729#ifdef _WIN32
1730 append_config("GDI");
1731#endif
1732 printf("%s\n", config.c_str());
1733}
1734
1735constexpr char kUsageString[] =
1736 "Usage: pdfium_test [OPTION] [FILE]...\n"
1737 " --show-config - print build options and exit\n"
1738 " --show-metadata - print the file metadata\n"
1739 " --show-pageinfo - print information about pages\n"
1740 " --show-structure - print the structure elements from the "
1741 "document\n"
1742 " --send-events - send input described by .evt file\n"
1743 " --mem-document - load document with FPDF_LoadMemDocument()\n"
1744 " --render-oneshot - render image without using progressive "
1745 "renderer\n"
1746 " --lcd-text - render text optimized for LCD displays\n"
1747 " --no-nativetext - render without using the native text output\n"
1748 " --grayscale - render grayscale output\n"
1749 " --forced-color - render in forced color mode\n"
1750 " --fill-to-stroke - render fill as stroke in forced color mode\n"
1751 " --limit-cache - render limiting image cache size\n"
1752 " --force-halftone - render forcing halftone\n"
1753 " --printing - render as if for printing\n"
1754 " --no-smoothtext - render disabling text anti-aliasing\n"
1755 " --no-smoothimage - render disabling image anti-alisasing\n"
1756 " --no-smoothpath - render disabling path anti-aliasing\n"
1757 " --reverse-byte-order - render to BGRA, if supported by the output "
1758 "format\n"
1759 " --save-attachments - write embedded attachments "
1760 "<pdf-name>.attachment.<attachment-name>\n"
1761 " --save-images - write raw embedded images "
1762 "<pdf-name>.<page-number>.<object-number>.png\n"
1763 " --save-rendered-images - write embedded images as rendered on the page "
1764 "<pdf-name>.<page-number>.<object-number>.png\n"
1765 " --save-thumbs - write page thumbnails "
1766 "<pdf-name>.thumbnail.<page-number>.png\n"
1767 " --save-thumbs-dec - write page thumbnails' decoded stream data"
1768 "<pdf-name>.thumbnail.decoded.<page-number>.png\n"
1769 " --save-thumbs-raw - write page thumbnails' raw stream data"
1770 "<pdf-name>.thumbnail.raw.<page-number>.png\n"
1771
1772#if defined(PDF_ENABLE_SKIA)
1773#ifdef _WIN32
1774 " --use-renderer - renderer to use, one of [agg | gdi | skia]\n"
1775#else
1776 " --use-renderer - renderer to use, one of [agg | skia]\n"
1777#endif // _WIN32
1778#else
1779#ifdef _WIN32
1780 " --use-renderer - renderer to use, one of [agg | gdi]\n"
1781#else
1782 " --use-renderer - renderer to use, one of [agg]\n"
1783#endif // _WIN32
1784#endif // defined(PDF_ENABLE_SKIA)
1785
1786#ifdef PDF_ENABLE_V8
1787 " --disable-javascript - do not execute JS in PDF files\n"
1788 " --js-flags=<flags> - additional flags to pass to V8\n"
1789#ifdef PDF_ENABLE_XFA
1790 " --disable-xfa - do not process XFA forms\n"
1791#endif // PDF_ENABLE_XFA
1792#endif // PDF_ENABLE_V8
1793#ifdef ENABLE_CALLGRIND
1794 " --callgrind-delim - delimit interesting section when using "
1795 "callgrind\n"
1796#endif
1797#if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
1798 " --no-system-fonts - do not use system fonts, overrides --font-dir\n"
1799#endif
1800 " --croscore-font-names - use Croscore font names\n"
1801 " --bin-dir=<path> - override path to v8 external data\n"
1802 " --font-dir=<path> - override path to external fonts\n"
1803 " --scale=<number> - scale output size by number (e.g. 0.5)\n"
1804 " --password=<secret> - password to decrypt the PDF with\n"
1805 " --pages=<number>(-<number>) - only render the given 0-based page(s)\n"
1806#ifdef _WIN32
1807 " --bmp - write page images <pdf-name>.<page-number>.bmp\n"
1808 " --emf - write page meta files <pdf-name>.<page-number>.emf\n"
1809 " --ps2 - write page raw PostScript (Lvl 2) "
1810 "<pdf-name>.<page-number>.ps\n"
1811 " --ps3 - write page raw PostScript (Lvl 3) "
1812 "<pdf-name>.<page-number>.ps\n"
1813 " --ps3-type42 - write page raw PostScript (Lvl 3 with Type 42 fonts) "
1814 "<pdf-name>.<page-number>.ps\n"
1815#endif
1816 " --txt - write page text in UTF32-LE <pdf-name>.<page-number>.txt\n"
1817 " --png - write page images <pdf-name>.<page-number>.png\n"
1818 " --ppm - write page images <pdf-name>.<page-number>.ppm\n"
1819 " --annot - write annotation info <pdf-name>.<page-number>.annot.txt\n"
1820#ifdef PDF_ENABLE_SKIA
1821 " --skp - write page images <pdf-name>.<page-number>.skp\n"
1822#ifdef _WIN32
1823 " --xps - write page images <pdf-name>.<page-number>.xps\n"
1824#endif // _WIN32
1825#endif // PDF_ENABLE_SKIA
1826 " --md5 - write output image paths and their md5 hashes to stdout.\n"
1827 " --time=<number> - Seconds since the epoch to set system time.\n"
1828 "";
1829
1830void SetUpErrorHandling() {
1831#ifdef _WIN32
1832 // Suppress various Windows error reporting mechanisms that can pop up dialog
1833 // boxes and cause the program to hang.
1834 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
1835 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
1836 _set_error_mode(_OUT_TO_STDERR);
1837 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1838 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
1839 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1840#endif // _WIN32
1841}
1842
1843} // namespace
1844
1845int main(int argc, const char* argv[]) {
1846#if defined(PDF_USE_PARTITION_ALLOC)
1847 pdfium::ConfigurePartitionAllocShimPartitionForTest();
1848#endif
1849
1850 SetUpErrorHandling();
1851 setlocale(LC_CTYPE, "en_US.UTF-8"); // For printf() of high-characters.
1852
1853 std::vector<std::string> args(argv, argv + argc);
1854 Options options;
1855 std::vector<std::string> files;
1856 if (!ParseCommandLine(args, &options, &files)) {
1857 fprintf(stderr, "%s", kUsageString);
1858 return 1;
1859 }
1860
1861 if (options.show_config) {
1862 ShowConfig();
1863 return 0;
1864 }
1865
1866 if (files.empty()) {
1867 fprintf(stderr, "No input files.\n");
1868 return 1;
1869 }
1870
1871 FPDF_LIBRARY_CONFIG config;
1872 config.version = 4;
1873 config.m_pUserFontPaths = nullptr;
1874 config.m_pIsolate = nullptr;
1875 config.m_v8EmbedderSlot = 0;
1876 config.m_pPlatform = nullptr;
1877
1878 switch (options.use_renderer_type) {
1879 case RendererType::kDefault:
1880 config.m_RendererType = GetDefaultRendererType();
1881 break;
1882
1883 case RendererType::kAgg:
1884 config.m_RendererType = FPDF_RENDERERTYPE_AGG;
1885 break;
1886
1887#ifdef _WIN32
1888 case RendererType::kGdi:
1889 // GDI renderer uses `FPDF_RenderPage()`, rather than a renderer type.
1890 config.m_RendererType = GetDefaultRendererType();
1891 break;
1892#endif // _WIN32
1893
1894#if defined(PDF_ENABLE_SKIA)
1895 case RendererType::kSkia:
1896#if defined(BUILD_WITH_CHROMIUM)
1897 // Needed to support Chromium's copy of Skia, which uses a
1898 // `DiscardableMemoryAllocator`.
1899 chromium_support::InitializeDiscardableMemoryAllocator();
1900#endif // defined(BUILD_WITH_CHROMIUM)
1901 config.m_RendererType = FPDF_RENDERERTYPE_SKIA;
1902 break;
1903#endif // defined(PDF_ENABLE_SKIA)
1904 }
1905
1906 std::function<void()> idler = []() {};
1907#ifdef PDF_ENABLE_V8
1908#ifdef V8_USE_EXTERNAL_STARTUP_DATA
1909 v8::StartupData snapshot;
1910#endif // V8_USE_EXTERNAL_STARTUP_DATA
1911 std::unique_ptr<v8::Platform> platform;
1912 std::unique_ptr<v8::Isolate, V8IsolateDeleter> isolate;
1913 if (!options.disable_javascript) {
1914#ifdef V8_USE_EXTERNAL_STARTUP_DATA
1915 platform = InitializeV8ForPDFiumWithStartupData(
1916 options.exe_path, options.js_flags, options.bin_directory, &snapshot);
1917#else // V8_USE_EXTERNAL_STARTUP_DATA
1918 platform = InitializeV8ForPDFium(options.exe_path, options.js_flags);
1919#endif // V8_USE_EXTERNAL_STARTUP_DATA
1920 if (!platform) {
1921 fprintf(stderr, "V8 initialization failed.\n");
1922 return 1;
1923 }
1924 config.m_pPlatform = platform.get();
1925
1926 v8::Isolate::CreateParams params;
1927 params.array_buffer_allocator = static_cast<v8::ArrayBuffer::Allocator*>(
1928 FPDF_GetArrayBufferAllocatorSharedInstance());
1929 isolate.reset(v8::Isolate::New(params));
1930 config.m_pIsolate = isolate.get();
1931
1932 idler = [&platform, &isolate]() {
1933 int task_count = 0;
1934 while (v8::platform::PumpMessageLoop(platform.get(), isolate.get()))
1935 ++task_count;
1936 if (task_count)
1937 fprintf(stderr, "Pumped %d tasks\n", task_count);
1938 };
1939 }
1940#endif // PDF_ENABLE_V8
1941
1942 const char* path_array[2] = {nullptr, nullptr};
1943 std::optional<const char*> custom_font_path = GetCustomFontPath(options);
1944 if (custom_font_path.has_value()) {
1945 path_array[0] = custom_font_path.value();
1946 config.m_pUserFontPaths = path_array;
1947 }
1948
1950
1951 {
1952 std::unique_ptr<FontRenamer> font_renamer;
1953 if (options.croscore_font_names) {
1954 // Must be destroyed before FPDF_DestroyLibrary().
1955 font_renamer = std::make_unique<FontRenamer>();
1956 }
1957
1958 UNSUPPORT_INFO unsupported_info = {};
1959 unsupported_info.version = 1;
1960 unsupported_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
1961
1962 FSDK_SetUnSpObjProcessHandler(&unsupported_info);
1963
1964 if (options.time > -1) {
1965 // This must be a static var to avoid explicit capture, so the lambda can
1966 // be converted to a function ptr.
1967 static time_t time_ret = options.time;
1968 FSDK_SetTimeFunction([]() { return time_ret; });
1969 FSDK_SetLocaltimeFunction([](const time_t* tp) { return gmtime(tp); });
1970 }
1971
1972 Processor processor(&options, &idler);
1973 for (const std::string& filename : files) {
1974 std::vector<uint8_t> file_contents = GetFileContents(filename.c_str());
1975 if (file_contents.empty()) {
1976 continue;
1977 }
1978 fprintf(stderr, "Processing PDF file %s.\n", filename.c_str());
1979
1980#ifdef ENABLE_CALLGRIND
1981 if (options.callgrind_delimiters) {
1982 CALLGRIND_START_INSTRUMENTATION;
1983 }
1984#endif // ENABLE_CALLGRIND
1985
1986 std::string events;
1987 if (options.send_events) {
1988 std::string event_filename = filename;
1989 size_t extension_pos = event_filename.find(".pdf");
1990 if (extension_pos != std::string::npos) {
1991 event_filename.replace(extension_pos, 4, ".evt");
1992 if (access(event_filename.c_str(), R_OK) == 0) {
1993 fprintf(stderr, "Using event file %s.\n", event_filename.c_str());
1994 std::vector<uint8_t> event_contents =
1995 GetFileContents(event_filename.c_str());
1996 if (!event_contents.empty()) {
1997 fprintf(stderr, "Sending events from: %s\n",
1998 event_filename.c_str());
1999 std::copy(event_contents.begin(), event_contents.end(),
2000 std::back_inserter(events));
2001 }
2002 }
2003 }
2004 }
2005
2006 processor.ProcessPdf(filename, file_contents, events);
2007
2008#ifdef ENABLE_CALLGRIND
2009 if (options.callgrind_delimiters) {
2010 CALLGRIND_STOP_INSTRUMENTATION;
2011 }
2012#endif // ENABLE_CALLGRIND
2013 }
2014 }
2015
2017
2018#ifdef PDF_ENABLE_V8
2019 if (!options.disable_javascript) {
2020 isolate.reset();
2021 ShutdownV8ForPDFium();
2022#ifdef V8_USE_EXTERNAL_STARTUP_DATA
2023 free(const_cast<char*>(snapshot.data));
2024#endif // V8_USE_EXTERNAL_STARTUP_DATA
2025 }
2026#endif // PDF_ENABLE_V8
2027
2028 return 0;
2029}
#define DCHECK
Definition check.h:33
PageRenderer(FPDF_PAGE page, int width, int height, int flags)
int width() const
int height() const
FPDF_PAGE page()
int flags() const
static bool DirectoryExists(const std::string &path)
static int GetBlock(void *param, unsigned long pos, unsigned char *pBuf, unsigned long size)
FPDF_RENDERER_TYPE GetDefaultRendererType()
#define UNSAFE_TODO(...)
void DumpPageStructure(FPDF_PAGE page, int page_idx)
Definition dump.cc:233
void DumpPageInfo(FPDF_PAGE page, int page_idx)
Definition dump.cc:225
void SendPageEvents(FPDF_FORMHANDLE form, FPDF_PAGE page, const std::string &events, const std::function< void()> &idler)
Definition event.cc:162
#define PDF_FORM_NOTAVAIL
#define PDF_DATA_NOTAVAIL
#define PDF_DATA_ERROR
#define PDF_LINEARIZED
#define PDF_FORM_ERROR
FPDF_EXPORT FPDF_AVAIL FPDF_CALLCONV FPDFAvail_Create(FX_FILEAVAIL *file_avail, FPDF_FILEACCESS *file)
#define FPDF_UNSP_DOC_PORTABLECOLLECTION
Definition fpdf_ext.h:22
#define FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
Definition fpdf_ext.h:44
#define FPDF_UNSP_ANNOT_ATTACHMENT
Definition fpdf_ext.h:46
#define FPDF_UNSP_DOC_SECURITY
Definition fpdf_ext.h:26
#define FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
Definition fpdf_ext.h:32
FPDF_EXPORT void FPDF_CALLCONV FSDK_SetLocaltimeFunction(struct tm *(*func)(const time_t *))
Definition fpdf_ext.cpp:80
FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FSDK_SetUnSpObjProcessHandler(UNSUPPORT_INFO *unsp_info)
Definition fpdf_ext.cpp:67
#define FPDF_UNSP_DOC_ATTACHMENT
Definition fpdf_ext.h:24
#define FPDF_UNSP_ANNOT_SIG
Definition fpdf_ext.h:48
#define FPDF_UNSP_ANNOT_SOUND
Definition fpdf_ext.h:40
#define FPDF_UNSP_DOC_SHAREDFORM_EMAIL
Definition fpdf_ext.h:34
#define FPDF_UNSP_DOC_XFAFORM
Definition fpdf_ext.h:20
#define FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
Definition fpdf_ext.h:30
#define FPDF_UNSP_ANNOT_3DANNOT
Definition fpdf_ext.h:36
#define FPDF_UNSP_ANNOT_MOVIE
Definition fpdf_ext.h:38
FPDF_EXPORT void FPDF_CALLCONV FSDK_SetTimeFunction(time_t(*func)())
Definition fpdf_ext.cpp:75
#define FPDF_UNSP_ANNOT_SCREEN_MEDIA
Definition fpdf_ext.h:42
#define FPDF_UNSP_DOC_SHAREDREVIEW
Definition fpdf_ext.h:28
#define FPDFDOC_AACTION_WC
FPDF_EXPORT void FPDF_CALLCONV FORM_OnAfterLoadPage(FPDF_PAGE page, FPDF_FORMHANDLE hHandle)
FPDF_EXPORT void FPDF_CALLCONV FORM_OnBeforeClosePage(FPDF_PAGE page, FPDF_FORMHANDLE hHandle)
#define FPDFPAGE_AACTION_CLOSE
FPDF_EXPORT void FPDF_CALLCONV FORM_DoPageAAction(FPDF_PAGE page, FPDF_FORMHANDLE hHandle, int aaType)
#define FPDF_FORMFIELD_UNKNOWN
#define FPDFPAGE_AACTION_OPEN
#define FPDF_RENDER_TOBECONTINUED
FPDF_EXPORT FPDF_TEXTPAGE FPDF_CALLCONV FPDFText_LoadPage(FPDF_PAGE page)
Definition fpdf_text.cpp:43
FPDF_EXPORT FPDF_PAGE FPDF_CALLCONV FPDF_LoadPage(FPDF_DOCUMENT document, int page_index)
FPDF_EXPORT unsigned long FPDF_CALLCONV FPDF_GetLastError()
FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV FPDF_LoadCustomDocument(FPDF_FILEACCESS *pFileAccess, FPDF_BYTESTRING password)
FPDF_EXPORT float FPDF_CALLCONV FPDF_GetPageHeightF(FPDF_PAGE page)
FPDF_EXPORT void FPDF_CALLCONV FPDF_DestroyLibrary()
FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetStride(FPDF_BITMAP bitmap)
FPDF_EXPORT void FPDF_CALLCONV FPDF_InitLibraryWithConfig(const FPDF_LIBRARY_CONFIG *config)
FPDF_EXPORT void *FPDF_CALLCONV FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap)
FPDF_EXPORT float FPDF_CALLCONV FPDF_GetPageWidthF(FPDF_PAGE page)
#define FPDF_RENDER_LIMITEDIMAGECACHE
Definition fpdfview.h:803
#define FPDF_RENDER_NO_SMOOTHTEXT
Definition fpdfview.h:810
#define FPDF_ERR_FILE
Definition fpdfview.h:585
#define FPDF_ERR_SECURITY
Definition fpdfview.h:588
#define FPDF_PRINTING
Definition fpdfview.h:807
#define FPDFBitmap_BGRx
Definition fpdfview.h:1088
#define FPDF_RENDER_NO_SMOOTHIMAGE
Definition fpdfview.h:812
#define FPDF_CONVERT_FILL_TO_STROKE
Definition fpdfview.h:821
#define FPDF_REVERSE_BYTE_ORDER
Definition fpdfview.h:817
#define FPDFBitmap_BGRA
Definition fpdfview.h:1090
#define FPDF_ERR_UNKNOWN
Definition fpdfview.h:584
#define FPDF_ERR_PASSWORD
Definition fpdfview.h:587
#define FPDF_ERR_PAGE
Definition fpdfview.h:589
#define FPDF_RENDER_FORCEHALFTONE
Definition fpdfview.h:805
#define FPDF_ERR_FORMAT
Definition fpdfview.h:586
#define FPDF_ERR_SUCCESS
Definition fpdfview.h:583
#define FPDF_GRAYSCALE
Definition fpdfview.h:797
#define FPDF_NO_NATIVETEXT
Definition fpdfview.h:795
#define FPDF_ANNOT
Definition fpdfview.h:790
#define FPDF_LCD_TEXT
Definition fpdfview.h:793
#define FPDF_RENDER_NO_SMOOTHPATH
Definition fpdfview.h:814
int main(int argc, const char *argv[])
void(* FFI_ExecuteNamedAction)(struct _FPDF_FORMFILLINFO *pThis, FPDF_BYTESTRING namedAction)
void(* AddSegment)(struct _FX_DOWNLOADHINTS *pThis, size_t offset, size_t size)
void(* FSDK_UnSupport_Handler)(struct _UNSUPPORT_INFO *pThis, int nType)
Definition fpdf_ext.h:61
void WriteAnnot(FPDF_PAGE page, const char *pdf_name, int num)
Definition write.cc:339
std::string WritePng(const char *pdf_name, int num, void *buffer, int stride, int width, int height)
Definition write.cc:451
void WriteText(FPDF_TEXTPAGE textpage, const char *pdf_name, int num)
Definition write.cc:310
std::string WritePpm(const char *pdf_name, int num, void *buffer_void, int stride, int width, int height)
Definition write.cc:259