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 "../fpdfsdk/include/fpdf_dataavail.h"
17 #include "../fpdfsdk/include/fpdf_ext.h"
18 #include "../fpdfsdk/include/fpdfformfill.h"
19 #include "../fpdfsdk/include/fpdftext.h"
20 #include "../fpdfsdk/include/fpdfview.h"
21 #include "../core/include/fxcrt/fx_system.h"
22 #include "image_diff_png.h"
23 #include "v8/include/v8.h"
24 #include "v8/include/libplatform/libplatform.h"
27 #define snprintf _snprintf
28 #define PATH_SEPARATOR '\\'
30 #define PATH_SEPARATOR '/'
44 Options() : output_format(OUTPUT_NONE) { }
46 OutputFormat output_format;
47 std::string scale_factor_as_string;
49 std::string bin_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);
64 (void) fseek(file, 0, SEEK_SET);
65 char* buffer = (char*) malloc(file_length);
69 size_t bytes_read = fread(buffer, 1, file_length, file);
71 if (bytes_read != file_length) {
72 fprintf(stderr, "Failed to read: %s\n", filename);
80 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
81 // Returns the full path for an external V8 data file based on either
82 // the currect exectuable path or an explicit override.
83 static std::string GetFullPathForSnapshotFile(const Options& options,
84 const std::string& filename) {
86 if (!options.bin_directory.empty()) {
87 result = options.bin_directory;
88 if (*options.bin_directory.rbegin() != PATH_SEPARATOR) {
89 result += PATH_SEPARATOR;
91 } else if (!options.exe_path.empty()) {
92 size_t last_separator = options.exe_path.rfind(PATH_SEPARATOR);
93 if (last_separator != std::string::npos) {
94 result = options.exe_path.substr(0, last_separator + 1);
101 // Reads an extenal V8 data file from the |options|-indicated location,
102 // returing true on success and false on error.
103 static bool GetExternalData(const Options& options,
104 const std::string& bin_filename,
105 v8::StartupData* result_data) {
106 std::string full_path = GetFullPathForSnapshotFile(options, bin_filename);
107 size_t data_length = 0;
108 char* data_buffer = GetFileContents(full_path.c_str(), &data_length);
112 result_data->data = const_cast<const char*>(data_buffer);
113 result_data->raw_size = static_cast<int>(data_length);
116 #endif // V8_USE_EXTERNAL_STARTUP_DATA
118 static bool CheckDimensions(int stride, int width, int height) {
119 if (stride < 0 || width < 0 || height < 0)
121 if (height > 0 && width > INT_MAX / height)
126 static void WritePpm(const char* pdf_name, int num, const void* buffer_void,
127 int stride, int width, int height) {
128 const char* buffer = reinterpret_cast<const char*>(buffer_void);
130 if (!CheckDimensions(stride, width, height))
133 int out_len = width * height;
134 if (out_len > INT_MAX / 3)
139 snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num);
140 FILE* fp = fopen(filename, "wb");
143 fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height);
144 // Source data is B, G, R, unused.
145 // Dest data is R, G, B.
146 char* result = new char[out_len];
148 for (int h = 0; h < height; ++h) {
149 const char* src_line = buffer + (stride * h);
150 char* dest_line = result + (width * h * 3);
151 for (int w = 0; w < width; ++w) {
153 dest_line[w * 3] = src_line[(w * 4) + 2];
155 dest_line[(w * 3) + 1] = src_line[(w * 4) + 1];
157 dest_line[(w * 3) + 2] = src_line[w * 4];
160 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");
219 BITMAPINFO bmi = {0};
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 = {0};
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(NULL, filename, NULL, NULL);
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 (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;
353 else if (cur_arg == "--emf") {
354 if (options->output_format != OUTPUT_NONE) {
355 fprintf(stderr, "Duplicate or conflicting --emf argument\n");
358 options->output_format = OUTPUT_EMF;
360 else if (cur_arg == "--bmp") {
361 if (options->output_format != OUTPUT_NONE) {
362 fprintf(stderr, "Duplicate or conflicting --bmp argument\n");
365 options->output_format = OUTPUT_BMP;
368 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
369 else if (cur_arg.size() > 10 && cur_arg.compare(0, 10, "--bin-dir=") == 0) {
370 if (!options->bin_directory.empty()) {
371 fprintf(stderr, "Duplicate --bin-dir argument\n");
374 options->bin_directory = cur_arg.substr(10);
376 #endif // V8_USE_EXTERNAL_STARTUP_DATA
377 else if (cur_arg.size() > 8 && cur_arg.compare(0, 8, "--scale=") == 0) {
378 if (!options->scale_factor_as_string.empty()) {
379 fprintf(stderr, "Duplicate --scale argument\n");
382 options->scale_factor_as_string = cur_arg.substr(8);
387 if (cur_idx >= args.size()) {
388 fprintf(stderr, "No input files.\n");
391 for (size_t i = cur_idx; i < args.size(); i++) {
392 files->push_back(args[i]);
399 TestLoader(const char* pBuf, size_t len);
405 TestLoader::TestLoader(const char* pBuf, size_t len)
406 : m_pBuf(pBuf), m_Len(len) {
409 int Get_Block(void* param, unsigned long pos, unsigned char* pBuf,
410 unsigned long size) {
411 TestLoader* pLoader = (TestLoader*) param;
412 if (pos + size < pos || pos + size > pLoader->m_Len) return 0;
413 memcpy(pBuf, pLoader->m_pBuf + pos, size);
417 bool Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) {
421 void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) {
424 void RenderPdf(const std::string& name, const char* pBuf, size_t len,
425 const Options& options) {
426 fprintf(stderr, "Rendering PDF file %s.\n", name.c_str());
428 IPDF_JSPLATFORM platform_callbacks;
429 memset(&platform_callbacks, '\0', sizeof(platform_callbacks));
430 platform_callbacks.version = 1;
431 platform_callbacks.app_alert = ExampleAppAlert;
432 platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
434 FPDF_FORMFILLINFO form_callbacks;
435 memset(&form_callbacks, '\0', sizeof(form_callbacks));
436 form_callbacks.version = 1;
437 form_callbacks.m_pJsPlatform = &platform_callbacks;
439 TestLoader loader(pBuf, len);
441 FPDF_FILEACCESS file_access;
442 memset(&file_access, '\0', sizeof(file_access));
443 file_access.m_FileLen = static_cast<unsigned long>(len);
444 file_access.m_GetBlock = Get_Block;
445 file_access.m_Param = &loader;
447 FX_FILEAVAIL file_avail;
448 memset(&file_avail, '\0', sizeof(file_avail));
449 file_avail.version = 1;
450 file_avail.IsDataAvail = Is_Data_Avail;
452 FX_DOWNLOADHINTS hints;
453 memset(&hints, '\0', sizeof(hints));
455 hints.AddSegment = Add_Segment;
458 FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access);
460 (void) FPDFAvail_IsDocAvail(pdf_avail, &hints);
462 if (!FPDFAvail_IsLinearized(pdf_avail)) {
463 fprintf(stderr, "Non-linearized path...\n");
464 doc = FPDF_LoadCustomDocument(&file_access, NULL);
466 fprintf(stderr, "Linearized path...\n");
467 doc = FPDFAvail_GetDocument(pdf_avail, NULL);
470 (void) FPDF_GetDocPermissions(doc);
471 (void) FPDFAvail_IsFormAvail(pdf_avail, &hints);
473 FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnvironment(doc, &form_callbacks);
474 FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD);
475 FPDF_SetFormFieldHighlightAlpha(form, 100);
477 int first_page = FPDFAvail_GetFirstPageNum(doc);
478 (void) FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints);
480 int page_count = FPDF_GetPageCount(doc);
481 for (int i = 0; i < page_count; ++i) {
482 (void) FPDFAvail_IsPageAvail(pdf_avail, i, &hints);
485 FORM_DoDocumentJSAction(form);
486 FORM_DoDocumentOpenAction(form);
488 size_t rendered_pages = 0;
489 size_t bad_pages = 0;
490 for (int i = 0; i < page_count; ++i) {
491 FPDF_PAGE page = FPDF_LoadPage(doc, i);
496 FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page);
497 FORM_OnAfterLoadPage(page, form);
498 FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN);
501 if (!options.scale_factor_as_string.empty()) {
502 std::stringstream(options.scale_factor_as_string) >> scale;
504 int width = static_cast<int>(FPDF_GetPageWidth(page) * scale);
505 int height = static_cast<int>(FPDF_GetPageHeight(page) * scale);
507 FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
508 FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
509 FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
512 FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0);
513 int stride = FPDFBitmap_GetStride(bitmap);
515 reinterpret_cast<const char*>(FPDFBitmap_GetBuffer(bitmap));
517 switch (options.output_format) {
520 WriteBmp(name.c_str(), i, buffer, stride, width, height);
524 WriteEmf(page, name.c_str(), i);
528 WritePng(name.c_str(), i, buffer, stride, width, height);
532 WritePpm(name.c_str(), i, buffer, stride, width, height);
539 FPDFBitmap_Destroy(bitmap);
541 FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
542 FORM_OnBeforeClosePage(page, form);
543 FPDFText_ClosePage(text_page);
544 FPDF_ClosePage(page);
547 FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC);
548 FPDFDOC_ExitFormFillEnvironment(form);
549 FPDF_CloseDocument(doc);
550 FPDFAvail_Destroy(pdf_avail);
552 fprintf(stderr, "Rendered %" PRIuS " pages.\n", rendered_pages);
553 fprintf(stderr, "Skipped %" PRIuS " bad pages.\n", bad_pages);
556 static const char usage_string[] =
557 "Usage: pdfium_test [OPTION] [FILE]...\n"
558 " --bin-dir=<path> - override path to v8 external data\n"
559 " --scale=<number> - scale output size by number (e.g. 0.5)\n"
561 " --bmp - write page images <pdf-name>.<page-number>.bmp\n"
562 " --emf - write page meta files <pdf-name>.<page-number>.emf\n"
564 " --png - write page images <pdf-name>.<page-number>.png\n"
565 " --ppm - write page images <pdf-name>.<page-number>.ppm\n";
567 int main(int argc, const char* argv[]) {
568 std::vector<std::string> args(argv, argv + argc);
570 std::list<std::string> files;
571 if (!ParseCommandLine(args, &options, &files)) {
572 fprintf(stderr, "%s", usage_string);
576 v8::V8::InitializeICU();
577 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
578 v8::V8::InitializePlatform(platform);
579 v8::V8::Initialize();
581 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
582 v8::StartupData natives;
583 v8::StartupData snapshot;
584 if (!GetExternalData(options, "natives_blob.bin", &natives) ||
585 !GetExternalData(options, "snapshot_blob.bin", &snapshot)) {
588 v8::V8::SetNativesDataBlob(&natives);
589 v8::V8::SetSnapshotDataBlob(&snapshot);
590 #endif // V8_USE_EXTERNAL_STARTUP_DATA
594 UNSUPPORT_INFO unsuppored_info;
595 memset(&unsuppored_info, '\0', sizeof(unsuppored_info));
596 unsuppored_info.version = 1;
597 unsuppored_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
599 FSDK_SetUnSpObjProcessHandler(&unsuppored_info);
601 while (!files.empty()) {
602 std::string filename = files.front();
604 size_t file_length = 0;
605 char* file_contents = GetFileContents(filename.c_str(), &file_length);
608 RenderPdf(filename, file_contents, file_length, options);
612 FPDF_DestroyLibrary();
613 v8::V8::ShutdownPlatform();