pdfium_engine_exports.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // Copyright 2018 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.
  4. #include "pdf/pdfium/pdfium_engine_exports.h"
  5. #include <algorithm>
  6. #include <utility>
  7. #include "base/bind.h"
  8. #include "base/no_destructor.h"
  9. #include "base/numerics/safe_conversions.h"
  10. #include "build/build_config.h"
  11. #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
  12. #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
  13. #include "pdf/pdfium/pdfium_print.h"
  14. #include "pdf/pdfium/pdfium_unsupported_features.h"
  15. #include "printing/nup_parameters.h"
  16. #include "printing/units.h"
  17. #include "third_party/abseil-cpp/absl/types/optional.h"
  18. #include "third_party/pdfium/public/cpp/fpdf_scopers.h"
  19. #include "third_party/pdfium/public/fpdf_catalog.h"
  20. #include "third_party/pdfium/public/fpdf_ppo.h"
  21. #include "third_party/pdfium/public/fpdf_structtree.h"
  22. #include "third_party/pdfium/public/fpdfview.h"
  23. #include "ui/gfx/geometry/rect.h"
  24. #include "ui/gfx/geometry/size.h"
  25. #include "ui/gfx/geometry/size_f.h"
  26. #include "ui/gfx/geometry/vector2d.h"
  27. using printing::ConvertUnitFloat;
  28. using printing::kPointsPerInch;
  29. namespace chrome_pdf {
  30. namespace {
  31. int CalculatePosition(FPDF_PAGE page,
  32. const PDFiumEngineExports::RenderingSettings& settings,
  33. gfx::Rect* dest) {
  34. // settings.bounds is in terms of the max DPI. Convert page sizes to match.
  35. const int dpi_x = settings.dpi.width();
  36. const int dpi_y = settings.dpi.height();
  37. const int dpi = std::max(dpi_x, dpi_y);
  38. int page_width = static_cast<int>(
  39. ConvertUnitFloat(FPDF_GetPageWidthF(page), kPointsPerInch, dpi));
  40. int page_height = static_cast<int>(
  41. ConvertUnitFloat(FPDF_GetPageHeightF(page), kPointsPerInch, dpi));
  42. // Start by assuming that we will draw exactly to the bounds rect
  43. // specified.
  44. *dest = settings.bounds;
  45. int rotate = 0; // normal orientation.
  46. // Auto-rotate landscape pages to print correctly.
  47. if (settings.autorotate &&
  48. (dest->width() > dest->height()) != (page_width > page_height)) {
  49. rotate = 3; // 90 degrees counter-clockwise.
  50. std::swap(page_width, page_height);
  51. }
  52. // See if we need to scale the output
  53. bool scale_to_bounds = false;
  54. if (settings.fit_to_bounds &&
  55. ((page_width > dest->width()) || (page_height > dest->height()))) {
  56. scale_to_bounds = true;
  57. } else if (settings.stretch_to_bounds &&
  58. ((page_width < dest->width()) || (page_height < dest->height()))) {
  59. scale_to_bounds = true;
  60. }
  61. if (scale_to_bounds) {
  62. // If we need to maintain aspect ratio, calculate the actual width and
  63. // height.
  64. if (settings.keep_aspect_ratio) {
  65. double scale_factor_x = page_width;
  66. scale_factor_x /= dest->width();
  67. double scale_factor_y = page_height;
  68. scale_factor_y /= dest->height();
  69. if (scale_factor_x > scale_factor_y) {
  70. dest->set_height(page_height / scale_factor_x);
  71. } else {
  72. dest->set_width(page_width / scale_factor_y);
  73. }
  74. }
  75. } else {
  76. // We are not scaling to bounds. Draw in the actual page size. If the
  77. // actual page size is larger than the bounds, the output will be
  78. // clipped.
  79. dest->set_width(page_width);
  80. dest->set_height(page_height);
  81. }
  82. // Scale the bounds to device units if DPI is rectangular.
  83. if (dpi_x != dpi_y) {
  84. dest->set_width(dest->width() * dpi_x / dpi);
  85. dest->set_height(dest->height() * dpi_y / dpi);
  86. }
  87. if (settings.center_in_bounds) {
  88. gfx::Vector2d offset(
  89. (settings.bounds.width() * dpi_x / dpi - dest->width()) / 2,
  90. (settings.bounds.height() * dpi_y / dpi - dest->height()) / 2);
  91. dest->Offset(offset);
  92. }
  93. return rotate;
  94. }
  95. ScopedFPDFDocument LoadPdfData(base::span<const uint8_t> pdf_buffer) {
  96. if (!base::IsValueInRangeForNumericType<int>(pdf_buffer.size()))
  97. return nullptr;
  98. return ScopedFPDFDocument(
  99. FPDF_LoadMemDocument(pdf_buffer.data(), pdf_buffer.size(), nullptr));
  100. }
  101. ScopedFPDFDocument CreatePdfDoc(
  102. std::vector<base::span<const uint8_t>> input_buffers) {
  103. if (input_buffers.empty())
  104. return nullptr;
  105. ScopedFPDFDocument doc(FPDF_CreateNewDocument());
  106. size_t index = 0;
  107. for (auto input_buffer : input_buffers) {
  108. ScopedFPDFDocument single_page_doc = LoadPdfData(input_buffer);
  109. if (!FPDF_ImportPages(doc.get(), single_page_doc.get(), "1", index++)) {
  110. return nullptr;
  111. }
  112. }
  113. return doc;
  114. }
  115. bool IsValidPrintableArea(const gfx::Size& page_size,
  116. const gfx::Rect& printable_area) {
  117. return !printable_area.IsEmpty() && printable_area.x() >= 0 &&
  118. printable_area.y() >= 0 &&
  119. printable_area.right() <= page_size.width() &&
  120. printable_area.bottom() <= page_size.height();
  121. }
  122. int GetRenderFlagsFromSettings(
  123. const PDFiumEngineExports::RenderingSettings& settings) {
  124. int flags = FPDF_ANNOT;
  125. if (!settings.use_color)
  126. flags |= FPDF_GRAYSCALE;
  127. if (settings.render_for_printing)
  128. flags |= FPDF_PRINTING;
  129. return flags;
  130. }
  131. base::Value RecursiveGetStructTree(FPDF_STRUCTELEMENT struct_elem) {
  132. int children_count = FPDF_StructElement_CountChildren(struct_elem);
  133. if (children_count <= 0)
  134. return base::Value(base::Value::Type::NONE);
  135. absl::optional<std::u16string> opt_type =
  136. CallPDFiumWideStringBufferApiAndReturnOptional(
  137. base::BindRepeating(FPDF_StructElement_GetType, struct_elem), true);
  138. if (!opt_type)
  139. return base::Value(base::Value::Type::NONE);
  140. base::Value::Dict result;
  141. result.Set("type", *opt_type);
  142. absl::optional<std::u16string> opt_alt =
  143. CallPDFiumWideStringBufferApiAndReturnOptional(
  144. base::BindRepeating(FPDF_StructElement_GetAltText, struct_elem),
  145. true);
  146. if (opt_alt)
  147. result.Set("alt", *opt_alt);
  148. absl::optional<std::u16string> opt_lang =
  149. CallPDFiumWideStringBufferApiAndReturnOptional(
  150. base::BindRepeating(FPDF_StructElement_GetLang, struct_elem), true);
  151. if (opt_lang)
  152. result.Set("lang", *opt_lang);
  153. base::Value::List children;
  154. for (int i = 0; i < children_count; i++) {
  155. FPDF_STRUCTELEMENT child_elem =
  156. FPDF_StructElement_GetChildAtIndex(struct_elem, i);
  157. base::Value child = RecursiveGetStructTree(child_elem);
  158. if (child.is_dict())
  159. children.Append(std::move(child));
  160. }
  161. // use "~children" instead of "children" because we pretty-print the
  162. // result of this as JSON and the keys are sorted; it's much easier to
  163. // understand when the children are the last key.
  164. if (!children.empty())
  165. result.Set("~children", std::move(children));
  166. return base::Value(std::move(result));
  167. }
  168. } // namespace
  169. PDFEngineExports::RenderingSettings::RenderingSettings(const gfx::Size& dpi,
  170. const gfx::Rect& bounds,
  171. bool fit_to_bounds,
  172. bool stretch_to_bounds,
  173. bool keep_aspect_ratio,
  174. bool center_in_bounds,
  175. bool autorotate,
  176. bool use_color,
  177. bool render_for_printing)
  178. : dpi(dpi),
  179. bounds(bounds),
  180. fit_to_bounds(fit_to_bounds),
  181. stretch_to_bounds(stretch_to_bounds),
  182. keep_aspect_ratio(keep_aspect_ratio),
  183. center_in_bounds(center_in_bounds),
  184. autorotate(autorotate),
  185. use_color(use_color),
  186. render_for_printing(render_for_printing) {}
  187. PDFEngineExports::RenderingSettings::RenderingSettings(
  188. const RenderingSettings& that) = default;
  189. PDFEngineExports* PDFEngineExports::Get() {
  190. static base::NoDestructor<PDFiumEngineExports> exports;
  191. return exports.get();
  192. }
  193. PDFiumEngineExports::PDFiumEngineExports() {}
  194. PDFiumEngineExports::~PDFiumEngineExports() {}
  195. #if BUILDFLAG(IS_CHROMEOS)
  196. std::vector<uint8_t> PDFiumEngineExports::CreateFlattenedPdf(
  197. base::span<const uint8_t> input_buffer) {
  198. ScopedUnsupportedFeature scoped_unsupported_feature(
  199. ScopedUnsupportedFeature::kNoEngine);
  200. ScopedFPDFDocument doc = LoadPdfData(input_buffer);
  201. if (!doc)
  202. return std::vector<uint8_t>();
  203. return PDFiumPrint::CreateFlattenedPdf(std::move(doc));
  204. }
  205. #endif // BUILDFLAG(IS_CHROMEOS)
  206. #if BUILDFLAG(IS_WIN)
  207. bool PDFiumEngineExports::RenderPDFPageToDC(
  208. base::span<const uint8_t> pdf_buffer,
  209. int page_number,
  210. const RenderingSettings& settings,
  211. HDC dc) {
  212. ScopedUnsupportedFeature scoped_unsupported_feature(
  213. ScopedUnsupportedFeature::kNoEngine);
  214. ScopedFPDFDocument doc = LoadPdfData(pdf_buffer);
  215. if (!doc)
  216. return false;
  217. ScopedFPDFPage page(FPDF_LoadPage(doc.get(), page_number));
  218. if (!page)
  219. return false;
  220. RenderingSettings new_settings = settings;
  221. // calculate the page size
  222. if (new_settings.dpi.width() == -1)
  223. new_settings.dpi.set_width(GetDeviceCaps(dc, LOGPIXELSX));
  224. if (new_settings.dpi.height() == -1)
  225. new_settings.dpi.set_height(GetDeviceCaps(dc, LOGPIXELSY));
  226. gfx::Rect dest;
  227. int rotate = CalculatePosition(page.get(), new_settings, &dest);
  228. int save_state = SaveDC(dc);
  229. // The caller wanted all drawing to happen within the bounds specified.
  230. // Based on scale calculations, our destination rect might be larger
  231. // than the bounds. Set the clip rect to the bounds.
  232. IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
  233. settings.bounds.x() + settings.bounds.width(),
  234. settings.bounds.y() + settings.bounds.height());
  235. int flags = GetRenderFlagsFromSettings(settings);
  236. // A "temporary" hack. Some PDFs seems to render very slowly if
  237. // FPDF_RenderPage() is directly used on a printer DC. I suspect it is
  238. // because of the code to talk Postscript directly to the printer if
  239. // the printer supports this. Need to discuss this with PDFium. For now,
  240. // render to a bitmap and then blit the bitmap to the DC if we have been
  241. // supplied a printer DC.
  242. int device_type = GetDeviceCaps(dc, TECHNOLOGY);
  243. if (device_type == DT_RASPRINTER || device_type == DT_PLOTTER) {
  244. ScopedFPDFBitmap bitmap(
  245. FPDFBitmap_Create(dest.width(), dest.height(), FPDFBitmap_BGRx));
  246. // Clear the bitmap
  247. FPDFBitmap_FillRect(bitmap.get(), 0, 0, dest.width(), dest.height(),
  248. 0xFFFFFFFF);
  249. FPDF_RenderPageBitmap(bitmap.get(), page.get(), 0, 0, dest.width(),
  250. dest.height(), rotate, flags);
  251. int stride = FPDFBitmap_GetStride(bitmap.get());
  252. BITMAPINFO bmi;
  253. memset(&bmi, 0, sizeof(bmi));
  254. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  255. bmi.bmiHeader.biWidth = dest.width();
  256. bmi.bmiHeader.biHeight = -dest.height(); // top-down image
  257. bmi.bmiHeader.biPlanes = 1;
  258. bmi.bmiHeader.biBitCount = 32;
  259. bmi.bmiHeader.biCompression = BI_RGB;
  260. bmi.bmiHeader.biSizeImage = stride * dest.height();
  261. StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(), 0, 0,
  262. dest.width(), dest.height(),
  263. FPDFBitmap_GetBuffer(bitmap.get()), &bmi, DIB_RGB_COLORS,
  264. SRCCOPY);
  265. } else {
  266. FPDF_RenderPage(dc, page.get(), dest.x(), dest.y(), dest.width(),
  267. dest.height(), rotate, flags);
  268. }
  269. RestoreDC(dc, save_state);
  270. return true;
  271. }
  272. void PDFiumEngineExports::SetPDFUsePrintMode(int mode) {
  273. FPDF_SetPrintMode(mode);
  274. }
  275. #endif // BUILDFLAG(IS_WIN)
  276. bool PDFiumEngineExports::RenderPDFPageToBitmap(
  277. base::span<const uint8_t> pdf_buffer,
  278. int page_number,
  279. const RenderingSettings& settings,
  280. void* bitmap_buffer) {
  281. ScopedUnsupportedFeature scoped_unsupported_feature(
  282. ScopedUnsupportedFeature::kNoEngine);
  283. ScopedFPDFDocument doc = LoadPdfData(pdf_buffer);
  284. if (!doc)
  285. return false;
  286. ScopedFPDFPage page(FPDF_LoadPage(doc.get(), page_number));
  287. if (!page)
  288. return false;
  289. gfx::Rect dest;
  290. int rotate = CalculatePosition(page.get(), settings, &dest);
  291. ScopedFPDFBitmap bitmap(FPDFBitmap_CreateEx(
  292. settings.bounds.width(), settings.bounds.height(), FPDFBitmap_BGRA,
  293. bitmap_buffer, settings.bounds.width() * 4));
  294. // Clear the bitmap
  295. FPDFBitmap_FillRect(bitmap.get(), 0, 0, settings.bounds.width(),
  296. settings.bounds.height(), 0xFFFFFFFF);
  297. // Shift top-left corner of bounds to (0, 0) if it's not there.
  298. dest.set_origin(dest.origin() - settings.bounds.OffsetFromOrigin());
  299. FPDF_RenderPageBitmap(bitmap.get(), page.get(), dest.x(), dest.y(),
  300. dest.width(), dest.height(), rotate,
  301. GetRenderFlagsFromSettings(settings));
  302. return true;
  303. }
  304. std::vector<uint8_t> PDFiumEngineExports::ConvertPdfPagesToNupPdf(
  305. std::vector<base::span<const uint8_t>> input_buffers,
  306. size_t pages_per_sheet,
  307. const gfx::Size& page_size,
  308. const gfx::Rect& printable_area) {
  309. if (!IsValidPrintableArea(page_size, printable_area))
  310. return std::vector<uint8_t>();
  311. ScopedUnsupportedFeature scoped_unsupported_feature(
  312. ScopedUnsupportedFeature::kNoEngine);
  313. ScopedFPDFDocument doc = CreatePdfDoc(std::move(input_buffers));
  314. if (!doc)
  315. return std::vector<uint8_t>();
  316. return PDFiumPrint::CreateNupPdf(std::move(doc), pages_per_sheet, page_size,
  317. printable_area);
  318. }
  319. std::vector<uint8_t> PDFiumEngineExports::ConvertPdfDocumentToNupPdf(
  320. base::span<const uint8_t> input_buffer,
  321. size_t pages_per_sheet,
  322. const gfx::Size& page_size,
  323. const gfx::Rect& printable_area) {
  324. if (!IsValidPrintableArea(page_size, printable_area))
  325. return std::vector<uint8_t>();
  326. ScopedUnsupportedFeature scoped_unsupported_feature(
  327. ScopedUnsupportedFeature::kNoEngine);
  328. ScopedFPDFDocument doc = LoadPdfData(input_buffer);
  329. if (!doc)
  330. return std::vector<uint8_t>();
  331. return PDFiumPrint::CreateNupPdf(std::move(doc), pages_per_sheet, page_size,
  332. printable_area);
  333. }
  334. bool PDFiumEngineExports::GetPDFDocInfo(base::span<const uint8_t> pdf_buffer,
  335. int* page_count,
  336. float* max_page_width) {
  337. ScopedUnsupportedFeature scoped_unsupported_feature(
  338. ScopedUnsupportedFeature::kNoEngine);
  339. ScopedFPDFDocument doc = LoadPdfData(pdf_buffer);
  340. if (!doc)
  341. return false;
  342. if (!page_count && !max_page_width)
  343. return true;
  344. int page_count_local = FPDF_GetPageCount(doc.get());
  345. if (page_count)
  346. *page_count = page_count_local;
  347. if (max_page_width) {
  348. *max_page_width = 0;
  349. for (int page_number = 0; page_number < page_count_local; page_number++) {
  350. FS_SIZEF page_size;
  351. if (FPDF_GetPageSizeByIndexF(doc.get(), page_number, &page_size) &&
  352. page_size.width > *max_page_width) {
  353. *max_page_width = page_size.width;
  354. }
  355. }
  356. }
  357. return true;
  358. }
  359. absl::optional<bool> PDFiumEngineExports::IsPDFDocTagged(
  360. base::span<const uint8_t> pdf_buffer) {
  361. ScopedUnsupportedFeature scoped_unsupported_feature(
  362. ScopedUnsupportedFeature::kNoEngine);
  363. ScopedFPDFDocument doc = LoadPdfData(pdf_buffer);
  364. if (!doc)
  365. return absl::nullopt;
  366. return FPDFCatalog_IsTagged(doc.get());
  367. }
  368. base::Value PDFiumEngineExports::GetPDFStructTreeForPage(
  369. base::span<const uint8_t> pdf_buffer,
  370. int page_index) {
  371. ScopedUnsupportedFeature scoped_unsupported_feature(
  372. ScopedUnsupportedFeature::kNoEngine);
  373. ScopedFPDFDocument doc = LoadPdfData(pdf_buffer);
  374. if (!doc)
  375. return base::Value(base::Value::Type::NONE);
  376. ScopedFPDFPage page(FPDF_LoadPage(doc.get(), page_index));
  377. if (!page)
  378. return base::Value(base::Value::Type::NONE);
  379. ScopedFPDFStructTree struct_tree(FPDF_StructTree_GetForPage(page.get()));
  380. if (!struct_tree)
  381. return base::Value(base::Value::Type::NONE);
  382. // We only expect one child of the struct tree - i.e. a single root node.
  383. int children = FPDF_StructTree_CountChildren(struct_tree.get());
  384. if (children != 1)
  385. return base::Value(base::Value::Type::NONE);
  386. FPDF_STRUCTELEMENT struct_root_elem =
  387. FPDF_StructTree_GetChildAtIndex(struct_tree.get(), 0);
  388. if (!struct_root_elem)
  389. return base::Value(base::Value::Type::NONE);
  390. return RecursiveGetStructTree(struct_root_elem);
  391. }
  392. absl::optional<gfx::SizeF> PDFiumEngineExports::GetPDFPageSizeByIndex(
  393. base::span<const uint8_t> pdf_buffer,
  394. int page_number) {
  395. ScopedUnsupportedFeature scoped_unsupported_feature(
  396. ScopedUnsupportedFeature::kNoEngine);
  397. ScopedFPDFDocument doc = LoadPdfData(pdf_buffer);
  398. if (!doc)
  399. return absl::nullopt;
  400. FS_SIZEF size;
  401. if (!FPDF_GetPageSizeByIndexF(doc.get(), page_number, &size))
  402. return absl::nullopt;
  403. return gfx::SizeF(size.width, size.height);
  404. }
  405. } // namespace chrome_pdf