blob: addec4f01db57af70114abcd021bfdc952b25cbd [file] [log] [blame]
halcanary34422612015-10-12 10:11:18 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
halcanaryffe54002016-03-29 09:09:29 -07008#include "SkMilestone.h"
halcanary34422612015-10-12 10:11:18 -07009#include "SkPDFMetadata.h"
10#include "SkPDFTypes.h"
bungeman221524d2016-01-05 14:59:40 -080011#include <utility>
halcanary34422612015-10-12 10:11:18 -070012
13#ifdef SK_PDF_GENERATE_PDFA
14#include "SkMD5.h"
15#endif
16
17static SkString pdf_date(const SkTime::DateTime& dt) {
18 int timeZoneMinutes = SkToInt(dt.fTimeZoneMinutes);
19 char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-';
20 int timeZoneHours = SkTAbs(timeZoneMinutes) / 60;
21 timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60;
22 return SkStringPrintf(
23 "D:%04u%02u%02u%02u%02u%02u%c%02d'%02d'",
24 static_cast<unsigned>(dt.fYear), static_cast<unsigned>(dt.fMonth),
25 static_cast<unsigned>(dt.fDay), static_cast<unsigned>(dt.fHour),
26 static_cast<unsigned>(dt.fMinute),
27 static_cast<unsigned>(dt.fSecond), timezoneSign, timeZoneHours,
28 timeZoneMinutes);
29}
30
halcanaryffe54002016-03-29 09:09:29 -070031#define SKPDF_STRING(X) SKPDF_STRING_IMPL(X)
32#define SKPDF_STRING_IMPL(X) #X
33
halcanary34422612015-10-12 10:11:18 -070034SkPDFObject* SkPDFMetadata::createDocumentInformationDict() const {
halcanaryece83922016-03-08 08:32:12 -080035 auto dict = sk_make_sp<SkPDFDict>();
halcanary34422612015-10-12 10:11:18 -070036 static const char* keys[] = {
37 "Title", "Author", "Subject", "Keywords", "Creator"};
38 for (const char* key : keys) {
39 for (const SkDocument::Attribute& keyValue : fInfo) {
40 if (keyValue.fKey.equals(key)) {
41 dict->insertString(key, keyValue.fValue);
42 }
43 }
44 }
halcanaryffe54002016-03-29 09:09:29 -070045 dict->insertString("Producer", "Skia/PDF m" SKPDF_STRING(SK_MILESTONE));
halcanary34422612015-10-12 10:11:18 -070046 if (fCreation) {
47 dict->insertString("CreationDate", pdf_date(*fCreation.get()));
48 }
49 if (fModified) {
50 dict->insertString("ModDate", pdf_date(*fModified.get()));
51 }
halcanaryfcad44b2016-03-06 14:47:10 -080052 return dict.release();
halcanary34422612015-10-12 10:11:18 -070053}
54
halcanaryffe54002016-03-29 09:09:29 -070055#undef SKPDF_STRING
56#undef SKPDF_STRING_IMPL
57
halcanary34422612015-10-12 10:11:18 -070058#ifdef SK_PDF_GENERATE_PDFA
59SkPDFMetadata::UUID SkPDFMetadata::uuid() const {
60 // The main requirement is for the UUID to be unique; the exact
61 // format of the data that will be hashed is not important.
62 SkMD5 md5;
63 const char uuidNamespace[] = "org.skia.pdf\n";
64 md5.write(uuidNamespace, strlen(uuidNamespace));
benjaminwagnerec4d4d72016-03-25 12:59:53 -070065 double msec = SkTime::GetMSecs();
halcanary34422612015-10-12 10:11:18 -070066 md5.write(&msec, sizeof(msec));
67 SkTime::DateTime dateTime;
68 SkTime::GetDateTime(&dateTime);
69 md5.write(&dateTime, sizeof(dateTime));
70 if (fCreation) {
71 md5.write(fCreation.get(), sizeof(fCreation));
72 }
73 if (fModified) {
74 md5.write(fModified.get(), sizeof(fModified));
75 }
76 for (const auto& kv : fInfo) {
77 md5.write(kv.fKey.c_str(), kv.fKey.size());
78 md5.write("\037", 1);
79 md5.write(kv.fValue.c_str(), kv.fValue.size());
80 md5.write("\036", 1);
81 }
82 SkMD5::Digest digest;
83 md5.finish(digest);
84 // See RFC 4122, page 6-7.
85 digest.data[6] = (digest.data[6] & 0x0F) | 0x30;
86 digest.data[8] = (digest.data[6] & 0x3F) | 0x80;
87 static_assert(sizeof(digest) == sizeof(UUID), "uuid_size");
88 SkPDFMetadata::UUID uuid;
89 memcpy(&uuid, &digest, sizeof(digest));
90 return uuid;
91}
92
93SkPDFObject* SkPDFMetadata::CreatePdfId(const UUID& doc, const UUID& instance) {
94 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
95 // <81b14aafa313db63dbd6f981e49f94f4> ]
halcanaryece83922016-03-08 08:32:12 -080096 auto array = sk_make_sp<SkPDFArray>();
halcanary34422612015-10-12 10:11:18 -070097 static_assert(sizeof(UUID) == 16, "uuid_size");
98 array->appendString(
99 SkString(reinterpret_cast<const char*>(&doc), sizeof(UUID)));
100 array->appendString(
101 SkString(reinterpret_cast<const char*>(&instance), sizeof(UUID)));
halcanaryfcad44b2016-03-06 14:47:10 -0800102 return array.release();
halcanary34422612015-10-12 10:11:18 -0700103}
104
105// Improvement on SkStringPrintf to allow for arbitrarily long output.
106// TODO: replace SkStringPrintf.
107static SkString sk_string_printf(const char* format, ...) {
108#ifdef SK_BUILD_FOR_WIN
109 va_list args;
110 va_start(args, format);
111 char buffer[1024];
112 int length = _vsnprintf_s(buffer, sizeof(buffer), _TRUNCATE, format, args);
113 va_end(args);
114 if (length >= 0 && length < (int)sizeof(buffer)) {
115 return SkString(buffer, length);
116 }
117 va_start(args, format);
118 length = _vscprintf(format, args);
119 va_end(args);
120
121 SkString string((size_t)length);
122 va_start(args, format);
123 SkDEBUGCODE(int check = ) _vsnprintf_s(string.writable_str(), length + 1,
124 _TRUNCATE, format, args);
125 va_end(args);
126 SkASSERT(check == length);
127 SkASSERT(string[length] == '\0');
bungeman221524d2016-01-05 14:59:40 -0800128 return std::move(string);
halcanary34422612015-10-12 10:11:18 -0700129#else // C99/C++11 standard vsnprintf
130 // TODO: When all compilers support this, remove windows-specific code.
131 va_list args;
132 va_start(args, format);
133 char buffer[1024];
134 int length = vsnprintf(buffer, sizeof(buffer), format, args);
135 va_end(args);
136 if (length < 0) {
137 return SkString();
138 }
139 if (length < (int)sizeof(buffer)) {
140 return SkString(buffer, length);
141 }
142 SkString string((size_t)length);
143 va_start(args, format);
144 SkDEBUGCODE(int check = )
145 vsnprintf(string.writable_str(), length + 1, format, args);
146 va_end(args);
147 SkASSERT(check == length);
148 SkASSERT(string[length] == '\0');
bungeman221524d2016-01-05 14:59:40 -0800149 return std::move(string);
halcanary34422612015-10-12 10:11:18 -0700150#endif
151}
152
153static const SkString get(const SkTArray<SkDocument::Attribute>& info,
154 const char* key) {
155 for (const auto& keyValue : info) {
156 if (keyValue.fKey.equals(key)) {
157 return keyValue.fValue;
158 }
159 }
160 return SkString();
161}
162
163#define HEXIFY(INPUT_PTR, OUTPUT_PTR, HEX_STRING, BYTE_COUNT) \
164 do { \
165 for (int i = 0; i < (BYTE_COUNT); ++i) { \
166 uint8_t value = *(INPUT_PTR)++; \
167 *(OUTPUT_PTR)++ = (HEX_STRING)[value >> 4]; \
168 *(OUTPUT_PTR)++ = (HEX_STRING)[value & 0xF]; \
169 } \
170 } while (false)
171static SkString uuid_to_string(const SkPDFMetadata::UUID& uuid) {
172 // 8-4-4-4-12
173 char buffer[36]; // [32 + 4]
174 static const char gHex[] = "0123456789abcdef";
175 SkASSERT(strlen(gHex) == 16);
176 char* ptr = buffer;
177 const uint8_t* data = uuid.fData;
178 HEXIFY(data, ptr, gHex, 4);
179 *ptr++ = '-';
180 HEXIFY(data, ptr, gHex, 2);
181 *ptr++ = '-';
182 HEXIFY(data, ptr, gHex, 2);
183 *ptr++ = '-';
184 HEXIFY(data, ptr, gHex, 2);
185 *ptr++ = '-';
186 HEXIFY(data, ptr, gHex, 6);
187 SkASSERT(ptr == buffer + 36);
188 SkASSERT(data == uuid.fData + 16);
189 return SkString(buffer, 36);
190}
191#undef HEXIFY
192
193namespace {
halcanary70d15542015-11-22 12:55:04 -0800194class PDFXMLObject final : public SkPDFObject {
halcanary34422612015-10-12 10:11:18 -0700195public:
bungeman221524d2016-01-05 14:59:40 -0800196 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
halcanary34422612015-10-12 10:11:18 -0700197 void emitObject(SkWStream* stream,
198 const SkPDFObjNumMap& omap,
199 const SkPDFSubstituteMap& smap) const override {
200 SkPDFDict dict("Metadata");
201 dict.insertName("Subtype", "XML");
202 dict.insertInt("Length", fXML.size());
203 dict.emitObject(stream, omap, smap);
204 static const char streamBegin[] = " stream\n";
205 stream->write(streamBegin, strlen(streamBegin));
206 // Do not compress this. The standard requires that a
207 // program that does not understand PDF can grep for
208 // "<?xpacket" and extracť the entire XML.
209 stream->write(fXML.c_str(), fXML.size());
210 static const char streamEnd[] = "\nendstream";
211 stream->write(streamEnd, strlen(streamEnd));
212 }
213
214private:
215 const SkString fXML;
216};
217} // namespace
218
219static int count_xml_escape_size(const SkString& input) {
220 int extra = 0;
221 for (size_t i = 0; i < input.size(); ++i) {
222 if (input[i] == '&') {
223 extra += 4; // strlen("&amp;") - strlen("&")
224 } else if (input[i] == '<') {
225 extra += 3; // strlen("&lt;") - strlen("<")
226 }
227 }
228 return extra;
229}
230
231const SkString escape_xml(const SkString& input,
232 const char* before = nullptr,
233 const char* after = nullptr) {
234 if (input.size() == 0) {
235 return input;
236 }
237 // "&" --> "&amp;" and "<" --> "&lt;"
238 // text is assumed to be in UTF-8
239 // all strings are xml content, not attribute values.
240 size_t beforeLen = before ? strlen(before) : 0;
241 size_t afterLen = after ? strlen(after) : 0;
242 int extra = count_xml_escape_size(input);
243 SkString output(input.size() + extra + beforeLen + afterLen);
244 char* out = output.writable_str();
245 if (before) {
246 strncpy(out, before, beforeLen);
247 out += beforeLen;
248 }
249 static const char kAmp[] = "&amp;";
250 static const char kLt[] = "&lt;";
251 for (size_t i = 0; i < input.size(); ++i) {
252 if (input[i] == '&') {
253 strncpy(out, kAmp, strlen(kAmp));
254 out += strlen(kAmp);
255 } else if (input[i] == '<') {
256 strncpy(out, kLt, strlen(kLt));
257 out += strlen(kLt);
258 } else {
259 *out++ = input[i];
260 }
261 }
262 if (after) {
263 strncpy(out, after, afterLen);
264 out += afterLen;
265 }
266 // Validate that we haven't written outside of our string.
267 SkASSERT(out == &output.writable_str()[output.size()]);
268 *out = '\0';
bungeman221524d2016-01-05 14:59:40 -0800269 return std::move(output);
halcanary34422612015-10-12 10:11:18 -0700270}
271
272SkPDFObject* SkPDFMetadata::createXMPObject(const UUID& doc,
273 const UUID& instance) const {
274 static const char templateString[] =
275 "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
276 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"\n"
277 " x:xmptk=\"Adobe XMP Core 5.4-c005 78.147326, "
278 "2012/08/23-13:03:03\">\n"
279 "<rdf:RDF "
280 "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
281 "<rdf:Description rdf:about=\"\"\n"
282 " xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n"
283 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n"
284 " xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n"
285 " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n"
286 " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
287 "<pdfaid:part>2</pdfaid:part>\n"
288 "<pdfaid:conformance>B</pdfaid:conformance>\n"
289 "%s" // ModifyDate
290 "%s" // CreateDate
291 "%s" // MetadataDate
292 "%s" // xmp:CreatorTool
293 "<dc:format>application/pdf</dc:format>\n"
294 "%s" // dc:title
295 "%s" // dc:description
296 "%s" // author
297 "%s" // keywords
298 "<xmpMM:DocumentID>uuid:%s</xmpMM:DocumentID>\n"
299 "<xmpMM:InstanceID>uuid:%s</xmpMM:InstanceID>\n"
300 "<pdf:Producer>Skia/PDF</pdf:Producer>\n"
301 "%s" // pdf:Keywords
302 "</rdf:Description>\n"
303 "</rdf:RDF>\n"
304 "</x:xmpmeta>\n" // Note: the standard suggests 4k of padding.
305 "<?xpacket end=\"w\"?>\n";
306
307 SkString creationDate;
308 SkString modificationDate;
309 SkString metadataDate;
310 if (fCreation) {
311 SkString tmp;
312 fCreation->toISO8601(&tmp);
313 SkASSERT(0 == count_xml_escape_size(tmp));
314 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
315 creationDate = sk_string_printf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
316 tmp.c_str());
317 }
318 if (fModified) {
319 SkString tmp;
320 fModified->toISO8601(&tmp);
321 SkASSERT(0 == count_xml_escape_size(tmp));
322 modificationDate = sk_string_printf(
323 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
324 metadataDate = sk_string_printf(
325 "<xmp:MetadataDate>%s</xmp:MetadataDate>\n", tmp.c_str());
326 }
327
328 SkString title =
329 escape_xml(get(fInfo, "Title"), "<dc:title><rdf:Alt><rdf:li>",
330 "</rdf:li></rdf:Alt></dc:title>\n");
331 SkString author =
332 escape_xml(get(fInfo, "Author"), "<dc:creator><rdf:Bag><rdf:li>",
333 "</rdf:li></rdf:Bag></dc:creator>\n");
334 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
335 SkString subject = escape_xml(get(fInfo, "Subject"),
336 "<dc:description><rdf:Alt><rdf:li>",
337 "</rdf:li></rdf:Alt></dc:description>\n");
338 SkString keywords1 =
339 escape_xml(get(fInfo, "Keywords"), "<dc:subject><rdf:Bag><rdf:li>",
340 "</rdf:li></rdf:Bag></dc:subject>\n");
341 SkString keywords2 = escape_xml(get(fInfo, "Keywords"), "<pdf:Keywords>",
342 "</pdf:Keywords>\n");
343
344 // TODO: in theory, keywords can be a list too.
345 SkString creator = escape_xml(get(fInfo, "Creator"), "<xmp:CreatorTool>",
346 "</xmp:CreatorTool>\n");
347 SkString documentID = uuid_to_string(doc); // no need to escape
348 SkASSERT(0 == count_xml_escape_size(documentID));
349 SkString instanceID = uuid_to_string(instance);
350 SkASSERT(0 == count_xml_escape_size(instanceID));
351 return new PDFXMLObject(sk_string_printf(
352 templateString, modificationDate.c_str(), creationDate.c_str(),
353 metadataDate.c_str(), creator.c_str(), title.c_str(),
354 subject.c_str(), author.c_str(), keywords1.c_str(),
355 documentID.c_str(), instanceID.c_str(), keywords2.c_str()));
356}
357
358#endif // SK_PDF_GENERATE_PDFA