2 * PaperJam -- Low-level handling of PDFs
4 * (c) 2018 Martin Mares <mj@ucw.cz>
16 #include <qpdf/QPDFWriter.hh>
21 static void do_recalc_bbox(vector<page *> &pages, const char *in_name);
23 string out_context::new_resource(const string type)
25 return "/" + type + to_string(++res_cnt);
28 class in_page : public page {
29 QPDFObjectHandle pdf_page;
30 QPDFObjectHandle xobject;
33 void render(out_context *out, pdf_matrix xform);
34 void debug_dump() { debug("Input page %d", index); }
35 in_page(QPDFObjectHandle inpg, int idx);
38 in_page::in_page(QPDFObjectHandle inpg, int idx)
41 xobject = QPDFObjectHandle::newNull();
44 media_box = BBox(inpg.getKey("/MediaBox"));
45 width = media_box.width();
46 height = media_box.height();
48 QPDFObjectHandle art_box = inpg.getKey("/ArtBox");
50 art_box = inpg.getKey("/CropBox");
52 image_box = BBox(width, height);
55 image_box = BBox(art_box);
56 image_box.x_min -= media_box.x_min;
57 image_box.x_max -= media_box.x_min;
58 image_box.y_min -= media_box.y_min;
59 image_box.y_max -= media_box.y_min;
63 void in_page::render(out_context *out, pdf_matrix xform)
65 // Convert page to xobject
67 xobject = out->pdf->makeIndirectObject( page_to_xobject(out->pdf, out->pdf->copyForeignObject(pdf_page)) );
68 string xobj_res = out->new_resource("XO");
69 out->xobjects.replaceKey(xobj_res, xobject);
72 m.shift(-media_box.x_min, -media_box.y_min);
75 out->contents += "q " + m.to_string() + " cm " + xobj_res + " Do Q ";
78 void debug_pages(vector<page *> &pages)
85 debug("Page #%d: media[%.3f %.3f] image[%.3f %.3f %.3f %.3f][%.3f %.3f]",
87 pg->width, pg->height,
88 pg->image_box.x_min, pg->image_box.y_min, pg->image_box.x_max, pg->image_box.y_max,
89 pg->image_box.width(), pg->image_box.height());
99 vector<page *> run_command_list(list<cmd *> &cmds, vector<page *> &pages)
106 debug("# Executing %s", c->def->name);
110 pages = c->exec->process(pages);
114 die("Error in %s: %s", c->def->name, e.what());
123 static void make_info_dict()
125 // Create info dictionary if it did not exist yet
126 QPDFObjectHandle trailer = out_pdf.getTrailer();
127 QPDFObjectHandle info = trailer.getKey("/Info");
130 info = QPDFObjectHandle::newDictionary();
131 trailer.replaceKey("/Info", info);
134 assert(info.isDictionary());
136 info.replaceKey("/Producer", unicode_string("PaperJam"));
138 // Copy entries from the source file's info dictionary
139 QPDFObjectHandle orig_trailer = in_pdf.getTrailer();
140 QPDFObjectHandle orig_info = orig_trailer.getKey("/Info");
141 if (!orig_info.isNull())
143 const string to_copy[] = { "/Title", "/Author", "/Subject", "/Keywords", "/Creator", "/CreationDate" };
144 for (string key: to_copy)
145 info.replaceOrRemoveKey(key, orig_info.getKey(key));
149 void process(list<cmd *> &cmds)
151 debug("### Reading input");
152 in_pdf.processFile(in_name);
153 in_pdf.pushInheritedAttributesToPage();
156 vector<QPDFObjectHandle> const &in_pages = in_pdf.getAllPages();
157 vector<page *> pages;
159 QPDFObjectHandle page_copy = out_pdf.copyForeignObject(in_pages[0]);
162 for (auto inpg: in_pages)
163 pages.push_back(new in_page(inpg, ++cnt));
166 do_recalc_bbox(pages, in_name);
168 debug("### Running commands");
169 pages = run_command_list(cmds, pages);
171 debug("### Writing output");
178 debug("Page #%d", out_page);
186 out.resources = QPDFObjectHandle::newDictionary();
187 out.resources.replaceKey("/ProcSet", QPDFObjectHandle::parse("[/PDF]"));
188 out.xobjects = QPDFObjectHandle::newDictionary();
189 out.egstates = QPDFObjectHandle::newDictionary();
190 pg->render(&out, pdf_matrix());
192 QPDFObjectHandle contents = QPDFObjectHandle::newStream(&out_pdf, out.contents);
194 // Create the page object
195 QPDFObjectHandle out_page = out_pdf.makeIndirectObject(QPDFObjectHandle::newDictionary());
196 out_page.replaceKey("/Type", QPDFObjectHandle::newName("/Page"));
197 out_page.replaceKey("/MediaBox", BBox(pg->width, pg->height).to_array());
199 // out_page.replaceKey("/CropBox", pg->image_box.to_array());
200 out_page.replaceKey("/Contents", contents);
201 if (!out.xobjects.getKeys().empty())
202 out.resources.replaceKey("/XObject", out.xobjects);
203 if (!out.egstates.getKeys().empty())
204 out.resources.replaceKey("/ExtGState", out.egstates);
205 out_page.replaceKey("/Resources", out.resources);
206 out_pdf.addPage(out_page, false);
209 // Produce info dictionary
212 // Write the output file
213 QPDFWriter writer(out_pdf, out_name);
218 /*** Re-calculation of bboxes ***/
220 vector<BBox> gs_bboxes(const char *in)
224 die("Cannot create pipe: %m");
228 die("Cannot fork: %m");
236 execlp("gs", "gs", "-sDEVICE=bbox", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-q", in, NULL);
237 die("Cannot execute gs: %m");
241 FILE *f = fdopen(pipes[0], "r");
243 die("fdopen failed: %m");
247 while (fgets(line, sizeof(line), f))
249 char *eol = strchr(line, '\n');
251 die("Ghostscript produced too long lines");
254 if (!strncmp(line, "%%HiResBoundingBox: ", 20))
256 double x1, y1, x2, y2;
257 if (sscanf(line+20, "%lf%lf%lf%lf", &x1, &y1, &x2, &y2) != 4)
258 die("Cannot parse Ghostscript output: %s", line);
259 bboxes.push_back(BBox(x1, y1, x2, y2));
261 else if (line[0] != '%')
262 fprintf(stderr, "%s\n", line);
267 if (waitpid(pid, &stat, 0) < 0)
268 die("wait failed: %m");
269 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
270 die("Ghostscript failed");
275 static void do_recalc_bbox(vector<page *> &pages, const char *in_name)
277 debug("Calling Ghostscript to re-calculate bounding boxes");
278 vector<BBox> bboxes = gs_bboxes(in_name);
279 if (pages.size() != bboxes.size())
280 die("Ghostscript failed to produce the right number of bboxes");
282 for (size_t i=0; i<pages.size(); i++)
283 pages[i]->image_box = bboxes[i];