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 in_page(QPDFObjectHandle inpg, int idx);
36 in_page::in_page(QPDFObjectHandle inpg, int idx)
39 xobject = QPDFObjectHandle::newNull();
42 media_box = BBox(inpg.getKey("/MediaBox"));
43 width = media_box.width();
44 height = media_box.height();
46 QPDFObjectHandle art_box = inpg.getKey("/ArtBox");
48 art_box = inpg.getKey("/CropBox");
50 image_box = BBox(width, height);
53 image_box = BBox(art_box);
54 image_box.x_min -= media_box.x_min;
55 image_box.x_max -= media_box.x_min;
56 image_box.y_min -= media_box.y_min;
57 image_box.y_max -= media_box.y_min;
61 void in_page::render(out_context *out, pdf_matrix xform)
63 // Convert page to xobject
65 xobject = out->pdf->makeIndirectObject( page_to_xobject(out->pdf, out->pdf->copyForeignObject(pdf_page)) );
66 string xobj_res = out->new_resource("XO");
67 out->xobjects.replaceKey(xobj_res, xobject);
70 m.shift(-media_box.x_min, -media_box.y_min);
73 out->contents += "q " + m.to_string() + " cm " + xobj_res + " Do Q ";
76 void debug_pages(vector<page *> &pages)
82 debug("Page #%d: media[%.3f %.3f] image[%.3f %.3f %.3f %.3f]",
84 pg->width, pg->height,
85 pg->image_box.x_min, pg->image_box.y_min, pg->image_box.x_max, pg->image_box.y_max);
88 vector<page *> run_command_list(list<cmd *> &cmds, vector<page *> &pages)
95 debug("# Executing %s", c->def->name);
99 pages = c->exec->process(pages);
103 die("Error in %s: %s", c->def->name, e.what());
112 void process(list<cmd *> &cmds)
114 in_pdf.processFile(in_name);
115 in_pdf.pushInheritedAttributesToPage();
118 vector<QPDFObjectHandle> const &in_pages = in_pdf.getAllPages();
119 vector<page *> pages;
121 QPDFObjectHandle page_copy = out_pdf.copyForeignObject(in_pages[0]);
124 for (auto inpg: in_pages)
125 pages.push_back(new in_page(inpg, ++cnt));
128 do_recalc_bbox(pages, in_name);
130 pages = run_command_list(cmds, pages);
136 out.resources = QPDFObjectHandle::newDictionary();
137 out.resources.replaceKey("/ProcSet", QPDFObjectHandle::parse("[/PDF]"));
138 out.xobjects = QPDFObjectHandle::newDictionary();
139 out.egstates = QPDFObjectHandle::newDictionary();
140 pg->render(&out, pdf_matrix());
142 QPDFObjectHandle contents = QPDFObjectHandle::newStream(&out_pdf, out.contents);
144 // Create the page object
145 QPDFObjectHandle out_page = out_pdf.makeIndirectObject(QPDFObjectHandle::newDictionary());
146 out_page.replaceKey("/Type", QPDFObjectHandle::newName("/Page"));
147 out_page.replaceKey("/MediaBox", BBox(pg->width, pg->height).to_array());
149 // out_page.replaceKey("/CropBox", pg->image_box.to_array());
150 out_page.replaceKey("/Contents", contents);
151 if (!out.xobjects.getKeys().empty())
152 out.resources.replaceKey("/XObject", out.xobjects);
153 if (!out.egstates.getKeys().empty())
154 out.resources.replaceKey("/ExtGState", out.egstates);
155 out_page.replaceKey("/Resources", out.resources);
156 out_pdf.addPage(out_page, false);
159 // Produce info dictionary
160 QPDFObjectHandle trailer = out_pdf.getTrailer();
161 QPDFObjectHandle info = trailer.getKey("/Info");
164 info = QPDFObjectHandle::newDictionary();
165 trailer.replaceKey("/Info", info);
168 assert(info.isDictionary());
169 // FIXME: More meta-data
170 info.replaceKey("/Producer", unicode_string("PaperJam"));
172 // Write the output file
173 QPDFWriter writer(out_pdf, out_name);
177 /*** Re-calculation of bboxes ***/
179 vector<BBox> gs_bboxes(const char *in)
183 die("Cannot create pipe: %m");
187 die("Cannot fork: %m");
195 execlp("gs", "gs", "-sDEVICE=bbox", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-q", in, NULL);
196 die("Cannot execute gs: %m");
200 FILE *f = fdopen(pipes[0], "r");
202 die("fdopen failed: %m");
206 while (fgets(line, sizeof(line), f))
208 char *eol = strchr(line, '\n');
210 die("Ghostscript produced too long lines");
213 if (!strncmp(line, "%%HiResBoundingBox: ", 20))
215 double x1, y1, x2, y2;
216 if (sscanf(line+20, "%lf%lf%lf%lf", &x1, &y1, &x2, &y2) != 4)
217 die("Cannot parse Ghostscript output: %s", line);
218 bboxes.push_back(BBox(x1, y1, x2, y2));
220 else if (line[0] != '%')
221 fprintf(stderr, "%s\n", line);
226 if (waitpid(pid, &stat, 0) < 0)
227 die("wait failed: %m");
228 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
229 die("Ghostscript failed");
234 static void do_recalc_bbox(vector<page *> &pages, const char *in_name)
236 debug("Calling Ghostscript to re-calculate bounding boxes");
237 vector<BBox> bboxes = gs_bboxes(in_name);
238 if (pages.size() != bboxes.size())
239 die("Ghostscript failed to produce the right number of bboxes");
241 for (size_t i=0; i<pages.size(); i++)
242 pages[i]->image_box = bboxes[i];