Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
SkPDFMetadata.cpp
Go to the documentation of this file.
1/*
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
9
12#include "src/base/SkUTF.h"
13#include "src/base/SkUtils.h"
14#include "src/core/SkMD5.h"
15#include "src/pdf/SkPDFTypes.h"
16#include "src/pdf/SkPDFUtils.h"
17
18#include <utility>
19
20static constexpr SkPDF::DateTime kZeroTime = {0, 0, 0, 0, 0, 0, 0, 0};
21
22static bool operator!=(const SkPDF::DateTime& u, const SkPDF::DateTime& v) {
23 return u.fTimeZoneMinutes != v.fTimeZoneMinutes ||
24 u.fYear != v.fYear ||
25 u.fMonth != v.fMonth ||
26 u.fDayOfWeek != v.fDayOfWeek ||
27 u.fDay != v.fDay ||
28 u.fHour != v.fHour ||
29 u.fMinute != v.fMinute ||
30 u.fSecond != v.fSecond;
31}
32
34 int timeZoneMinutes = SkToInt(dt.fTimeZoneMinutes);
35 char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-';
36 int timeZoneHours = SkTAbs(timeZoneMinutes) / 60;
37 timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60;
38 return SkStringPrintf(
39 "D:%04u%02u%02u%02u%02u%02u%c%02d'%02d'",
40 static_cast<unsigned>(dt.fYear), static_cast<unsigned>(dt.fMonth),
41 static_cast<unsigned>(dt.fDay), static_cast<unsigned>(dt.fHour),
42 static_cast<unsigned>(dt.fMinute),
43 static_cast<unsigned>(dt.fSecond), timezoneSign, timeZoneHours,
44 timeZoneMinutes);
45}
46
47namespace {
48static const struct {
49 const char* const key;
50 SkString SkPDF::Metadata::*const valuePtr;
51} gMetadataKeys[] = {
52 {"Title", &SkPDF::Metadata::fTitle},
53 {"Author", &SkPDF::Metadata::fAuthor},
54 {"Subject", &SkPDF::Metadata::fSubject},
55 {"Keywords", &SkPDF::Metadata::fKeywords},
56 {"Creator", &SkPDF::Metadata::fCreator},
57 {"Producer", &SkPDF::Metadata::fProducer},
58};
59} // namespace
60
61std::unique_ptr<SkPDFObject> SkPDFMetadata::MakeDocumentInformationDict(
62 const SkPDF::Metadata& metadata) {
63 auto dict = SkPDFMakeDict();
64 for (const auto keyValuePtr : gMetadataKeys) {
65 const SkString& value = metadata.*(keyValuePtr.valuePtr);
66 if (value.size() > 0) {
67 dict->insertTextString(keyValuePtr.key, value);
68 }
69 }
70 if (metadata.fCreation != kZeroTime) {
71 dict->insertTextString("CreationDate", pdf_date(metadata.fCreation));
72 }
73 if (metadata.fModified != kZeroTime) {
74 dict->insertTextString("ModDate", pdf_date(metadata.fModified));
75 }
76 return dict;
77}
78
80 // The main requirement is for the UUID to be unique; the exact
81 // format of the data that will be hashed is not important.
82 SkMD5 md5;
83 const char uuidNamespace[] = "org.skia.pdf\n";
84 md5.writeText(uuidNamespace);
85 double msec = SkTime::GetMSecs();
86 md5.write(&msec, sizeof(msec));
87 SkPDF::DateTime dateTime;
88 SkPDFUtils::GetDateTime(&dateTime);
89 md5.write(&dateTime, sizeof(dateTime));
90 md5.write(&metadata.fCreation, sizeof(metadata.fCreation));
91 md5.write(&metadata.fModified, sizeof(metadata.fModified));
92
93 for (const auto keyValuePtr : gMetadataKeys) {
94 md5.writeText(keyValuePtr.key);
95 md5.write("\037", 1);
96 const SkString& value = metadata.*(keyValuePtr.valuePtr);
97 md5.write(value.c_str(), value.size());
98 md5.write("\036", 1);
99 }
100 SkMD5::Digest digest = md5.finish();
101 // See RFC 4122, page 6-7.
102 digest.data[6] = (digest.data[6] & 0x0F) | 0x30;
103 digest.data[8] = (digest.data[6] & 0x3F) | 0x80;
104 static_assert(sizeof(digest) == sizeof(SkUUID), "uuid_size");
105 SkUUID uuid;
106 memcpy((void*)&uuid, &digest, sizeof(digest));
107 return uuid;
108}
109
110std::unique_ptr<SkPDFObject> SkPDFMetadata::MakePdfId(const SkUUID& doc, const SkUUID& instance) {
111 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
112 // <81b14aafa313db63dbd6f981e49f94f4> ]
113 auto array = SkPDFMakeArray();
114 static_assert(sizeof(SkUUID) == 16, "uuid_size");
115 array->appendByteString(SkString(reinterpret_cast<const char*>(&doc ), sizeof(SkUUID)));
116 array->appendByteString(SkString(reinterpret_cast<const char*>(&instance), sizeof(SkUUID)));
117 return array;
118}
119
120// Convert a block of memory to hexadecimal. Input and output pointers will be
121// moved to end of the range.
122static void hexify(const uint8_t** inputPtr, char** outputPtr, int count) {
123 SkASSERT(inputPtr && *inputPtr);
124 SkASSERT(outputPtr && *outputPtr);
125 while (count-- > 0) {
126 uint8_t value = *(*inputPtr)++;
127 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value >> 4];
128 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value & 0xF];
129 }
130}
131
132static SkString uuid_to_string(const SkUUID& uuid) {
133 // 8-4-4-4-12
134 char buffer[36]; // [32 + 4]
135 char* ptr = buffer;
136 const uint8_t* data = uuid.fData;
137 hexify(&data, &ptr, 4);
138 *ptr++ = '-';
139 hexify(&data, &ptr, 2);
140 *ptr++ = '-';
141 hexify(&data, &ptr, 2);
142 *ptr++ = '-';
143 hexify(&data, &ptr, 2);
144 *ptr++ = '-';
145 hexify(&data, &ptr, 6);
146 SkASSERT(ptr == buffer + 36);
147 SkASSERT(data == uuid.fData + 16);
148 return SkString(buffer, 36);
149}
150
151namespace {
152class PDFXMLObject final : public SkPDFObject {
153public:
154 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
155 void emitObject(SkWStream* stream) const override {
156 SkPDFDict dict("Metadata");
157 dict.insertName("Subtype", "XML");
158 dict.insertInt("Length", fXML.size());
159 dict.emitObject(stream);
160 static const char streamBegin[] = " stream\n";
161 stream->writeText(streamBegin);
162 // Do not compress this. The standard requires that a
163 // program that does not understand PDF can grep for
164 // "<?xpacket" and extract the entire XML.
165 stream->write(fXML.c_str(), fXML.size());
166 static const char streamEnd[] = "\nendstream";
167 stream->writeText(streamEnd);
168 }
169
170private:
171 const SkString fXML;
172};
173} // namespace
174
175static int count_xml_escape_size(const SkString& input) {
176 int extra = 0;
177 for (size_t i = 0; i < input.size(); ++i) {
178 if (input[i] == '&') {
179 extra += 4; // strlen("&amp;") - strlen("&")
180 } else if (input[i] == '<') {
181 extra += 3; // strlen("&lt;") - strlen("<")
182 }
183 }
184 return extra;
185}
186
188 const char* before = nullptr,
189 const char* after = nullptr) {
190 if (input.size() == 0) {
191 return input;
192 }
193 // "&" --> "&amp;" and "<" --> "&lt;"
194 // text is assumed to be in UTF-8
195 // all strings are xml content, not attribute values.
196 size_t beforeLen = before ? strlen(before) : 0;
197 size_t afterLen = after ? strlen(after) : 0;
198 int extra = count_xml_escape_size(input);
199 SkString output(input.size() + extra + beforeLen + afterLen);
200 char* out = output.data();
201 if (before) {
202 strncpy(out, before, beforeLen);
203 out += beforeLen;
204 }
205 static const char kAmp[] = "&amp;";
206 static const char kLt[] = "&lt;";
207 for (size_t i = 0; i < input.size(); ++i) {
208 if (input[i] == '&') {
209 memcpy(out, kAmp, strlen(kAmp));
210 out += strlen(kAmp);
211 } else if (input[i] == '<') {
212 memcpy(out, kLt, strlen(kLt));
213 out += strlen(kLt);
214 } else {
215 *out++ = input[i];
216 }
217 }
218 if (after) {
219 strncpy(out, after, afterLen);
220 out += afterLen;
221 }
222 // Validate that we haven't written outside of our string.
223 SkASSERT(out == &output.data()[output.size()]);
224 *out = '\0';
225 return output;
226}
227
229 const SkPDF::Metadata& metadata,
230 const SkUUID& doc,
231 const SkUUID& instance,
232 SkPDFDocument* docPtr) {
233 static const char templateString[] =
234 "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
235 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"\n"
236 " x:xmptk=\"Adobe XMP Core 5.4-c005 78.147326, "
237 "2012/08/23-13:03:03\">\n"
238 "<rdf:RDF "
239 "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
240 "<rdf:Description rdf:about=\"\"\n"
241 " xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n"
242 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n"
243 " xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n"
244 " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n"
245 " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
246 "<pdfaid:part>2</pdfaid:part>\n"
247 "<pdfaid:conformance>B</pdfaid:conformance>\n"
248 "%s" // ModifyDate
249 "%s" // CreateDate
250 "%s" // xmp:CreatorTool
251 "<dc:format>application/pdf</dc:format>\n"
252 "%s" // dc:title
253 "%s" // dc:description
254 "%s" // author
255 "%s" // keywords
256 "<xmpMM:DocumentID>uuid:%s</xmpMM:DocumentID>\n"
257 "<xmpMM:InstanceID>uuid:%s</xmpMM:InstanceID>\n"
258 "%s" // pdf:Producer
259 "%s" // pdf:Keywords
260 "</rdf:Description>\n"
261 "</rdf:RDF>\n"
262 "</x:xmpmeta>\n" // Note: the standard suggests 4k of padding.
263 "<?xpacket end=\"w\"?>\n";
264
265 SkString creationDate;
266 SkString modificationDate;
267 if (metadata.fCreation != kZeroTime) {
268 SkString tmp;
269 metadata.fCreation.toISO8601(&tmp);
271 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
272 creationDate = SkStringPrintf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
273 tmp.c_str());
274 }
275 if (metadata.fModified != kZeroTime) {
276 SkString tmp;
277 metadata.fModified.toISO8601(&tmp);
279 modificationDate = SkStringPrintf(
280 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
281 }
282 SkString title =
283 escape_xml(metadata.fTitle,
284 "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">",
285 "</rdf:li></rdf:Alt></dc:title>\n");
286 SkString author =
287 escape_xml(metadata.fAuthor, "<dc:creator><rdf:Seq><rdf:li>",
288 "</rdf:li></rdf:Seq></dc:creator>\n");
289 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
290 SkString subject = escape_xml(
291 metadata.fSubject,
292 "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">",
293 "</rdf:li></rdf:Alt></dc:description>\n");
294 SkString keywords1 =
295 escape_xml(metadata.fKeywords, "<dc:subject><rdf:Bag><rdf:li>",
296 "</rdf:li></rdf:Bag></dc:subject>\n");
297 SkString keywords2 = escape_xml(metadata.fKeywords, "<pdf:Keywords>",
298 "</pdf:Keywords>\n");
299 // TODO: in theory, keywords can be a list too.
300
301 SkString producer = escape_xml(metadata.fProducer, "<pdf:Producer>", "</pdf:Producer>\n");
302
303 SkString creator = escape_xml(metadata.fCreator, "<xmp:CreatorTool>",
304 "</xmp:CreatorTool>\n");
305 SkString documentID = uuid_to_string(doc); // no need to escape
306 SkASSERT(0 == count_xml_escape_size(documentID));
307 SkString instanceID = uuid_to_string(instance);
308 SkASSERT(0 == count_xml_escape_size(instanceID));
309
310
311 auto value = SkStringPrintf(
312 templateString, modificationDate.c_str(), creationDate.c_str(),
313 creator.c_str(), title.c_str(), subject.c_str(), author.c_str(),
314 keywords1.c_str(), documentID.c_str(), instanceID.c_str(),
315 producer.c_str(), keywords2.c_str());
316
317 std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict("Metadata");
318 dict->insertName("Subtype", "XML");
319 return SkPDFStreamOut(std::move(dict),
320 SkMemoryStream::MakeCopy(value.c_str(), value.size()),
322}
323
324#undef SKPDF_CUSTOM_PRODUCER_KEY
325#undef SKPDF_PRODUCER
326#undef SKPDF_STRING
327#undef SKPDF_STRING_IMPL
static SkMD5::Digest md5(const SkBitmap &bm)
Definition CodecTest.cpp:77
int count
#define SkASSERT(cond)
Definition SkAssert.h:116
static bool operator!=(const SkPDF::DateTime &u, const SkPDF::DateTime &v)
static SkString uuid_to_string(const SkUUID &uuid)
static void hexify(const uint8_t **inputPtr, char **outputPtr, int count)
SkString escape_xml(const SkString &input, const char *before=nullptr, const char *after=nullptr)
static int count_xml_escape_size(const SkString &input)
static SkString pdf_date(const SkPDF::DateTime &dt)
static constexpr SkPDF::DateTime kZeroTime
SkPDFIndirectReference SkPDFStreamOut(std::unique_ptr< SkPDFDict > dict, std::unique_ptr< SkStreamAsset > content, SkPDFDocument *doc, SkPDFSteamCompressionEnabled compress)
static std::unique_ptr< SkPDFDict > SkPDFMakeDict(const char *type=nullptr)
Definition SkPDFTypes.h:195
static std::unique_ptr< SkPDFArray > SkPDFMakeArray(Args... args)
Definition SkPDFTypes.h:135
SK_API SkString static SkString SkStringPrintf()
Definition SkString.h:287
static T SkTAbs(T value)
Definition SkTemplates.h:43
constexpr int SkToInt(S x)
Definition SkTo.h:29
Definition SkMD5.h:19
static std::unique_ptr< SkMemoryStream > MakeCopy(const void *data, size_t length)
Definition SkStream.cpp:306
virtual void emitObject(SkWStream *stream) const =0
size_t size() const
Definition SkString.h:131
const char * c_str() const
Definition SkString.h:133
VkInstance instance
Definition main.cc:48
static const uint8_t buffer[]
uint8_t value
const char gLower[16]
Definition SkUtils.cpp:12
std::unique_ptr< SkPDFObject > MakeDocumentInformationDict(const SkPDF::Metadata &)
SkPDFIndirectReference MakeXMPObject(const SkPDF::Metadata &metadata, const SkUUID &doc, const SkUUID &instance, SkPDFDocument *)
SkUUID CreateUUID(const SkPDF::Metadata &)
std::unique_ptr< SkPDFObject > MakePdfId(const SkUUID &doc, const SkUUID &instance)
void GetDateTime(SkPDF::DateTime *)
double GetMSecs()
Definition SkTime.h:17
Definition ref_ptr.h:256
uint8_t data[16]
Definition SkMD5.h:39
uint8_t fMinute
0..59
uint8_t fMonth
1..12
uint8_t fDay
1..31
uint16_t fYear
e.g. 2005
void toISO8601(SkString *dst) const
uint8_t fSecond
0..59
int16_t fTimeZoneMinutes
uint8_t fHour
0..23
uint8_t fDayOfWeek
0..6, 0==Sunday
Definition SkUUID.h:9
uint8_t fData[16]
Definition SkUUID.h:10