Document.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. String OutlineItem::to_string(int indent) const
  11. {
  12. auto indent_str = String::repeated(" ", indent + 1);
  13. StringBuilder child_builder;
  14. child_builder.append('[');
  15. for (auto& child : children)
  16. child_builder.appendff("{}\n", child.to_string(indent + 1));
  17. child_builder.appendff("{}]", indent_str);
  18. StringBuilder builder;
  19. builder.append("OutlineItem {{\n");
  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_string());
  27. builder.appendff("{}}}", String::repeated(" ", indent));
  28. return builder.to_string();
  29. }
  30. PDFErrorOr<NonnullRefPtr<Document>> Document::create(ReadonlyBytes bytes)
  31. {
  32. auto parser = adopt_ref(*new Parser({}, 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("");
  44. }
  45. return document;
  46. }
  47. Document::Document(NonnullRefPtr<Parser> 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. if (!raw_page_object->contains(CommonNames::Resources)) {
  89. // This page inherits its resource dictionary
  90. TODO();
  91. }
  92. auto resources = TRY(raw_page_object->get_dict(this, CommonNames::Resources));
  93. auto contents = TRY(raw_page_object->get_object(this, CommonNames::Contents));
  94. auto media_box_array = TRY(raw_page_object->get_array(this, CommonNames::MediaBox));
  95. auto media_box = Rectangle {
  96. media_box_array->at(0).to_float(),
  97. media_box_array->at(1).to_float(),
  98. media_box_array->at(2).to_float(),
  99. media_box_array->at(3).to_float(),
  100. };
  101. auto crop_box = media_box;
  102. if (raw_page_object->contains(CommonNames::CropBox)) {
  103. auto crop_box_array = TRY(raw_page_object->get_array(this, CommonNames::CropBox));
  104. crop_box = Rectangle {
  105. crop_box_array->at(0).to_float(),
  106. crop_box_array->at(1).to_float(),
  107. crop_box_array->at(2).to_float(),
  108. crop_box_array->at(3).to_float(),
  109. };
  110. }
  111. float user_unit = 1.0f;
  112. if (raw_page_object->contains(CommonNames::UserUnit))
  113. user_unit = raw_page_object->get_value(CommonNames::UserUnit).to_float();
  114. int rotate = 0;
  115. if (raw_page_object->contains(CommonNames::Rotate)) {
  116. rotate = raw_page_object->get_value(CommonNames::Rotate).get<int>();
  117. VERIFY(rotate % 90 == 0);
  118. }
  119. Page page { move(resources), move(contents), media_box, crop_box, user_unit, rotate };
  120. m_pages.set(index, page);
  121. return page;
  122. }
  123. PDFErrorOr<Value> Document::resolve(Value const& value)
  124. {
  125. if (value.has<Reference>()) {
  126. // FIXME: Surely indirect PDF objects can't contain another indirect PDF object,
  127. // right? Unsure from the spec, but if they can, these return values would have
  128. // to be wrapped with another resolve() call.
  129. return get_or_load_value(value.as_ref_index());
  130. }
  131. if (!value.has<NonnullRefPtr<Object>>())
  132. return value;
  133. auto& obj = value.get<NonnullRefPtr<Object>>();
  134. if (obj->is<IndirectValue>())
  135. return static_ptr_cast<IndirectValue>(obj)->value();
  136. return value;
  137. }
  138. PDFErrorOr<void> Document::build_page_tree()
  139. {
  140. auto page_tree = TRY(m_catalog->get_dict(this, CommonNames::Pages));
  141. return add_page_tree_node_to_page_tree(page_tree);
  142. }
  143. PDFErrorOr<void> Document::add_page_tree_node_to_page_tree(NonnullRefPtr<DictObject> const& page_tree)
  144. {
  145. auto kids_array = TRY(page_tree->get_array(this, CommonNames::Kids));
  146. auto page_count = page_tree->get(CommonNames::Count).value().get<int>();
  147. if (static_cast<size_t>(page_count) != kids_array->elements().size()) {
  148. // This page tree contains child page trees, so we recursively add
  149. // these pages to the overall page tree
  150. for (auto& value : *kids_array) {
  151. auto reference_index = value.as_ref_index();
  152. auto maybe_page_tree_node = TRY(m_parser->conditionally_parse_page_tree_node(reference_index));
  153. if (maybe_page_tree_node) {
  154. TRY(add_page_tree_node_to_page_tree(maybe_page_tree_node.release_nonnull()));
  155. } else {
  156. m_page_object_indices.append(reference_index);
  157. }
  158. }
  159. } else {
  160. // We know all of the kids are leaf nodes
  161. for (auto& value : *kids_array)
  162. m_page_object_indices.append(value.as_ref_index());
  163. }
  164. return {};
  165. }
  166. PDFErrorOr<void> Document::build_outline()
  167. {
  168. if (!m_catalog->contains(CommonNames::Outlines))
  169. return {};
  170. auto outline_dict = TRY(m_catalog->get_dict(this, CommonNames::Outlines));
  171. if (!outline_dict->contains(CommonNames::First))
  172. return {};
  173. if (!outline_dict->contains(CommonNames::Last))
  174. return {};
  175. auto first_ref = outline_dict->get_value(CommonNames::First);
  176. auto last_ref = outline_dict->get_value(CommonNames::Last);
  177. auto children = TRY(build_outline_item_chain(first_ref, last_ref));
  178. m_outline = adopt_ref(*new OutlineDict());
  179. m_outline->children = move(children);
  180. if (outline_dict->contains(CommonNames::Count))
  181. m_outline->count = outline_dict->get_value(CommonNames::Count).get<int>();
  182. return {};
  183. }
  184. PDFErrorOr<Destination> Document::create_destination_from_parameters(NonnullRefPtr<ArrayObject> array)
  185. {
  186. auto page_ref = array->at(0);
  187. auto type_name = TRY(array->get_name_at(this, 1))->name();
  188. Vector<float> parameters;
  189. for (size_t i = 2; i < array->size(); i++)
  190. parameters.append(array->at(i).to_float());
  191. Destination::Type type;
  192. if (type_name == CommonNames::XYZ) {
  193. type = Destination::Type::XYZ;
  194. } else if (type_name == CommonNames::Fit) {
  195. type = Destination::Type::Fit;
  196. } else if (type_name == CommonNames::FitH) {
  197. type = Destination::Type::FitH;
  198. } else if (type_name == CommonNames::FitV) {
  199. type = Destination::Type::FitV;
  200. } else if (type_name == CommonNames::FitR) {
  201. type = Destination::Type::FitR;
  202. } else if (type_name == CommonNames::FitB) {
  203. type = Destination::Type::FitB;
  204. } else if (type_name == CommonNames::FitBH) {
  205. type = Destination::Type::FitBH;
  206. } else if (type_name == CommonNames::FitBV) {
  207. type = Destination::Type::FitBV;
  208. } else {
  209. VERIFY_NOT_REACHED();
  210. }
  211. return Destination { type, page_ref, parameters };
  212. }
  213. PDFErrorOr<NonnullRefPtr<OutlineItem>> Document::build_outline_item(NonnullRefPtr<DictObject> const& outline_item_dict)
  214. {
  215. auto outline_item = adopt_ref(*new OutlineItem {});
  216. if (outline_item_dict->contains(CommonNames::First)) {
  217. VERIFY(outline_item_dict->contains(CommonNames::Last));
  218. auto first_ref = outline_item_dict->get_value(CommonNames::First);
  219. auto last_ref = outline_item_dict->get_value(CommonNames::Last);
  220. auto children = TRY(build_outline_item_chain(first_ref, last_ref));
  221. outline_item->children = move(children);
  222. }
  223. outline_item->title = TRY(outline_item_dict->get_string(this, CommonNames::Title))->string();
  224. if (outline_item_dict->contains(CommonNames::Count))
  225. outline_item->count = outline_item_dict->get_value(CommonNames::Count).get<int>();
  226. if (outline_item_dict->contains(CommonNames::Dest)) {
  227. auto dest_obj = TRY(outline_item_dict->get_object(this, CommonNames::Dest));
  228. if (dest_obj->is<ArrayObject>()) {
  229. auto dest_arr = dest_obj->cast<ArrayObject>();
  230. outline_item->dest = TRY(create_destination_from_parameters(dest_arr));
  231. } else if (dest_obj->is<NameObject>()) {
  232. auto dest_name = dest_obj->cast<NameObject>()->name();
  233. if (auto dests_value = m_catalog->get(CommonNames::Dests); dests_value.has_value()) {
  234. auto dests = dests_value.value().get<NonnullRefPtr<Object>>()->cast<DictObject>();
  235. auto entry = MUST(dests->get_object(this, dest_name));
  236. if (entry->is<ArrayObject>()) {
  237. auto entry_array = entry->cast<ArrayObject>();
  238. outline_item->dest = TRY(create_destination_from_parameters(entry_array));
  239. } else {
  240. auto entry_dictionary = entry->cast<DictObject>();
  241. auto d_array = MUST(entry_dictionary->get_array(this, CommonNames::D));
  242. outline_item->dest = TRY(create_destination_from_parameters(d_array));
  243. }
  244. } else {
  245. return Error { Error::Type::MalformedPDF, "Malformed outline destination" };
  246. }
  247. }
  248. }
  249. if (outline_item_dict->contains(CommonNames::C)) {
  250. auto color_array = TRY(outline_item_dict->get_array(this, CommonNames::C));
  251. auto r = static_cast<int>(255.0f * color_array->at(0).get<float>());
  252. auto g = static_cast<int>(255.0f * color_array->at(1).get<float>());
  253. auto b = static_cast<int>(255.0f * color_array->at(2).get<float>());
  254. outline_item->color = Color(r, g, b);
  255. }
  256. if (outline_item_dict->contains(CommonNames::F)) {
  257. auto bitfield = outline_item_dict->get_value(CommonNames::F).get<int>();
  258. outline_item->italic = bitfield & 0x1;
  259. outline_item->bold = bitfield & 0x2;
  260. }
  261. return outline_item;
  262. }
  263. PDFErrorOr<NonnullRefPtrVector<OutlineItem>> Document::build_outline_item_chain(Value const& first_ref, Value const& last_ref)
  264. {
  265. VERIFY(first_ref.has<Reference>());
  266. VERIFY(last_ref.has<Reference>());
  267. NonnullRefPtrVector<OutlineItem> children;
  268. auto first_value = TRY(get_or_load_value(first_ref.as_ref_index())).get<NonnullRefPtr<Object>>();
  269. auto first_dict = first_value->cast<DictObject>();
  270. auto first = TRY(build_outline_item(first_dict));
  271. children.append(first);
  272. auto current_child_dict = first_dict;
  273. u32 current_child_index = first_ref.as_ref_index();
  274. while (current_child_dict->contains(CommonNames::Next)) {
  275. auto next_child_dict_ref = current_child_dict->get_value(CommonNames::Next);
  276. current_child_index = next_child_dict_ref.as_ref_index();
  277. auto next_child_value = TRY(get_or_load_value(current_child_index)).get<NonnullRefPtr<Object>>();
  278. auto next_child_dict = next_child_value->cast<DictObject>();
  279. auto next_child = TRY(build_outline_item(next_child_dict));
  280. children.append(next_child);
  281. current_child_dict = move(next_child_dict);
  282. }
  283. VERIFY(last_ref.as_ref_index() == current_child_index);
  284. return children;
  285. }
  286. }