]> mj.ucw.cz Git - paperjam.git/blob - pdf-tools.cc
29e79bff9f835e4ca10eb595883f7cca09eaee6c
[paperjam.git] / pdf-tools.cc
1 /*
2  *      Auxiliary functions for processing PDF files
3  *
4  *      (c) 2018 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <cstdio>
8 #include <cstdlib>
9
10 #include <iconv.h>
11
12 #include "jam.h"
13
14 #include <qpdf/QUtil.hh>
15 #include <qpdf/Pl_Concatenate.hh>
16
17 /*** Transformation matrices ***/
18
19 // Construct string representation of a transformation matrix
20 string pdf_matrix::to_string() {
21         string s;
22         for (int i=0; i<6; i++) {
23                 if (i)
24                         s += " ";
25                 char buf[16];
26                 snprintf(buf, sizeof(buf), "%.3f", m[i]);
27                 s += buf;
28         }
29         return s;
30 }
31
32 /*** Bounding boxes ***/
33
34 QPDFObjectHandle BBox::to_array()
35 {
36         QPDFObjectHandle a = QPDFObjectHandle::newArray();
37         a.appendItem(QPDFObjectHandle::newReal(x_min, 1));
38         a.appendItem(QPDFObjectHandle::newReal(y_min, 1));
39         a.appendItem(QPDFObjectHandle::newReal(x_max, 1));
40         a.appendItem(QPDFObjectHandle::newReal(y_max, 1));
41         return a;
42 }
43
44 string BBox::to_rect()
45 {
46         char buf[64];
47         snprintf(buf, sizeof(buf), "%.1f %.1f %.1f %.1f", x_min, y_min, width(), height());
48         return string(buf);
49 }
50
51 bool BBox::parse(QPDFObjectHandle h)
52 {
53         if (!h.isArray() || h.getArrayNItems() != 4)
54                 return false;
55         double x[4];
56         for (int i=0; i<4; i++) {
57                 QPDFObjectHandle item = h.getArrayItem(i);
58                 if (!item.isNumber())
59                         return false;
60                 x[i] = item.getNumericValue();
61         }
62         x_min = x[0];
63         y_min = x[1];
64         x_max = x[2];
65         y_max = x[3];
66         return true;
67 }
68
69 BBox::BBox(QPDFObjectHandle box) {
70         if (!parse(box)) {
71                 warn("Invalid bounding box, falling back to A4");
72                 x_min = 0, x_max = A4_WIDTH;
73                 y_min = 0, y_max = A4_HEIGHT;
74         }
75 }
76
77 void BBox::transform(pdf_matrix &m)
78 {
79         m.apply(&x_min, &y_min);
80         m.apply(&x_max, &y_max);
81         if (x_max < x_min)
82                 swap(x_min, x_max);
83         if (y_max < y_min)
84                 swap(y_min, y_max);
85 }
86
87 void BBox::join(BBox &with)
88 {
89         x_min = min(x_min, with.x_min);
90         x_max = max(x_max, with.x_max);
91         y_min = min(y_min, with.y_min);
92         y_max = max(y_max, with.y_max);
93 }
94
95 /*** Unicode strings ***/
96
97 // Construct PDF representation of a UTF-8 string
98 QPDFObjectHandle unicode_string(string s)
99 {
100         // If it is ASCII only, use the string directly
101         bool ascii_only = true;
102         for (char c: s)
103                 if (c < 0x20 || c > 0x7e)
104                         ascii_only = false;
105         if (ascii_only)
106                 return QPDFObjectHandle::newString(s);
107
108         // Use iconv to convert the string to big-endian UTF-16
109         iconv_t conv = iconv_open("UTF-16BE", "UTF-8");
110         if (conv == (iconv_t) -1)
111                 die("Cannot initialize iconv: %m");
112
113         char *in_ptr = (char *) s.c_str();      // Work around bad API of iconv()
114         size_t in_len = strlen(in_ptr);
115         size_t out_len = 2*in_len + 2;          // Worst case (including the BOM)
116         char out_buf[out_len];
117         char *out_ptr = out_buf;
118         size_t res = iconv(conv, &in_ptr, &in_len, &out_ptr, &out_len);
119         if (res == (size_t) -1)
120                 die("iconv failed: %m");
121         if (in_len)
122                 die("iconv stopped before the end of input");
123
124         iconv_close(conv);
125
126         // Package UTF-16 in a PDF string
127         string out;
128         out += 0xfe;
129         out += 0xff;
130         for (char *p = out_buf; p < out_ptr; p++)
131                 out += *p;
132         return QPDFObjectHandle::newString(out);
133 }
134
135 /*** Conversion of pages to XObjects ***/
136
137 static BBox get_trim_box(QPDFObjectHandle page)
138 {
139         static const char * const boxes[] = { "/TrimBox", "/CropBox", "/MediaBox", NULL };
140         for (int i=0; boxes[i]; i++)
141                 if (page.hasKey(boxes[i]))
142                         return BBox(page.getKey(boxes[i]));
143         warn("Page has no trimbox, falling back to A4");
144         return BBox(0, 0, A4_WIDTH, A4_HEIGHT);
145 }
146
147 /* Conversion of pages to XObjects is inspired by CUPS's pdftopdf filter. */
148 class CombineFromContents_Provider : public QPDFObjectHandle::StreamDataProvider {
149         private:
150                 vector<QPDFObjectHandle> contents;
151         public:
152                 CombineFromContents_Provider(const vector<QPDFObjectHandle> &contents) : contents(contents) { }
153                 void provideStreamData(int objid UNUSED, int generation UNUSED, Pipeline* pipeline) {
154                         Pl_Concatenate concat("concat", pipeline);
155                         for (int i=0; i < (int)contents.size(); i++)
156                                 contents[i].pipeStreamData(&concat, true, false, false);
157                         concat.manualFinish();
158                 }
159 };
160
161 QPDFObjectHandle page_to_xobject(QPDF *out, QPDFObjectHandle page)
162 {
163         page.assertPageObject();
164
165         QPDFObjectHandle xo_stream = QPDFObjectHandle::newStream(out);
166         QPDFObjectHandle xo_dict = xo_stream.getDict();
167
168         xo_dict.replaceKey("/Type", QPDFObjectHandle::newName("/XObject"));
169         xo_dict.replaceKey("/Subtype", QPDFObjectHandle::newName("/Form"));
170         xo_dict.replaceKey("/FormType", QPDFObjectHandle::newInteger(1));
171
172         BBox box = get_trim_box(page);
173         xo_dict.replaceKey("/BBox", box.to_array());
174
175         xo_dict.replaceKey("/Resources", page.getKey("/Resources"));
176         if (page.hasKey("/Group"))
177                 xo_dict.replaceKey("/Group", page.getKey("/Group"));
178
179         if (page.hasKey("/UserUnit")) {
180                 double u = page.getKey("/UserUnit").getNumericValue();
181                 QPDFObjectHandle m = QPDFObjectHandle::newArray();
182                 m.appendItem(QPDFObjectHandle::newReal(u, 3));
183                 m.appendItem(QPDFObjectHandle::newReal(0, 0));
184                 m.appendItem(QPDFObjectHandle::newReal(0, 0));
185                 m.appendItem(QPDFObjectHandle::newReal(u, 3));
186                 m.appendItem(QPDFObjectHandle::newReal(0, 0));
187                 m.appendItem(QPDFObjectHandle::newReal(0, 0));
188                 xo_dict.replaceKey("/Matrix", m);
189         }
190
191         vector<QPDFObjectHandle> contents = page.getPageContents();
192         auto ph = PointerHolder<QPDFObjectHandle::StreamDataProvider>(new CombineFromContents_Provider(contents));
193         xo_stream.replaceStreamData(ph, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());
194         return xo_stream;
195 }