2 * PaperJam -- Low-level handling of PDFs
4 * (c) 2018 Martin Mares <mj@ucw.cz>
15 #include <qpdf/QPDFWriter.hh>
20 static void do_recalc_bbox(vector<page *> &pages, const char *in_name);
22 string out_context::new_resource(const string type)
24 return "/" + type + to_string(++res_cnt);
27 class in_page : public page {
28 QPDFObjectHandle pdf_page;
29 QPDFObjectHandle xobject;
32 void render(out_context *out, pdf_matrix xform);
33 void debug_dump() { debug("Input page %d", index); }
34 in_page(QPDFObjectHandle inpg, int idx);
37 in_page::in_page(QPDFObjectHandle inpg, int idx)
40 xobject = QPDFObjectHandle::newNull();
43 media_box = BBox(inpg.getKey("/MediaBox"));
44 width = media_box.width();
45 height = media_box.height();
47 QPDFObjectHandle art_box = inpg.getKey("/ArtBox");
49 art_box = inpg.getKey("/CropBox");
51 image_box = BBox(width, height);
54 image_box = BBox(art_box);
55 image_box.x_min -= media_box.x_min;
56 image_box.x_max -= media_box.x_min;
57 image_box.y_min -= media_box.y_min;
58 image_box.y_max -= media_box.y_min;
62 void in_page::render(out_context *out, pdf_matrix xform)
64 // Convert page to xobject
66 xobject = out->pdf->makeIndirectObject( page_to_xobject(out->pdf, out->pdf->copyForeignObject(pdf_page)) );
67 string xobj_res = out->new_resource("XO");
68 out->xobjects.replaceKey(xobj_res, xobject);
71 m.shift(-media_box.x_min, -media_box.y_min);
74 out->contents += "q " + m.to_string() + " cm " + xobj_res + " Do Q ";
77 void debug_pages(vector<page *> &pages)
84 debug("Page #%d: media[%.3f %.3f] image[%.3f %.3f %.3f %.3f][%.3f %.3f]",
86 pg->width, pg->height,
87 pg->image_box.x_min, pg->image_box.y_min, pg->image_box.x_max, pg->image_box.y_max,
88 pg->image_box.width(), pg->image_box.height());
98 vector<page *> run_command_list(list<cmd *> &cmds, vector<page *> &pages)
105 debug("# Executing %s", c->def->name);
109 pages = c->exec->process(pages);
113 die("Error in %s: %s", c->def->name, e.what());
122 static void make_info_dict()
124 // Create info dictionary if it did not exist yet
125 QPDFObjectHandle trailer = out_pdf.getTrailer();
126 QPDFObjectHandle info = trailer.getKey("/Info");
129 info = QPDFObjectHandle::newDictionary();
130 trailer.replaceKey("/Info", info);
133 assert(info.isDictionary());
135 info.replaceKey("/Producer", unicode_string("PaperJam"));
137 // Copy entries from the source file's info dictionary
138 QPDFObjectHandle orig_trailer = in_pdf.getTrailer();
139 QPDFObjectHandle orig_info = orig_trailer.getKey("/Info");
140 if (!orig_info.isNull())
142 const string to_copy[] = { "/Title", "/Author", "/Subject", "/Keywords", "/Creator", "/CreationDate" };
143 for (string key: to_copy)
144 info.replaceOrRemoveKey(key, orig_info.getKey(key));
148 void process(list<cmd *> &cmds)
150 debug("### Reading input");
151 in_pdf.processFile(in_name);
152 in_pdf.pushInheritedAttributesToPage();
155 vector<QPDFObjectHandle> const &in_pages = in_pdf.getAllPages();
156 vector<page *> pages;
158 QPDFObjectHandle page_copy = out_pdf.copyForeignObject(in_pages[0]);
161 for (auto inpg: in_pages)
162 pages.push_back(new in_page(inpg, ++cnt));
165 do_recalc_bbox(pages, in_name);
167 debug("### Running commands");
168 pages = run_command_list(cmds, pages);
170 debug("### Writing output");
177 debug("Page #%d", out_page);
185 out.resources = QPDFObjectHandle::newDictionary();
186 out.resources.replaceKey("/ProcSet", QPDFObjectHandle::parse("[/PDF]"));
187 out.xobjects = QPDFObjectHandle::newDictionary();
188 out.egstates = QPDFObjectHandle::newDictionary();
189 pg->render(&out, pdf_matrix());
191 QPDFObjectHandle contents = QPDFObjectHandle::newStream(&out_pdf, out.contents);
193 // Create the page object
194 QPDFObjectHandle out_page = out_pdf.makeIndirectObject(QPDFObjectHandle::newDictionary());
195 out_page.replaceKey("/Type", QPDFObjectHandle::newName("/Page"));
196 out_page.replaceKey("/MediaBox", BBox(pg->width, pg->height).to_array());
198 // out_page.replaceKey("/CropBox", pg->image_box.to_array());
199 out_page.replaceKey("/Contents", contents);
200 if (!out.xobjects.getKeys().empty())
201 out.resources.replaceKey("/XObject", out.xobjects);
202 if (!out.egstates.getKeys().empty())
203 out.resources.replaceKey("/ExtGState", out.egstates);
204 out_page.replaceKey("/Resources", out.resources);
205 out_pdf.addPage(out_page, false);
208 // Produce info dictionary
211 // Write the output file
212 QPDFWriter writer(out_pdf, out_name);
217 /*** Re-calculation of bboxes ***/
219 vector<BBox> gs_bboxes(const char *in)
223 die("Cannot create pipe: %m");
227 die("Cannot fork: %m");
235 execlp("gs", "gs", "-sDEVICE=bbox", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-q", in, NULL);
236 die("Cannot execute gs: %m");
240 FILE *f = fdopen(pipes[0], "r");
242 die("fdopen failed: %m");
246 while (fgets(line, sizeof(line), f))
248 char *eol = strchr(line, '\n');
250 die("Ghostscript produced too long lines");
253 if (!strncmp(line, "%%HiResBoundingBox: ", 20))
255 double x1, y1, x2, y2;
256 if (sscanf(line+20, "%lf%lf%lf%lf", &x1, &y1, &x2, &y2) != 4)
257 die("Cannot parse Ghostscript output: %s", line);
258 bboxes.push_back(BBox(x1, y1, x2, y2));
260 else if (line[0] != '%')
261 fprintf(stderr, "%s\n", line);
266 if (waitpid(pid, &stat, 0) < 0)
267 die("wait failed: %m");
268 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
269 die("Ghostscript failed");
274 static void do_recalc_bbox(vector<page *> &pages, const char *in_name)
276 debug("Calling Ghostscript to re-calculate bounding boxes");
277 vector<BBox> bboxes = gs_bboxes(in_name);
278 if (pages.size() != bboxes.size())
279 die("Ghostscript failed to produce the right number of bboxes");
281 for (size_t i=0; i<pages.size(); i++)
282 pages[i]->image_box = bboxes[i];