]> mj.ucw.cz Git - paperjam.git/blob - pdf.cc
0c9b27b491be88b3b248d4901b692e2820bfd2a9
[paperjam.git] / pdf.cc
1 /*
2  *      PaperJam -- Low-level handling of PDFs
3  *
4  *      (c) 2018 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <cassert>
8 #include <cstdlib>
9 #include <cstdio>
10 #include <unistd.h>
11 #include <sys/wait.h>
12
13 #include "jam.h"
14
15 #include <qpdf/QPDFWriter.hh>
16
17 static QPDF in_pdf;
18 static QPDF out_pdf;
19
20 static void do_recalc_bbox(vector<page *> &pages, const char *in_name);
21
22 string out_context::new_resource(const string type)
23 {
24   return "/" + type + to_string(++res_cnt);
25 }
26
27 class in_page : public page {
28   QPDFObjectHandle pdf_page;
29   QPDFObjectHandle xobject;
30 public:
31   BBox media_box;
32   void render(out_context *out, pdf_matrix xform);
33   in_page(QPDFObjectHandle inpg, int idx);
34 };
35
36 in_page::in_page(QPDFObjectHandle inpg, int idx)
37 {
38   pdf_page = inpg;
39   xobject = QPDFObjectHandle::newNull();
40   index = idx;
41
42   media_box = BBox(inpg.getKey("/MediaBox"));
43   width = media_box.width();
44   height = media_box.height();
45
46   QPDFObjectHandle art_box = inpg.getKey("/ArtBox");
47   if (art_box.isNull())
48     art_box = inpg.getKey("/CropBox");
49   if (art_box.isNull())
50     image_box = BBox(width, height);
51   else
52     {
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;
58     }
59 }
60
61 void in_page::render(out_context *out, pdf_matrix xform)
62 {
63   // Convert page to xobject
64   if (xobject.isNull())
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);
68
69   pdf_matrix m;
70   m.shift(-media_box.x_min, -media_box.y_min);
71   m.concat(xform);
72
73   out->contents += "q " + m.to_string() + " cm " + xobj_res + " Do Q ";
74 }
75
76 void debug_pages(vector<page *> &pages)
77 {
78   if (!debug_mode)
79     return;
80
81   for (auto pg: pages)
82     debug("Page #%d: media[%.3f %.3f] image[%.3f %.3f %.3f %.3f]",
83       pg->index,
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);
86 }
87
88 vector<page *> run_command_list(list<cmd *> &cmds, vector<page *> &pages)
89 {
90   debug("# Input");
91   debug_pages(pages);
92
93   for (auto c: cmds)
94     {
95       debug("# Executing %s", c->def->name);
96       debug_indent += 4;
97       pages = c->exec->process(pages);
98       debug_indent -= 4;
99       debug_pages(pages);
100     }
101
102   return pages;
103 }
104
105 void process(list<cmd *> &cmds)
106 {
107   in_pdf.processFile(in_name);
108   in_pdf.pushInheritedAttributesToPage();
109   out_pdf.emptyPDF();
110
111   vector<QPDFObjectHandle> const &in_pages = in_pdf.getAllPages();
112   vector<page *> pages;
113
114   QPDFObjectHandle page_copy = out_pdf.copyForeignObject(in_pages[0]);
115
116   int cnt = 0;
117   for (auto inpg: in_pages)
118     pages.push_back(new in_page(inpg, ++cnt));
119
120   if (recalc_bbox)
121     do_recalc_bbox(pages, in_name);
122
123   pages = run_command_list(cmds, pages);
124
125   for (auto pg: pages)
126     {
127       out_context out;
128       out.pdf = &out_pdf;
129       out.resources = QPDFObjectHandle::newDictionary();
130       out.resources.replaceKey("/ProcSet", QPDFObjectHandle::parse("[/PDF]"));
131       out.xobjects = QPDFObjectHandle::newDictionary();
132       out.egstates = QPDFObjectHandle::newDictionary();
133       pg->render(&out, pdf_matrix());
134
135       QPDFObjectHandle contents = QPDFObjectHandle::newStream(&out_pdf, out.contents);
136
137       // Create the page object
138       QPDFObjectHandle out_page = out_pdf.makeIndirectObject(QPDFObjectHandle::newDictionary());
139       out_page.replaceKey("/Type", QPDFObjectHandle::newName("/Page"));
140       out_page.replaceKey("/MediaBox", BBox(pg->width, pg->height).to_array());
141       // FIXME:
142       // out_page.replaceKey("/CropBox", pg->image_box.to_array());
143       out_page.replaceKey("/Contents", contents);
144       if (!out.xobjects.getKeys().empty())
145         out.resources.replaceKey("/XObject", out.xobjects);
146       if (!out.egstates.getKeys().empty())
147         out.resources.replaceKey("/ExtGState", out.egstates);
148       out_page.replaceKey("/Resources", out.resources);
149       out_pdf.addPage(out_page, false);
150     }
151
152   // Produce info dictionary
153   QPDFObjectHandle trailer = out_pdf.getTrailer();
154   QPDFObjectHandle info = trailer.getKey("/Info");
155   if (info.isNull())
156     {
157       info = QPDFObjectHandle::newDictionary();
158       trailer.replaceKey("/Info", info);
159     }
160   else
161     assert(info.isDictionary());
162   // FIXME: More meta-data
163   info.replaceKey("/Producer", unicode_string("PaperJam"));
164
165   // Write the output file
166   QPDFWriter writer(out_pdf, out_name);
167   writer.write();
168 }
169
170 /*** Re-calculation of bboxes ***/
171
172 vector<BBox> gs_bboxes(const char *in)
173 {
174   int pipes[2];
175   if (pipe(pipes) < 0)
176     die("Cannot create pipe: %m");
177
178   pid_t pid = fork();
179   if (pid < 0)
180     die("Cannot fork: %m");
181
182   if (!pid)
183     {
184       close(pipes[0]);
185       dup2(pipes[1], 1);
186       dup2(pipes[1], 2);
187       close(pipes[1]);
188       execlp("gs", "gs", "-sDEVICE=bbox", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-q", in, NULL);
189       die("Cannot execute gs: %m");
190     }
191
192   close(pipes[1]);
193   FILE *f = fdopen(pipes[0], "r");
194   if (!f)
195     die("fdopen failed: %m");
196
197   char line[1024];
198   vector<BBox> bboxes;
199   while (fgets(line, sizeof(line), f))
200     {
201       char *eol = strchr(line, '\n');
202       if (!eol)
203         die("Ghostscript produced too long lines");
204       *eol = 0;
205
206       if (!strncmp(line, "%%HiResBoundingBox: ", 20))
207         {
208           double x1, y1, x2, y2;
209           if (sscanf(line+20, "%lf%lf%lf%lf", &x1, &y1, &x2, &y2) != 4)
210             die("Cannot parse Ghostscript output: %s", line);
211           bboxes.push_back(BBox(x1, y1, x2, y2));
212         }
213       else if (line[0] != '%')
214         fprintf(stderr, "%s\n", line);
215     }
216   fclose(f);
217
218   int stat;
219   if (waitpid(pid, &stat, 0) < 0)
220     die("wait failed: %m");
221   if (!WIFEXITED(stat) || WEXITSTATUS(stat))
222     die("Ghostscript failed");
223
224   return bboxes;
225 }
226
227 static void do_recalc_bbox(vector<page *> &pages, const char *in_name)
228 {
229   debug("Calling Ghostscript to re-calculate bounding boxes");
230   vector<BBox> bboxes = gs_bboxes(in_name);
231   if (pages.size() != bboxes.size())
232     die("Ghostscript failed to produce the right number of bboxes");
233
234   for (size_t i=0; i<pages.size(); i++)
235     pages[i]->image_box = bboxes[i];
236 }