Document.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibPDF/CommonNames.h>
  7. #include <LibPDF/Document.h>
  8. #include <LibPDF/Parser.h>
  9. namespace PDF {
  10. DeprecatedString OutlineItem::to_deprecated_string(int indent) const
  11. {
  12. auto indent_str = DeprecatedString::repeated(" "sv, indent + 1);
  13. StringBuilder child_builder;
  14. child_builder.append('[');
  15. for (auto& child : children)
  16. child_builder.appendff("{}\n", child->to_deprecated_string(indent + 1));
  17. child_builder.appendff("{}]", indent_str);
  18. StringBuilder builder;
  19. builder.append("OutlineItem {{\n"sv);
  20. builder.appendff("{}title={}\n", indent_str, title);
  21. builder.appendff("{}count={}\n", indent_str, count);
  22. builder.appendff("{}dest={}\n", indent_str, dest);
  23. builder.appendff("{}color={}\n", indent_str, color);
  24. builder.appendff("{}italic={}\n", indent_str, italic);
  25. builder.appendff("{}bold={}\n", indent_str, bold);
  26. builder.appendff("{}children={}\n", indent_str, child_builder.to_deprecated_string());
  27. builder.appendff("{}}}", DeprecatedString::repeated(" "sv, indent));
  28. return builder.to_deprecated_string();
  29. }
  30. PDFErrorOr<NonnullRefPtr<Document>> Document::create(ReadonlyBytes bytes)
  31. {
  32. auto parser = adopt_ref(*new DocumentParser({}, bytes));
  33. auto document = adopt_ref(*new Document(parser));
  34. TRY(parser->initialize());
  35. document->m_trailer = parser->trailer();
  36. document->m_catalog = TRY(parser->trailer()->get_dict(document, CommonNames::Root));
  37. if (document->m_trailer->contains(CommonNames::Encrypt)) {
  38. auto encryption_dict = TRY(document->m_trailer->get_dict(document, CommonNames::Encrypt));
  39. document->m_security_handler = TRY(SecurityHandler::create(document, encryption_dict));
  40. // Automatically attempt to unencrypt the document with the empty string. The
  41. // result is not important; it is the caller's responsibility to ensure the
  42. // document is unencrypted before calling initialize().
  43. document->m_security_handler->try_provide_user_password(""sv);
  44. }
  45. return document;
  46. }
  47. Document::Document(NonnullRefPtr<DocumentParser> const& parser)
  48. : m_parser(parser)
  49. {
  50. m_parser->set_document(this);
  51. }
  52. PDFErrorOr<void> Document::initialize()
  53. {
  54. if (m_security_handler)
  55. VERIFY(m_security_handler->has_user_password());
  56. TRY(build_page_tree());
  57. TRY(build_outline());
  58. return {};
  59. }
  60. PDFErrorOr<Value> Document::get_or_load_value(u32 index)
  61. {
  62. auto value = get_value(index);
  63. if (!value.has<Empty>()) // FIXME: Use Optional instead?
  64. return value;
  65. auto object = TRY(m_parser->parse_object_with_index(index));
  66. m_values.set(index, object);
  67. return object;
  68. }
  69. u32 Document::get_first_page_index() const
  70. {
  71. // FIXME: A PDF can have a different default first page, which
  72. // should be fetched and returned here
  73. return 0;
  74. }
  75. u32 Document::get_page_count() const
  76. {
  77. return m_page_object_indices.size();
  78. }
  79. PDFErrorOr<Page> Document::get_page(u32 index)
  80. {
  81. VERIFY(index < m_page_object_indices.size());
  82. auto cached_page = m_pages.get(index);
  83. if (cached_page.has_value())
  84. return cached_page.value();
  85. auto page_object_index = m_page_object_indices[index];
  86. auto page_object = TRY(get_or_load_value(page_object_index));
  87. auto raw_page_object = TRY(resolve_to<DictObject>(page_object));
  88. RefPtr<DictObject> resources;
  89. auto maybe_resources_object = TRY(get_inheritable_object(CommonNames::Resources, raw_page_object));
  90. if (maybe_resources_object.has_value())
  91. resources = maybe_resources_object.value()->cast<DictObject>();
  92. else
  93. resources = adopt_ref(*new DictObject({}));
  94. RefPtr<Object> contents;
  95. if (raw_page_object->contains(CommonNames::Contents))
  96. contents = TRY(raw_page_object->get_object(this, CommonNames::Contents));
  97. Rectangle media_box;
  98. auto maybe_media_box_object = TRY(get_inheritable_object(CommonNames::MediaBox, raw_page_object));
  99. if (maybe_media_box_object.has_value()) {
  100. auto media_box_array = maybe_media_box_object.value()->cast<ArrayObject>();
  101. media_box = Rectangle {
  102. media_box_array->at(0).to_float(),
  103. media_box_array->at(1).to_float(),
  104. media_box_array->at(2).to_float(),
  105. media_box_array->at(3).to_float(),
  106. };
  107. } else {
  108. // As most other libraries seem to do, we default to the standard
  109. // US letter size of 8.5" x 11" (612 x 792 Postscript units).
  110. media_box = Rectangle {
  111. 0, 0,
  112. 612, 792
  113. };
  114. }
  115. Rectangle crop_box;
  116. auto maybe_crop_box_object = TRY(get_inheritable_object(CommonNames::CropBox, raw_page_object));
  117. if (maybe_crop_box_object.has_value()) {
  118. auto crop_box_array = maybe_crop_box_object.value()->cast<ArrayObject>();
  119. crop_box = Rectangle {
  120. crop_box_array->at(0).to_float(),
  121. crop_box_array->at(1).to_float(),
  122. crop_box_array->at(2).to_float(),
  123. crop_box_array->at(3).to_float(),
  124. };
  125. } else {
  126. crop_box = media_box;
  127. }
  128. float user_unit = 1.0f;
  129. if (raw_page_object->contains(CommonNames::UserUnit))
  130. user_unit = raw_page_object->get_value(CommonNames::UserUnit).to_float();
  131. int rotate = 0;
  132. if (raw_page_object->contains(CommonNames::Rotate)) {
  133. rotate = raw_page_object->get_value(CommonNames::Rotate).get<int>();
  134. VERIFY(rotate % 90 == 0);
  135. }
  136. Page page { resources.release_nonnull(), move(contents), media_box, crop_box, user_unit, rotate };
  137. m_pages.set(index, page);
  138. return page;
  139. }
  140. PDFErrorOr<Value> Document::resolve(Value const& value)
  141. {
  142. if (value.has<Reference>()) {
  143. // FIXME: Surely indirect PDF objects can't contain another indirect PDF object,
  144. // right? Unsure from the spec, but if they can, these return values would have
  145. // to be wrapped with another resolve() call.
  146. return get_or_load_value(value.as_ref_index());
  147. }
  148. if (!value.has<NonnullRefPtr<Object>>())
  149. return value;
  150. auto& obj = value.get<NonnullRefPtr<Object>>();
  151. if (obj->is<IndirectValue>())
  152. return static_ptr_cast<IndirectValue>(obj)->value();
  153. return value;
  154. }
  155. PDFErrorOr<void> Document::build_page_tree()
  156. {
  157. auto page_tree = TRY(m_catalog->get_dict(this, CommonNames::Pages));
  158. return add_page_tree_node_to_page_tree(page_tree);
  159. }
  160. PDFErrorOr<void> Document::add_page_tree_node_to_page_tree(NonnullRefPtr<DictObject> const& page_tree)
  161. {
  162. auto kids_array = TRY(page_tree->get_array(this, CommonNames::Kids));
  163. auto page_count = page_tree->get(CommonNames::Count).value().get<int>();
  164. if (static_cast<size_t>(page_count) != kids_array->elements().size()) {
  165. // This page tree contains child page trees, so we recursively add
  166. // these pages to the overall page tree
  167. for (auto& value : *kids_array) {
  168. auto reference_index = value.as_ref_index();
  169. auto maybe_page_tree_node = TRY(m_parser->conditionally_parse_page_tree_node(reference_index));
  170. if (maybe_page_tree_node) {
  171. TRY(add_page_tree_node_to_page_tree(maybe_page_tree_node.release_nonnull()));
  172. } else {
  173. m_page_object_indices.append(reference_index);
  174. }
  175. }
  176. } else {
  177. // We know all of the kids are leaf nodes
  178. for (auto& value : *kids_array)
  179. m_page_object_indices.append(value.as_ref_index());
  180. }
  181. return {};
  182. }
  183. PDFErrorOr<NonnullRefPtr<Object>> Document::find_in_name_tree(NonnullRefPtr<DictObject> tree, DeprecatedFlyString name)
  184. {
  185. if (tree->contains(CommonNames::Kids)) {
  186. return find_in_name_tree_nodes(tree->get_array(CommonNames::Kids), name);
  187. }
  188. if (!tree->contains(CommonNames::Names))
  189. return Error { Error::Type::MalformedPDF, "name tree has neither Kids nor Names" };
  190. auto key_value_names_array = TRY(tree->get_array(this, CommonNames::Names));
  191. return find_in_key_value_array(key_value_names_array, name);
  192. }
  193. PDFErrorOr<NonnullRefPtr<Object>> Document::find_in_name_tree_nodes(NonnullRefPtr<ArrayObject> siblings, DeprecatedFlyString name)
  194. {
  195. for (size_t i = 0; i < siblings->size(); i++) {
  196. auto sibling = TRY(resolve_to<DictObject>(siblings->at(i)));
  197. auto limits = sibling->get_array(CommonNames::Limits);
  198. if (limits->size() != 2)
  199. return Error { Error::Type::MalformedPDF, "Expected 2-element Limits array" };
  200. auto start = limits->get_string_at(0);
  201. auto end = limits->get_string_at(1);
  202. if (start->string() <= name && end->string() >= name) {
  203. return find_in_name_tree(sibling, name);
  204. }
  205. }
  206. return Error { Error::Type::MalformedPDF, DeprecatedString::formatted("Didn't find node in name tree containing name {}", name) };
  207. }
  208. PDFErrorOr<NonnullRefPtr<Object>> Document::find_in_key_value_array(NonnullRefPtr<ArrayObject> key_value_array, DeprecatedFlyString name)
  209. {
  210. if (key_value_array->size() % 2 == 1)
  211. return Error { Error::Type::MalformedPDF, "key/value array has dangling key" };
  212. for (size_t i = 0; i < key_value_array->size() / 2; i++) {
  213. auto key = key_value_array->get_string_at(2 * i);
  214. if (key->string() == name) {
  215. return key_value_array->get_object_at(this, 2 * i + 1);
  216. }
  217. }
  218. return Error { Error::Type::MalformedPDF, DeprecatedString::formatted("Didn't find expected name {} in key/value array", name) };
  219. }
  220. PDFErrorOr<void> Document::build_outline()
  221. {
  222. if (!m_catalog->contains(CommonNames::Outlines))
  223. return {};
  224. auto outline_dict = TRY(m_catalog->get_dict(this, CommonNames::Outlines));
  225. if (!outline_dict->contains(CommonNames::First))
  226. return {};
  227. if (!outline_dict->contains(CommonNames::Last))
  228. return {};
  229. HashMap<u32, u32> page_number_by_index_ref;
  230. for (u32 page_number = 0; page_number < m_page_object_indices.size(); ++page_number) {
  231. page_number_by_index_ref.set(m_page_object_indices[page_number], page_number);
  232. }
  233. auto first_ref = outline_dict->get_value(CommonNames::First);
  234. auto children = TRY(build_outline_item_chain(first_ref, page_number_by_index_ref));
  235. m_outline = adopt_ref(*new OutlineDict());
  236. m_outline->children = move(children);
  237. if (outline_dict->contains(CommonNames::Count))
  238. m_outline->count = outline_dict->get_value(CommonNames::Count).get<int>();
  239. return {};
  240. }
  241. PDFErrorOr<Destination> Document::create_destination_from_parameters(NonnullRefPtr<ArrayObject> array, HashMap<u32, u32> const& page_number_by_index_ref)
  242. {
  243. auto page_ref = array->at(0);
  244. auto type_name = TRY(array->get_name_at(this, 1))->name();
  245. Vector<Optional<float>> parameters;
  246. TRY(parameters.try_ensure_capacity(array->size() - 2));
  247. for (size_t i = 2; i < array->size(); i++) {
  248. auto& param = array->at(i);
  249. if (param.has<nullptr_t>())
  250. parameters.unchecked_append({});
  251. else
  252. parameters.append(param.to_float());
  253. }
  254. Destination::Type type;
  255. if (type_name == CommonNames::XYZ) {
  256. type = Destination::Type::XYZ;
  257. } else if (type_name == CommonNames::Fit) {
  258. type = Destination::Type::Fit;
  259. } else if (type_name == CommonNames::FitH) {
  260. type = Destination::Type::FitH;
  261. } else if (type_name == CommonNames::FitV) {
  262. type = Destination::Type::FitV;
  263. } else if (type_name == CommonNames::FitR) {
  264. type = Destination::Type::FitR;
  265. } else if (type_name == CommonNames::FitB) {
  266. type = Destination::Type::FitB;
  267. } else if (type_name == CommonNames::FitBH) {
  268. type = Destination::Type::FitBH;
  269. } else if (type_name == CommonNames::FitBV) {
  270. type = Destination::Type::FitBV;
  271. } else {
  272. VERIFY_NOT_REACHED();
  273. }
  274. return Destination { type, page_number_by_index_ref.get(page_ref.as_ref_index()), parameters };
  275. }
  276. PDFErrorOr<Optional<NonnullRefPtr<Object>>> Document::get_inheritable_object(DeprecatedFlyString const& name, NonnullRefPtr<DictObject> object)
  277. {
  278. if (!object->contains(name)) {
  279. if (!object->contains(CommonNames::Parent))
  280. return { OptionalNone() };
  281. auto parent = TRY(object->get_dict(this, CommonNames::Parent));
  282. return get_inheritable_object(name, parent);
  283. }
  284. return TRY(object->get_object(this, name));
  285. }
  286. PDFErrorOr<Destination> Document::create_destination_from_dictionary_entry(NonnullRefPtr<Object> const& entry, HashMap<u32, u32> const& page_number_by_index_ref)
  287. {
  288. if (entry->is<ArrayObject>()) {
  289. auto entry_array = entry->cast<ArrayObject>();
  290. return create_destination_from_parameters(entry_array, page_number_by_index_ref);
  291. }
  292. auto entry_dictionary = entry->cast<DictObject>();
  293. auto d_array = MUST(entry_dictionary->get_array(this, CommonNames::D));
  294. return create_destination_from_parameters(d_array, page_number_by_index_ref);
  295. }
  296. PDFErrorOr<NonnullRefPtr<OutlineItem>> Document::build_outline_item(NonnullRefPtr<DictObject> const& outline_item_dict, HashMap<u32, u32> const& page_number_by_index_ref)
  297. {
  298. auto outline_item = adopt_ref(*new OutlineItem {});
  299. if (outline_item_dict->contains(CommonNames::First)) {
  300. VERIFY(outline_item_dict->contains(CommonNames::Last));
  301. auto first_ref = outline_item_dict->get_value(CommonNames::First);
  302. auto children = TRY(build_outline_item_chain(first_ref, page_number_by_index_ref));
  303. for (auto& child : children) {
  304. child->parent = outline_item;
  305. }
  306. outline_item->children = move(children);
  307. }
  308. outline_item->title = TRY(outline_item_dict->get_string(this, CommonNames::Title))->string();
  309. if (outline_item_dict->contains(CommonNames::Count))
  310. outline_item->count = outline_item_dict->get_value(CommonNames::Count).get<int>();
  311. if (outline_item_dict->contains(CommonNames::Dest)) {
  312. auto dest_obj = TRY(outline_item_dict->get_object(this, CommonNames::Dest));
  313. if (dest_obj->is<ArrayObject>()) {
  314. auto dest_arr = dest_obj->cast<ArrayObject>();
  315. outline_item->dest = TRY(create_destination_from_parameters(dest_arr, page_number_by_index_ref));
  316. } else if (dest_obj->is<NameObject>() || dest_obj->is<StringObject>()) {
  317. DeprecatedFlyString dest_name;
  318. if (dest_obj->is<NameObject>())
  319. dest_name = dest_obj->cast<NameObject>()->name();
  320. else
  321. dest_name = dest_obj->cast<StringObject>()->string();
  322. if (auto dests_value = m_catalog->get(CommonNames::Dests); dests_value.has_value()) {
  323. auto dests = dests_value.value().get<NonnullRefPtr<Object>>()->cast<DictObject>();
  324. auto entry = MUST(dests->get_object(this, dest_name));
  325. outline_item->dest = TRY(create_destination_from_dictionary_entry(entry, page_number_by_index_ref));
  326. } else if (auto names_value = m_catalog->get(CommonNames::Names); names_value.has_value()) {
  327. auto names = TRY(resolve(names_value.release_value())).get<NonnullRefPtr<Object>>()->cast<DictObject>();
  328. if (!names->contains(CommonNames::Dests))
  329. return Error { Error::Type::MalformedPDF, "Missing Dests key in document catalogue's Names dictionary" };
  330. auto dest_obj = TRY(find_in_name_tree(TRY(names->get_dict(this, CommonNames::Dests)), dest_name));
  331. outline_item->dest = TRY(create_destination_from_dictionary_entry(dest_obj, page_number_by_index_ref));
  332. } else {
  333. return Error { Error::Type::MalformedPDF, "Malformed outline destination" };
  334. }
  335. }
  336. }
  337. if (outline_item_dict->contains(CommonNames::C)) {
  338. auto color_array = TRY(outline_item_dict->get_array(this, CommonNames::C));
  339. auto r = static_cast<int>(255.0f * color_array->at(0).get<float>());
  340. auto g = static_cast<int>(255.0f * color_array->at(1).get<float>());
  341. auto b = static_cast<int>(255.0f * color_array->at(2).get<float>());
  342. outline_item->color = Color(r, g, b);
  343. }
  344. if (outline_item_dict->contains(CommonNames::F)) {
  345. auto bitfield = outline_item_dict->get_value(CommonNames::F).get<int>();
  346. outline_item->italic = bitfield & 0x1;
  347. outline_item->bold = bitfield & 0x2;
  348. }
  349. return outline_item;
  350. }
  351. PDFErrorOr<Vector<NonnullRefPtr<OutlineItem>>> Document::build_outline_item_chain(Value const& first_ref, HashMap<u32, u32> const& page_number_by_index_ref)
  352. {
  353. // We used to receive a last_ref parameter, which was what the parent of this chain
  354. // thought was this chain's last child. There are documents out there in the wild
  355. // where this cross-references don't match though, and it seems like simply following
  356. // the /First and /Next links is the way to go to construct the whole Outline
  357. // (we already ignore the /Parent attribute too, which can also be out of sync).
  358. VERIFY(first_ref.has<Reference>());
  359. Vector<NonnullRefPtr<OutlineItem>> children;
  360. auto first_value = TRY(get_or_load_value(first_ref.as_ref_index())).get<NonnullRefPtr<Object>>();
  361. auto first_dict = first_value->cast<DictObject>();
  362. auto first = TRY(build_outline_item(first_dict, page_number_by_index_ref));
  363. children.append(first);
  364. auto current_child_dict = first_dict;
  365. u32 current_child_index = first_ref.as_ref_index();
  366. while (current_child_dict->contains(CommonNames::Next)) {
  367. auto next_child_dict_ref = current_child_dict->get_value(CommonNames::Next);
  368. current_child_index = next_child_dict_ref.as_ref_index();
  369. auto next_child_value = TRY(get_or_load_value(current_child_index)).get<NonnullRefPtr<Object>>();
  370. auto next_child_dict = next_child_value->cast<DictObject>();
  371. auto next_child = TRY(build_outline_item(next_child_dict, page_number_by_index_ref));
  372. children.append(next_child);
  373. current_child_dict = move(next_child_dict);
  374. }
  375. return children;
  376. }
  377. }