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