1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
16 #include "../public/fpdf_dataavail.h"
17 #include "../public/fpdf_ext.h"
18 #include "../public/fpdf_formfill.h"
19 #include "../public/fpdf_text.h"
20 #include "../public/fpdfview.h"
21 #include "image_diff_png.h"
22 #include "v8/include/libplatform/libplatform.h"
23 #include "v8/include/v8.h"
26 #define snprintf _snprintf
27 #define PATH_SEPARATOR '\\'
29 #define PATH_SEPARATOR '/'
43 Options() : output_format(OUTPUT_NONE) { }
45 OutputFormat output_format;
46 std::string scale_factor_as_string;
48 std::string bin_directory;
49 std::string font_directory;
52 // Reads the entire contents of a file into a newly malloc'd buffer.
53 static char* GetFileContents(const char* filename, size_t* retlen) {
54 FILE* file = fopen(filename, "rb");
56 fprintf(stderr, "Failed to open: %s\n", filename);
59 (void)fseek(file, 0, SEEK_END);
60 size_t file_length = ftell(file);
65 (void)fseek(file, 0, SEEK_SET);
66 char* buffer = static_cast<char*>(malloc(file_length));
71 size_t bytes_read = fread(buffer, 1, file_length, file);
73 if (bytes_read != file_length) {
74 fprintf(stderr, "Failed to read: %s\n", filename);
82 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
83 // Returns the full path for an external V8 data file based on either
84 // the currect exectuable path or an explicit override.
85 static std::string GetFullPathForSnapshotFile(const Options& options,
86 const std::string& filename) {
88 if (!options.bin_directory.empty()) {
89 result = options.bin_directory;
90 if (*options.bin_directory.rbegin() != PATH_SEPARATOR) {
91 result += PATH_SEPARATOR;
93 } else if (!options.exe_path.empty()) {
94 size_t last_separator = options.exe_path.rfind(PATH_SEPARATOR);
95 if (last_separator != std::string::npos) {
96 result = options.exe_path.substr(0, last_separator + 1);
103 // Reads an extenal V8 data file from the |options|-indicated location,
104 // returing true on success and false on error.
105 static bool GetExternalData(const Options& options,
106 const std::string& bin_filename,
107 v8::StartupData* result_data) {
108 std::string full_path = GetFullPathForSnapshotFile(options, bin_filename);
109 size_t data_length = 0;
110 char* data_buffer = GetFileContents(full_path.c_str(), &data_length);
114 result_data->data = const_cast<const char*>(data_buffer);
115 result_data->raw_size = static_cast<int>(data_length);
118 #endif // V8_USE_EXTERNAL_STARTUP_DATA
120 static bool CheckDimensions(int stride, int width, int height) {
121 if (stride < 0 || width < 0 || height < 0)
123 if (height > 0 && width > INT_MAX / height)
128 static void WritePpm(const char* pdf_name, int num, const void* buffer_void,
129 int stride, int width, int height) {
130 const char* buffer = reinterpret_cast<const char*>(buffer_void);
132 if (!CheckDimensions(stride, width, height))
135 int out_len = width * height;
136 if (out_len > INT_MAX / 3)
141 snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num);
142 FILE* fp = fopen(filename, "wb");
145 fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height);
146 // Source data is B, G, R, unused.
147 // Dest data is R, G, B.
148 char* result = new char[out_len];
149 for (int h = 0; h < height; ++h) {
150 const char* src_line = buffer + (stride * h);
151 char* dest_line = result + (width * h * 3);
152 for (int w = 0; w < width; ++w) {
154 dest_line[w * 3] = src_line[(w * 4) + 2];
156 dest_line[(w * 3) + 1] = src_line[(w * 4) + 1];
158 dest_line[(w * 3) + 2] = src_line[w * 4];
161 fwrite(result, out_len, 1, fp);
166 static void WritePng(const char* pdf_name, int num, const void* buffer_void,
167 int stride, int width, int height) {
168 if (!CheckDimensions(stride, width, height))
171 std::vector<unsigned char> png_encoding;
172 const unsigned char* buffer = static_cast<const unsigned char*>(buffer_void);
173 if (!image_diff_png::EncodeBGRAPNG(
174 buffer, width, height, stride, false, &png_encoding)) {
175 fprintf(stderr, "Failed to convert bitmap to PNG\n");
180 int chars_formatted = snprintf(
181 filename, sizeof(filename), "%s.%d.png", pdf_name, num);
182 if (chars_formatted < 0 ||
183 static_cast<size_t>(chars_formatted) >= sizeof(filename)) {
184 fprintf(stderr, "Filname %s is too long\n", filename);
188 FILE* fp = fopen(filename, "wb");
190 fprintf(stderr, "Failed to open %s for output\n", filename);
194 size_t bytes_written = fwrite(
195 &png_encoding.front(), 1, png_encoding.size(), fp);
196 if (bytes_written != png_encoding.size())
197 fprintf(stderr, "Failed to write to %s\n", filename);
203 static void WriteBmp(const char* pdf_name, int num, const void* buffer,
204 int stride, int width, int height) {
205 if (stride < 0 || width < 0 || height < 0)
207 if (height > 0 && width > INT_MAX / height)
209 int out_len = stride * height;
210 if (out_len > INT_MAX / 3)
214 snprintf(filename, sizeof(filename), "%s.%d.bmp", pdf_name, num);
215 FILE* fp = fopen(filename, "wb");
220 bmi.bmiHeader.biSize = sizeof(bmi) - sizeof(RGBQUAD);
221 bmi.bmiHeader.biWidth = width;
222 bmi.bmiHeader.biHeight = -height; // top-down image
223 bmi.bmiHeader.biPlanes = 1;
224 bmi.bmiHeader.biBitCount = 32;
225 bmi.bmiHeader.biCompression = BI_RGB;
226 bmi.bmiHeader.biSizeImage = 0;
228 BITMAPFILEHEADER file_header = {};
229 file_header.bfType = 0x4d42;
230 file_header.bfSize = sizeof(file_header) + bmi.bmiHeader.biSize + out_len;
231 file_header.bfOffBits = file_header.bfSize - out_len;
233 fwrite(&file_header, sizeof(file_header), 1, fp);
234 fwrite(&bmi, bmi.bmiHeader.biSize, 1, fp);
235 fwrite(buffer, out_len, 1, fp);
239 void WriteEmf(FPDF_PAGE page, const char* pdf_name, int num) {
240 int width = static_cast<int>(FPDF_GetPageWidth(page));
241 int height = static_cast<int>(FPDF_GetPageHeight(page));
244 snprintf(filename, sizeof(filename), "%s.%d.emf", pdf_name, num);
246 HDC dc = CreateEnhMetaFileA(nullptr, filename, nullptr, nullptr);
248 HRGN rgn = CreateRectRgn(0, 0, width, height);
249 SelectClipRgn(dc, rgn);
252 SelectObject(dc, GetStockObject(NULL_PEN));
253 SelectObject(dc, GetStockObject(WHITE_BRUSH));
254 // If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel less.
255 Rectangle(dc, 0, 0, width + 1, height + 1);
257 FPDF_RenderPage(dc, page, 0, 0, width, height, 0,
258 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
260 DeleteEnhMetaFile(CloseEnhMetaFile(dc));
264 int ExampleAppAlert(IPDF_JSPLATFORM*, FPDF_WIDESTRING msg, FPDF_WIDESTRING,
266 // Deal with differences between UTF16LE and wchar_t on this platform.
267 size_t characters = 0;
268 while (msg[characters]) {
271 wchar_t* platform_string =
272 static_cast<wchar_t*>(malloc((characters + 1) * sizeof(wchar_t)));
273 for (size_t i = 0; i < characters + 1; ++i) {
274 unsigned char* ptr = (unsigned char*)&msg[i];
275 platform_string[i] = ptr[0] + 256 * ptr[1];
277 printf("Alert: %ls\n", platform_string);
278 free(platform_string);
282 void ExampleDocGotoPage(IPDF_JSPLATFORM*, int pageNumber) {
283 printf("Goto Page: %d\n", pageNumber);
286 void ExampleUnsupportedHandler(UNSUPPORT_INFO*, int type) {
287 std::string feature = "Unknown";
289 case FPDF_UNSP_DOC_XFAFORM:
292 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
293 feature = "Portfolios_Packages";
295 case FPDF_UNSP_DOC_ATTACHMENT:
296 case FPDF_UNSP_ANNOT_ATTACHMENT:
297 feature = "Attachment";
299 case FPDF_UNSP_DOC_SECURITY:
300 feature = "Rights_Management";
302 case FPDF_UNSP_DOC_SHAREDREVIEW:
303 feature = "Shared_Review";
305 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
306 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
307 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
308 feature = "Shared_Form";
310 case FPDF_UNSP_ANNOT_3DANNOT:
313 case FPDF_UNSP_ANNOT_MOVIE:
316 case FPDF_UNSP_ANNOT_SOUND:
319 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
320 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
323 case FPDF_UNSP_ANNOT_SIG:
324 feature = "Digital_Signature";
327 printf("Unsupported feature: %s.\n", feature.c_str());
330 bool ParseCommandLine(const std::vector<std::string>& args,
331 Options* options, std::list<std::string>* files) {
335 options->exe_path = args[0];
337 for (; cur_idx < args.size(); ++cur_idx) {
338 const std::string& cur_arg = args[cur_idx];
339 if (cur_arg == "--ppm") {
340 if (options->output_format != OUTPUT_NONE) {
341 fprintf(stderr, "Duplicate or conflicting --ppm argument\n");
344 options->output_format = OUTPUT_PPM;
345 } else if (cur_arg == "--png") {
346 if (options->output_format != OUTPUT_NONE) {
347 fprintf(stderr, "Duplicate or conflicting --png argument\n");
350 options->output_format = OUTPUT_PNG;
351 } else if (cur_arg.size() > 11 &&
352 cur_arg.compare(0, 11, "--font-dir=") == 0) {
353 if (!options->font_directory.empty()) {
354 fprintf(stderr, "Duplicate --font-dir argument\n");
357 options->font_directory = cur_arg.substr(11);
361 else if (cur_arg == "--emf") {
362 if (options->output_format != OUTPUT_NONE) {
363 fprintf(stderr, "Duplicate or conflicting --emf argument\n");
366 options->output_format = OUTPUT_EMF;
368 else if (cur_arg == "--bmp") {
369 if (options->output_format != OUTPUT_NONE) {
370 fprintf(stderr, "Duplicate or conflicting --bmp argument\n");
373 options->output_format = OUTPUT_BMP;
376 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
377 else if (cur_arg.size() > 10 && cur_arg.compare(0, 10, "--bin-dir=") == 0) {
378 if (!options->bin_directory.empty()) {
379 fprintf(stderr, "Duplicate --bin-dir argument\n");
382 options->bin_directory = cur_arg.substr(10);
384 #endif // V8_USE_EXTERNAL_STARTUP_DATA
385 else if (cur_arg.size() > 8 && cur_arg.compare(0, 8, "--scale=") == 0) {
386 if (!options->scale_factor_as_string.empty()) {
387 fprintf(stderr, "Duplicate --scale argument\n");
390 options->scale_factor_as_string = cur_arg.substr(8);
395 if (cur_idx >= args.size()) {
396 fprintf(stderr, "No input files.\n");
399 for (size_t i = cur_idx; i < args.size(); i++) {
400 files->push_back(args[i]);
407 TestLoader(const char* pBuf, size_t len);
413 TestLoader::TestLoader(const char* pBuf, size_t len)
414 : m_pBuf(pBuf), m_Len(len) {
417 int GetBlock(void* param,
420 unsigned long size) {
421 TestLoader* pLoader = static_cast<TestLoader*>(param);
422 if (pos + size < pos || pos + size > pLoader->m_Len) return 0;
423 memcpy(pBuf, pLoader->m_pBuf + pos, size);
427 FPDF_BOOL Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) {
431 void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) {
434 void RenderPdf(const std::string& name, const char* pBuf, size_t len,
435 const Options& options) {
436 fprintf(stderr, "Rendering PDF file %s.\n", name.c_str());
438 IPDF_JSPLATFORM platform_callbacks;
439 memset(&platform_callbacks, '\0', sizeof(platform_callbacks));
440 platform_callbacks.version = 2;
441 platform_callbacks.app_alert = ExampleAppAlert;
442 platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
444 FPDF_FORMFILLINFO form_callbacks;
445 memset(&form_callbacks, '\0', sizeof(form_callbacks));
446 form_callbacks.version = 1;
447 form_callbacks.m_pJsPlatform = &platform_callbacks;
449 TestLoader loader(pBuf, len);
451 FPDF_FILEACCESS file_access;
452 memset(&file_access, '\0', sizeof(file_access));
453 file_access.m_FileLen = static_cast<unsigned long>(len);
454 file_access.m_GetBlock = GetBlock;
455 file_access.m_Param = &loader;
457 FX_FILEAVAIL file_avail;
458 memset(&file_avail, '\0', sizeof(file_avail));
459 file_avail.version = 1;
460 file_avail.IsDataAvail = Is_Data_Avail;
462 FX_DOWNLOADHINTS hints;
463 memset(&hints, '\0', sizeof(hints));
465 hints.AddSegment = Add_Segment;
468 FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access);
470 (void)FPDFAvail_IsDocAvail(pdf_avail, &hints);
472 if (FPDFAvail_IsLinearized(pdf_avail)) {
473 fprintf(stderr, "Linearized path...\n");
474 doc = FPDFAvail_GetDocument(pdf_avail, nullptr);
476 fprintf(stderr, "Non-linearized path...\n");
477 doc = FPDF_LoadCustomDocument(&file_access, nullptr);
481 fprintf(stderr, "Load pdf docs unsuccessful.\n");
485 (void)FPDF_GetDocPermissions(doc);
486 (void)FPDFAvail_IsFormAvail(pdf_avail, &hints);
488 FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnvironment(doc, &form_callbacks);
489 FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD);
490 FPDF_SetFormFieldHighlightAlpha(form, 100);
492 int first_page = FPDFAvail_GetFirstPageNum(doc);
493 (void)FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints);
495 int page_count = FPDF_GetPageCount(doc);
496 for (int i = 0; i < page_count; ++i) {
497 (void)FPDFAvail_IsPageAvail(pdf_avail, i, &hints);
500 FORM_DoDocumentJSAction(form);
501 FORM_DoDocumentOpenAction(form);
503 int rendered_pages = 0;
505 for (int i = 0; i < page_count; ++i) {
506 FPDF_PAGE page = FPDF_LoadPage(doc, i);
511 FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page);
512 FORM_OnAfterLoadPage(page, form);
513 FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN);
516 if (!options.scale_factor_as_string.empty()) {
517 std::stringstream(options.scale_factor_as_string) >> scale;
519 int width = static_cast<int>(FPDF_GetPageWidth(page) * scale);
520 int height = static_cast<int>(FPDF_GetPageHeight(page) * scale);
522 FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
524 fprintf(stderr, "Page was too large to be rendered.\n");
529 FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
530 FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
533 FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0);
534 int stride = FPDFBitmap_GetStride(bitmap);
536 reinterpret_cast<const char*>(FPDFBitmap_GetBuffer(bitmap));
538 switch (options.output_format) {
541 WriteBmp(name.c_str(), i, buffer, stride, width, height);
545 WriteEmf(page, name.c_str(), i);
549 WritePng(name.c_str(), i, buffer, stride, width, height);
553 WritePpm(name.c_str(), i, buffer, stride, width, height);
560 FPDFBitmap_Destroy(bitmap);
562 FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
563 FORM_OnBeforeClosePage(page, form);
564 FPDFText_ClosePage(text_page);
565 FPDF_ClosePage(page);
568 FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC);
569 FPDFDOC_ExitFormFillEnvironment(form);
570 FPDF_CloseDocument(doc);
571 FPDFAvail_Destroy(pdf_avail);
573 fprintf(stderr, "Rendered %d pages.\n", rendered_pages);
574 fprintf(stderr, "Skipped %d bad pages.\n", bad_pages);
577 static const char usage_string[] =
578 "Usage: pdfium_test [OPTION] [FILE]...\n"
579 " --bin-dir=<path> - override path to v8 external data\n"
580 " --font-dir=<path> - override path to external fonts\n"
581 " --scale=<number> - scale output size by number (e.g. 0.5)\n"
583 " --bmp - write page images <pdf-name>.<page-number>.bmp\n"
584 " --emf - write page meta files <pdf-name>.<page-number>.emf\n"
586 " --png - write page images <pdf-name>.<page-number>.png\n"
587 " --ppm - write page images <pdf-name>.<page-number>.ppm\n";
589 int main(int argc, const char* argv[]) {
590 std::vector<std::string> args(argv, argv + argc);
592 std::list<std::string> files;
593 if (!ParseCommandLine(args, &options, &files)) {
594 fprintf(stderr, "%s", usage_string);
598 v8::V8::InitializeICU();
599 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
600 v8::V8::InitializePlatform(platform);
601 v8::V8::Initialize();
603 // By enabling predictable mode, V8 won't post any background tasks.
604 static const char predictable_flag[] = "--predictable";
605 v8::V8::SetFlagsFromString(predictable_flag,
606 static_cast<int>(strlen(predictable_flag)));
608 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
609 v8::StartupData natives;
610 v8::StartupData snapshot;
611 if (!GetExternalData(options, "natives_blob.bin", &natives) ||
612 !GetExternalData(options, "snapshot_blob.bin", &snapshot)) {
615 v8::V8::SetNativesDataBlob(&natives);
616 v8::V8::SetSnapshotDataBlob(&snapshot);
617 #endif // V8_USE_EXTERNAL_STARTUP_DATA
619 if (options.font_directory.empty()) {
622 const char* path_array[2];
623 path_array[0] = options.font_directory.c_str();
624 path_array[1] = nullptr;
625 FPDF_LIBRARY_CONFIG config;
627 config.m_pUserFontPaths = path_array;
628 FPDF_InitLibraryWithConfig(&config);
631 UNSUPPORT_INFO unsuppored_info;
632 memset(&unsuppored_info, '\0', sizeof(unsuppored_info));
633 unsuppored_info.version = 1;
634 unsuppored_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
636 FSDK_SetUnSpObjProcessHandler(&unsuppored_info);
638 while (!files.empty()) {
639 std::string filename = files.front();
641 size_t file_length = 0;
642 char* file_contents = GetFileContents(filename.c_str(), &file_length);
645 RenderPdf(filename, file_contents, file_length, options);
649 FPDF_DestroyLibrary();
650 v8::V8::ShutdownPlatform();