pdf-clean-file.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. // Copyright (C) 2004-2025 Artifex Software, Inc.
  2. //
  3. // This file is part of MuPDF.
  4. //
  5. // MuPDF is free software: you can redistribute it and/or modify it under the
  6. // terms of the GNU Affero General Public License as published by the Free
  7. // Software Foundation, either version 3 of the License, or (at your option)
  8. // any later version.
  9. //
  10. // MuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
  11. // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  13. // details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
  17. //
  18. // Alternative licensing terms are available from the licensor.
  19. // For commercial licensing, see <https://www.artifex.com/> or contact
  20. // Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
  21. // CA 94129, USA, for further information.
  22. #include "mupdf/fitz.h"
  23. #include "mupdf/pdf.h"
  24. #include <string.h>
  25. static int
  26. string_in_names_list(fz_context *ctx, pdf_obj *p, pdf_obj *names_list)
  27. {
  28. int n = pdf_array_len(ctx, names_list);
  29. int i;
  30. char *str = pdf_to_str_buf(ctx, p);
  31. for (i = 0; i < n ; i += 2)
  32. {
  33. if (!strcmp(pdf_to_str_buf(ctx, pdf_array_get(ctx, names_list, i)), str))
  34. return 1;
  35. }
  36. return 0;
  37. }
  38. /*
  39. * Recreate page tree to only retain specified pages.
  40. */
  41. static void retainpage(fz_context *ctx, pdf_document *doc, pdf_obj *parentobj, pdf_obj *kids, int page, pdf_obj *structparents, pdf_obj *ostructparents)
  42. {
  43. pdf_obj *pageref = pdf_lookup_page_obj(ctx, doc, page);
  44. pdf_flatten_inheritable_page_items(ctx, pageref);
  45. pdf_dict_put(ctx, pageref, PDF_NAME(Parent), parentobj);
  46. /* Store page object in new kids array */
  47. pdf_array_push(ctx, kids, pageref);
  48. if (structparents)
  49. {
  50. int parentnum = pdf_dict_get_int(ctx, pageref, PDF_NAME(StructParents));
  51. pdf_obj *parent = pdf_lookup_number(ctx, ostructparents, parentnum);
  52. pdf_obj *nums = pdf_dict_get(ctx, structparents, PDF_NAME(Nums));
  53. pdf_obj *limits = pdf_dict_get(ctx, structparents, PDF_NAME(Limits));
  54. int min, max;
  55. pdf_array_push_int(ctx, nums, parentnum);
  56. pdf_array_push(ctx, nums, parent);
  57. if (limits == NULL)
  58. {
  59. min = max = parentnum;
  60. limits = pdf_new_array(ctx, doc, 2);
  61. pdf_dict_put_drop(ctx, structparents, PDF_NAME(Limits), limits);
  62. }
  63. else
  64. {
  65. min = pdf_array_get_int(ctx, limits, 0);
  66. max = pdf_array_get_int(ctx, limits, 1);
  67. if (min > parentnum)
  68. min = parentnum;
  69. if (max < parentnum)
  70. max = parentnum;
  71. }
  72. pdf_array_put_int(ctx, limits, 0, min);
  73. pdf_array_put_int(ctx, limits, 1, max);
  74. }
  75. }
  76. static int dest_is_valid_page(fz_context *ctx, pdf_obj *obj, int *page_object_nums, int pagecount)
  77. {
  78. int i;
  79. int num = pdf_to_num(ctx, obj);
  80. if (num == 0)
  81. return 0;
  82. for (i = 0; i < pagecount; i++)
  83. {
  84. if (page_object_nums[i] == num)
  85. return 1;
  86. }
  87. return 0;
  88. }
  89. static int dest_is_valid(fz_context *ctx, pdf_obj *o, int page_count, int *page_object_nums, pdf_obj *names_list)
  90. {
  91. pdf_obj *p;
  92. p = pdf_dict_get(ctx, o, PDF_NAME(A));
  93. if (pdf_name_eq(ctx, pdf_dict_get(ctx, p, PDF_NAME(S)), PDF_NAME(GoTo)))
  94. {
  95. pdf_obj *d = pdf_dict_get(ctx, p, PDF_NAME(D));
  96. if (pdf_is_array(ctx, d) && !dest_is_valid_page(ctx, pdf_array_get(ctx, d, 0), page_object_nums, page_count))
  97. return 0;
  98. else if (pdf_is_string(ctx, d) && !string_in_names_list(ctx, d, names_list))
  99. return 0;
  100. }
  101. p = pdf_dict_get(ctx, o, PDF_NAME(Dest));
  102. if (p == NULL)
  103. return 1; /* A name with no dest counts as valid. */
  104. else if (pdf_is_string(ctx, p))
  105. return string_in_names_list(ctx, p, names_list);
  106. else if (!dest_is_valid_page(ctx, pdf_array_get(ctx, p, 0), page_object_nums, page_count))
  107. return 0;
  108. return 1;
  109. }
  110. static int strip_stale_annot_refs(fz_context *ctx, pdf_obj *field, int page_count, int *page_object_nums)
  111. {
  112. pdf_obj *kids = pdf_dict_get(ctx, field, PDF_NAME(Kids));
  113. int len = pdf_array_len(ctx, kids);
  114. int j;
  115. if (kids)
  116. {
  117. for (j = 0; j < len; j++)
  118. {
  119. if (strip_stale_annot_refs(ctx, pdf_array_get(ctx, kids, j), page_count, page_object_nums))
  120. {
  121. pdf_array_delete(ctx, kids, j);
  122. len--;
  123. j--;
  124. }
  125. }
  126. return pdf_array_len(ctx, kids) == 0;
  127. }
  128. else
  129. {
  130. pdf_obj *page = pdf_dict_get(ctx, field, PDF_NAME(P));
  131. int page_num = pdf_to_num(ctx, page);
  132. for (j = 0; j < page_count; j++)
  133. if (page_num == page_object_nums[j])
  134. return 0;
  135. return 1;
  136. }
  137. }
  138. static int strip_outlines(fz_context *ctx, pdf_document *doc, pdf_obj *outlines, int page_count, int *page_object_nums, pdf_obj *names_list, pdf_mark_bits *marks);
  139. static int strip_outline(fz_context *ctx, pdf_document *doc, pdf_obj *outlines, int page_count, int *page_object_nums, pdf_obj *names_list, pdf_obj **pfirst, pdf_obj **plast, pdf_mark_bits *marks)
  140. {
  141. pdf_obj *prev = NULL;
  142. pdf_obj *first = NULL;
  143. pdf_obj *current;
  144. int count = 0;
  145. for (current = outlines; current != NULL; )
  146. {
  147. int nc;
  148. /* Strip any children to start with. This takes care of
  149. * First/Last/Count for us. */
  150. nc = strip_outlines(ctx, doc, current, page_count, page_object_nums, names_list, marks);
  151. if (!dest_is_valid(ctx, current, page_count, page_object_nums, names_list))
  152. {
  153. if (nc == 0)
  154. {
  155. /* Outline with invalid dest and no children. Drop it by
  156. * pulling the next one in here. */
  157. pdf_obj *next = pdf_dict_get(ctx, current, PDF_NAME(Next));
  158. if (!pdf_is_dict(ctx, next))
  159. {
  160. /* There is no next one to pull in */
  161. if (prev != NULL)
  162. pdf_dict_del(ctx, prev, PDF_NAME(Next));
  163. }
  164. else if (prev != NULL)
  165. {
  166. pdf_dict_put(ctx, prev, PDF_NAME(Next), next);
  167. pdf_dict_put(ctx, next, PDF_NAME(Prev), prev);
  168. }
  169. else
  170. {
  171. pdf_dict_del(ctx, next, PDF_NAME(Prev));
  172. }
  173. current = next;
  174. }
  175. else
  176. {
  177. /* Outline with invalid dest, but children. Just drop the dest. */
  178. pdf_dict_del(ctx, current, PDF_NAME(Dest));
  179. pdf_dict_del(ctx, current, PDF_NAME(A));
  180. current = pdf_dict_get(ctx, current, PDF_NAME(Next));
  181. }
  182. }
  183. else
  184. {
  185. /* Keep this one */
  186. if (first == NULL)
  187. first = current;
  188. prev = current;
  189. current = pdf_dict_get(ctx, current, PDF_NAME(Next));
  190. count++;
  191. }
  192. }
  193. *pfirst = first;
  194. *plast = prev;
  195. return count;
  196. }
  197. static int strip_outlines(fz_context *ctx, pdf_document *doc, pdf_obj *outlines, int page_count, int *page_object_nums, pdf_obj *names_list, pdf_mark_bits *marks)
  198. {
  199. int nc;
  200. pdf_obj *first;
  201. pdf_obj *last;
  202. if (!pdf_is_dict(ctx, outlines))
  203. return 0;
  204. if (pdf_mark_bits_set(ctx, marks, outlines))
  205. fz_throw(ctx, FZ_ERROR_FORMAT, "Cycle detected in outlines");
  206. first = pdf_dict_get(ctx, outlines, PDF_NAME(First));
  207. if (!pdf_is_dict(ctx, first))
  208. nc = 0;
  209. else
  210. nc = strip_outline(ctx, doc, first, page_count, page_object_nums, names_list, &first, &last, marks);
  211. if (nc == 0)
  212. {
  213. pdf_dict_del(ctx, outlines, PDF_NAME(First));
  214. pdf_dict_del(ctx, outlines, PDF_NAME(Last));
  215. pdf_dict_del(ctx, outlines, PDF_NAME(Count));
  216. }
  217. else
  218. {
  219. int old_count = pdf_dict_get_int(ctx, outlines, PDF_NAME(Count));
  220. pdf_dict_put(ctx, outlines, PDF_NAME(First), first);
  221. pdf_dict_put(ctx, outlines, PDF_NAME(Last), last);
  222. pdf_dict_put_int(ctx, outlines, PDF_NAME(Count), old_count > 0 ? nc : -nc);
  223. }
  224. return nc;
  225. }
  226. static void pdf_rearrange_pages_imp(fz_context *ctx, pdf_document *doc, int count, const int *new_page_list, pdf_clean_options_structure structure)
  227. {
  228. pdf_obj *oldroot, *pages, *kids, *olddests;
  229. pdf_obj *root = NULL;
  230. pdf_obj *names_list = NULL;
  231. pdf_obj *outlines;
  232. pdf_obj *ocproperties;
  233. pdf_obj *allfields = NULL;
  234. int pagecount, i;
  235. int *page_object_nums = NULL;
  236. pdf_obj *structtreeroot = NULL;
  237. pdf_obj *ostructparents = NULL;
  238. pdf_obj *structparents = NULL;
  239. pdf_mark_bits *marks = NULL;
  240. /* Keep only pages/type and (reduced) dest entries to avoid
  241. * references to unretained pages */
  242. oldroot = pdf_dict_get(ctx, pdf_trailer(ctx, doc), PDF_NAME(Root));
  243. pages = pdf_dict_get(ctx, oldroot, PDF_NAME(Pages));
  244. olddests = pdf_load_name_tree(ctx, doc, PDF_NAME(Dests));
  245. outlines = pdf_dict_get(ctx, oldroot, PDF_NAME(Outlines));
  246. ocproperties = pdf_dict_get(ctx, oldroot, PDF_NAME(OCProperties));
  247. if (structure == PDF_CLEAN_STRUCTURE_KEEP)
  248. {
  249. structtreeroot = pdf_dict_get(ctx, oldroot, PDF_NAME(StructTreeRoot));
  250. ostructparents = pdf_dict_get(ctx, structtreeroot, PDF_NAME(ParentTree));
  251. if (structtreeroot)
  252. structparents = pdf_new_dict(ctx, doc, 3);
  253. }
  254. fz_var(root);
  255. fz_var(names_list);
  256. fz_var(allfields);
  257. fz_var(page_object_nums);
  258. fz_var(kids);
  259. fz_var(marks);
  260. fz_try(ctx)
  261. {
  262. root = pdf_new_dict(ctx, doc, 3);
  263. pdf_dict_put(ctx, root, PDF_NAME(Type), pdf_dict_get(ctx, oldroot, PDF_NAME(Type)));
  264. pdf_dict_put(ctx, root, PDF_NAME(Pages), pdf_dict_get(ctx, oldroot, PDF_NAME(Pages)));
  265. if (structtreeroot)
  266. {
  267. pdf_dict_put(ctx, root, PDF_NAME(StructTreeRoot), structtreeroot);
  268. pdf_dict_put(ctx, structtreeroot, PDF_NAME(ParentTree), structparents);
  269. pdf_dict_put_array(ctx, structparents, PDF_NAME(Nums), 2);
  270. }
  271. if (outlines)
  272. pdf_dict_put(ctx, root, PDF_NAME(Outlines), outlines);
  273. if (ocproperties)
  274. pdf_dict_put(ctx, root, PDF_NAME(OCProperties), ocproperties);
  275. pdf_update_object(ctx, doc, pdf_to_num(ctx, oldroot), root);
  276. /* Create a new kids array with only the pages we want to keep */
  277. kids = pdf_new_array(ctx, doc, 1);
  278. /* Retain pages specified */
  279. for (i = 0; i < count; ++i)
  280. retainpage(ctx, doc, pages, kids, new_page_list[i], structparents, ostructparents);
  281. /* Update page count */
  282. pdf_dict_put_int(ctx, pages, PDF_NAME(Count), pdf_array_len(ctx, kids));
  283. pdf_dict_put(ctx, pages, PDF_NAME(Kids), kids);
  284. pagecount = pdf_count_pages(ctx, doc);
  285. page_object_nums = fz_calloc(ctx, pagecount, sizeof(*page_object_nums));
  286. for (i = 0; i < pagecount; i++)
  287. {
  288. pdf_obj *pageref = pdf_lookup_page_obj(ctx, doc, i);
  289. page_object_nums[i] = pdf_to_num(ctx, pageref);
  290. }
  291. /* If we had an old Dests tree (now reformed as an olddests
  292. * dictionary), keep any entries in there that point to
  293. * valid pages. This may mean we keep more than we need, but
  294. * it's safe at least. */
  295. if (olddests)
  296. {
  297. pdf_obj *names, *dests;
  298. int len = pdf_dict_len(ctx, olddests);
  299. names = pdf_dict_put_dict(ctx, root, PDF_NAME(Names), 1);
  300. dests = pdf_dict_put_dict(ctx, names, PDF_NAME(Dests), 1);
  301. names_list = pdf_dict_put_array(ctx, dests, PDF_NAME(Names), 32);
  302. for (i = 0; i < len; i++)
  303. {
  304. pdf_obj *key = pdf_dict_get_key(ctx, olddests, i);
  305. pdf_obj *val = pdf_dict_get_val(ctx, olddests, i);
  306. pdf_obj *dest = pdf_dict_get(ctx, val, PDF_NAME(D));
  307. dest = pdf_array_get(ctx, dest ? dest : val, 0);
  308. if (dest_is_valid_page(ctx, dest, page_object_nums, pagecount))
  309. {
  310. pdf_array_push_string(ctx, names_list, pdf_to_name(ctx, key), strlen(pdf_to_name(ctx, key)));
  311. pdf_array_push(ctx, names_list, val);
  312. }
  313. }
  314. pdf_drop_obj(ctx, olddests);
  315. }
  316. /* Edit each pages /Annot list to remove any links that point to nowhere. */
  317. for (i = 0; i < pagecount; i++)
  318. {
  319. pdf_obj *pageref = pdf_lookup_page_obj(ctx, doc, i);
  320. pdf_obj *annots = pdf_dict_get(ctx, pageref, PDF_NAME(Annots));
  321. int len = pdf_array_len(ctx, annots);
  322. int j;
  323. for (j = 0; j < len; j++)
  324. {
  325. pdf_obj *o = pdf_array_get(ctx, annots, j);
  326. if (!pdf_name_eq(ctx, pdf_dict_get(ctx, o, PDF_NAME(Subtype)), PDF_NAME(Link)))
  327. continue;
  328. if (!dest_is_valid(ctx, o, pagecount, page_object_nums, names_list))
  329. {
  330. /* Remove this annotation */
  331. pdf_array_delete(ctx, annots, j);
  332. len--;
  333. j--;
  334. }
  335. }
  336. }
  337. /* Locate all fields on retained pages */
  338. allfields = pdf_new_array(ctx, doc, 1);
  339. for (i = 0; i < pagecount; i++)
  340. {
  341. pdf_obj *pageref = pdf_lookup_page_obj(ctx, doc, i);
  342. pdf_obj *annots = pdf_dict_get(ctx, pageref, PDF_NAME(Annots));
  343. int len = pdf_array_len(ctx, annots);
  344. int j;
  345. for (j = 0; j < len; j++)
  346. {
  347. pdf_obj *f = pdf_array_get(ctx, annots, j);
  348. if (pdf_dict_get(ctx, f, PDF_NAME(Subtype)) == PDF_NAME(Widget))
  349. pdf_array_push(ctx, allfields, f);
  350. }
  351. }
  352. /* From non-terminal widget fields, strip out annot references not
  353. * belonging to any retained page. */
  354. for (i = 0; i < pdf_array_len(ctx, allfields); i++)
  355. {
  356. pdf_obj *f = pdf_array_get(ctx, allfields, i);
  357. while (pdf_dict_get(ctx, f, PDF_NAME(Parent)))
  358. f = pdf_dict_get(ctx, f, PDF_NAME(Parent));
  359. strip_stale_annot_refs(ctx, f, pagecount, page_object_nums);
  360. }
  361. /* For terminal fields, if action destination is not valid,
  362. * remove the action */
  363. for (i = 0; i < pdf_array_len(ctx, allfields); i++)
  364. {
  365. pdf_obj *f = pdf_array_get(ctx, allfields, i);
  366. if (!dest_is_valid(ctx, f, pagecount, page_object_nums, names_list))
  367. pdf_dict_del(ctx, f, PDF_NAME(A));
  368. }
  369. marks = pdf_new_mark_bits(ctx, doc);
  370. if (strip_outlines(ctx, doc, outlines, pagecount, page_object_nums, names_list, marks) == 0)
  371. {
  372. pdf_dict_del(ctx, root, PDF_NAME(Outlines));
  373. }
  374. }
  375. fz_always(ctx)
  376. {
  377. pdf_drop_mark_bits(ctx, marks);
  378. fz_free(ctx, page_object_nums);
  379. pdf_drop_obj(ctx, allfields);
  380. pdf_drop_obj(ctx, root);
  381. pdf_drop_obj(ctx, kids);
  382. pdf_drop_obj(ctx, structparents);
  383. }
  384. fz_catch(ctx)
  385. {
  386. fz_rethrow(ctx);
  387. }
  388. }
  389. void pdf_rearrange_pages(fz_context *ctx, pdf_document *doc, int count, const int *new_page_list, pdf_clean_options_structure structure)
  390. {
  391. if (structure < PDF_CLEAN_STRUCTURE_DROP || structure > PDF_CLEAN_STRUCTURE_KEEP)
  392. fz_throw(ctx, FZ_ERROR_ARGUMENT, "Invalid structure argument");
  393. pdf_begin_operation(ctx, doc, "Rearrange pages");
  394. fz_try(ctx)
  395. {
  396. pdf_rearrange_pages_imp(ctx, doc, count, new_page_list, structure);
  397. pdf_end_operation(ctx, doc);
  398. }
  399. fz_catch(ctx)
  400. {
  401. pdf_abandon_operation(ctx, doc);
  402. pdf_sync_open_pages(ctx, doc);
  403. fz_rethrow(ctx);
  404. }
  405. pdf_sync_open_pages(ctx, doc);
  406. }
  407. void pdf_clean_file(fz_context *ctx, char *infile, char *outfile, char *password, pdf_clean_options *opts, int argc, char *argv[])
  408. {
  409. pdf_clean_options default_opts = { 0 };
  410. pdf_document *pdf = NULL;
  411. int *pages = NULL;
  412. int cap, len, page;
  413. fz_var(pdf);
  414. fz_var(pages);
  415. if (opts == NULL)
  416. opts = &default_opts;
  417. if (argc > 0 && argv == NULL)
  418. fz_throw(ctx, FZ_ERROR_ARGUMENT, "arguments array must be set if arguments exist");
  419. fz_try(ctx)
  420. {
  421. pdf = pdf_open_document(ctx, infile);
  422. if (pdf_needs_password(ctx, pdf))
  423. if (!pdf_authenticate_password(ctx, pdf, password))
  424. fz_throw(ctx, FZ_ERROR_ARGUMENT, "cannot authenticate password: %s", infile);
  425. len = cap = 0;
  426. /* Only retain the specified subset of the pages */
  427. if (argc)
  428. {
  429. int pagecount = pdf_count_pages(ctx, pdf);
  430. int argidx = 0;
  431. while (argc - argidx)
  432. {
  433. int spage, epage;
  434. const char *pagelist = argv[argidx];
  435. while ((pagelist = fz_parse_page_range(ctx, pagelist, &spage, &epage, pagecount)))
  436. {
  437. if (len + (epage - spage + 1) >= cap)
  438. {
  439. int n = cap ? cap * 2 : 8;
  440. while (len + (epage - spage + 1) >= n)
  441. n *= 2;
  442. pages = fz_realloc_array(ctx, pages, n, int);
  443. cap = n;
  444. }
  445. if (spage < epage)
  446. for (page = spage; page <= epage; ++page)
  447. pages[len++] = page - 1;
  448. else
  449. for (page = spage; page >= epage; --page)
  450. pages[len++] = page - 1;
  451. }
  452. argidx++;
  453. }
  454. pdf_rearrange_pages(ctx, pdf, len, pages, opts->structure);
  455. }
  456. pdf_rewrite_images(ctx, pdf, &opts->image);
  457. if (opts->subset_fonts)
  458. pdf_subset_fonts(ctx, pdf, len, pages);
  459. pdf_save_document(ctx, pdf, outfile, &opts->write);
  460. }
  461. fz_always(ctx)
  462. {
  463. fz_free(ctx, pages);
  464. pdf_drop_document(ctx, pdf);
  465. }
  466. fz_catch(ctx)
  467. {
  468. fz_rethrow(ctx);
  469. }
  470. }