Flutter Engine
The Flutter Engine
SkPDFDocument.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2011 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
11#include "include/core/SkData.h"
14#include "include/core/SkRect.h"
15#include "include/core/SkSize.h"
25#include "src/base/SkUTF.h"
27#include "src/core/SkTHash.h"
28#include "src/pdf/SkBitmapKey.h"
29#include "src/pdf/SkPDFBitmap.h"
30#include "src/pdf/SkPDFDevice.h"
32#include "src/pdf/SkPDFFont.h"
36#include "src/pdf/SkPDFShader.h"
37#include "src/pdf/SkPDFTag.h"
38#include "src/pdf/SkPDFTypes.h"
39#include "src/pdf/SkPDFUtils.h"
40#include "src/pdf/SkUUID.h"
41
42#include <algorithm>
43#include <atomic>
44#include <cstddef>
45#include <new>
46#include <utility>
47
48// For use in SkCanvas::drawAnnotation
49const char* SkPDFGetNodeIdKey() {
50 static constexpr char key[] = "PDF_Node_Key";
51 return key;
52}
53
55 if (d.size() == 0) {
56 SkDEBUGFAIL("Not a valid string, data length is zero.");
57 return SkString();
58 }
59
60 const char* c_str = static_cast<const char*>(d.data());
61 if (c_str[d.size() - 1] != 0) {
62 SkDEBUGFAIL("Not a valid string, not null-terminated.");
63 return SkString();
64 }
65
66 // CountUTF8 returns -1 if there's an invalid UTF-8 byte sequence.
67 int valid_utf8_chars_count = SkUTF::CountUTF8(c_str, d.size() - 1);
68 if (valid_utf8_chars_count == -1) {
69 SkDEBUGFAIL("Not a valid UTF-8 string.");
70 return SkString();
71 }
72
73 return SkString(c_str, d.size() - 1);
74}
75
76////////////////////////////////////////////////////////////////////////////////
77
78void SkPDFOffsetMap::markStartOfDocument(const SkWStream* s) { fBaseOffset = s->bytesWritten(); }
79
80static size_t difference(size_t minuend, size_t subtrahend) {
81 return SkASSERT(minuend >= subtrahend), minuend - subtrahend;
82}
83
84void SkPDFOffsetMap::markStartOfObject(int referenceNumber, const SkWStream* s) {
85 SkASSERT(referenceNumber > 0);
86 size_t index = SkToSizeT(referenceNumber - 1);
87 if (index >= fOffsets.size()) {
88 fOffsets.resize(index + 1);
89 }
90 fOffsets[index] = SkToInt(difference(s->bytesWritten(), fBaseOffset));
91}
92
94 return SkToInt(fOffsets.size() + 1); // Include the special zeroth object in the count.
95}
96
98 int xRefFileOffset = SkToInt(difference(s->bytesWritten(), fBaseOffset));
99 s->writeText("xref\n0 ");
100 s->writeDecAsText(this->objectCount());
101 s->writeText("\n0000000000 65535 f \n");
102 for (int offset : fOffsets) {
103 SkASSERT(offset > 0); // Offset was set.
104 s->writeBigDecAsText(offset, 10);
105 s->writeText(" 00000 n \n");
106 }
107 return xRefFileOffset;
108}
109//
110////////////////////////////////////////////////////////////////////////////////
111
112#define SKPDF_MAGIC "\xD3\xEB\xE9\xE1"
113#ifndef SK_BUILD_FOR_WIN
114static_assert((SKPDF_MAGIC[0] & 0x7F) == "Skia"[0], "");
115static_assert((SKPDF_MAGIC[1] & 0x7F) == "Skia"[1], "");
116static_assert((SKPDF_MAGIC[2] & 0x7F) == "Skia"[2], "");
117static_assert((SKPDF_MAGIC[3] & 0x7F) == "Skia"[3], "");
118#endif
119static void serializeHeader(SkPDFOffsetMap* offsetMap, SkWStream* wStream) {
120 offsetMap->markStartOfDocument(wStream);
121 wStream->writeText("%PDF-1.4\n%" SKPDF_MAGIC "\n");
122 // The PDF spec recommends including a comment with four
123 // bytes, all with their high bits set. "\xD3\xEB\xE9\xE1" is
124 // "Skia" with the high bits set.
125}
126#undef SKPDF_MAGIC
127
130 SkWStream* s) {
131 offsetMap->markStartOfObject(ref.fValue, s);
132 s->writeDecAsText(ref.fValue);
133 s->writeText(" 0 obj\n"); // Generation number is always 0.
134}
135
136static void end_indirect_object(SkWStream* s) { s->writeText("\nendobj\n"); }
137
138// Xref table and footer
139static void serialize_footer(const SkPDFOffsetMap& offsetMap,
140 SkWStream* wStream,
141 SkPDFIndirectReference infoDict,
142 SkPDFIndirectReference docCatalog,
143 SkUUID uuid) {
144 int xRefFileOffset = offsetMap.emitCrossReferenceTable(wStream);
145 SkPDFDict trailerDict;
146 trailerDict.insertInt("Size", offsetMap.objectCount());
147 SkASSERT(docCatalog != SkPDFIndirectReference());
148 trailerDict.insertRef("Root", docCatalog);
149 SkASSERT(infoDict != SkPDFIndirectReference());
150 trailerDict.insertRef("Info", infoDict);
151 if (SkUUID() != uuid) {
152 trailerDict.insertObject("ID", SkPDFMetadata::MakePdfId(uuid, uuid));
153 }
154 wStream->writeText("trailer\n");
155 trailerDict.emitObject(wStream);
156 wStream->writeText("\nstartxref\n");
157 wStream->writeBigDecAsText(xRefFileOffset);
158 wStream->writeText("\n%%EOF\n");
159}
160
162 SkPDFDocument* doc,
163 std::vector<std::unique_ptr<SkPDFDict>> pages,
164 const std::vector<SkPDFIndirectReference>& pageRefs) {
165 // PDF wants a tree describing all the pages in the document. We arbitrary
166 // choose 8 (kNodeSize) as the number of allowed children. The internal
167 // nodes have type "Pages" with an array of children, a parent pointer, and
168 // the number of leaves below the node as "Count." The leaves are passed
169 // into the method, have type "Page" and need a parent pointer. This method
170 // builds the tree bottom up, skipping internal nodes that would have only
171 // one child.
172 SkASSERT(!pages.empty());
173 struct PageTreeNode {
174 std::unique_ptr<SkPDFDict> fNode;
175 SkPDFIndirectReference fReservedRef;
176 int fPageObjectDescendantCount;
177
178 static std::vector<PageTreeNode> Layer(std::vector<PageTreeNode> vec, SkPDFDocument* doc) {
179 std::vector<PageTreeNode> result;
180 static constexpr size_t kMaxNodeSize = 8;
181 const size_t n = vec.size();
182 SkASSERT(n >= 1);
183 const size_t result_len = (n - 1) / kMaxNodeSize + 1;
184 SkASSERT(result_len >= 1);
185 SkASSERT(n == 1 || result_len < n);
186 result.reserve(result_len);
187 size_t index = 0;
188 for (size_t i = 0; i < result_len; ++i) {
189 if (n != 1 && index + 1 == n) { // No need to create a new node.
190 result.push_back(std::move(vec[index++]));
191 continue;
192 }
193 SkPDFIndirectReference parent = doc->reserveRef();
194 auto kids_list = SkPDFMakeArray();
195 int descendantCount = 0;
196 for (size_t j = 0; j < kMaxNodeSize && index < n; ++j) {
197 PageTreeNode& node = vec[index++];
198 node.fNode->insertRef("Parent", parent);
199 kids_list->appendRef(doc->emit(*node.fNode, node.fReservedRef));
200 descendantCount += node.fPageObjectDescendantCount;
201 }
202 auto next = SkPDFMakeDict("Pages");
203 next->insertInt("Count", descendantCount);
204 next->insertObject("Kids", std::move(kids_list));
205 result.push_back(PageTreeNode{std::move(next), parent, descendantCount});
206 }
207 return result;
208 }
209 };
210 std::vector<PageTreeNode> currentLayer;
211 currentLayer.reserve(pages.size());
212 SkASSERT(pages.size() == pageRefs.size());
213 for (size_t i = 0; i < pages.size(); ++i) {
214 currentLayer.push_back(PageTreeNode{std::move(pages[i]), pageRefs[i], 1});
215 }
216 currentLayer = PageTreeNode::Layer(std::move(currentLayer), doc);
217 while (currentLayer.size() > 1) {
218 currentLayer = PageTreeNode::Layer(std::move(currentLayer), doc);
219 }
220 SkASSERT(currentLayer.size() == 1);
221 const PageTreeNode& root = currentLayer[0];
222 return doc->emit(*root.fNode, root.fReservedRef);
223}
224
225template<typename T, typename... Args>
226static void reset_object(T* dst, Args&&... args) {
227 dst->~T();
228 new (dst) T(std::forward<Args>(args)...);
229}
230
231////////////////////////////////////////////////////////////////////////////////
232
234 SkPDF::Metadata metadata)
236 , fMetadata(std::move(metadata)) {
237 constexpr float kDpiForRasterScaleOne = 72.0f;
238 if (fMetadata.fRasterDPI != kDpiForRasterScaleOne) {
239 fInverseRasterScale = kDpiForRasterScaleOne / fMetadata.fRasterDPI;
240 fRasterScale = fMetadata.fRasterDPI / kDpiForRasterScaleOne;
241 }
242 if (fMetadata.fStructureElementTreeRoot) {
243 fTagTree.init(fMetadata.fStructureElementTreeRoot, fMetadata.fOutline);
244 }
245 fExecutor = fMetadata.fExecutor;
246}
247
249 // subclasses of SkDocument must call close() in their destructors.
250 this->close();
251}
252
254 SkAutoMutexExclusive lock(fMutex);
255 object.emitObject(this->beginObject(ref));
256 this->endObject();
257 return ref;
258}
259
260SkWStream* SkPDFDocument::beginObject(SkPDFIndirectReference ref) SK_REQUIRES(fMutex) {
261 begin_indirect_object(&fOffsetMap, ref, this->getStream());
262 return this->getStream();
263}
264
265void SkPDFDocument::endObject() SK_REQUIRES(fMutex) {
267}
268
269static SkSize operator*(SkISize u, SkScalar s) { return SkSize{u.width() * s, u.height() * s}; }
270static SkSize operator*(SkSize u, SkScalar s) { return SkSize{u.width() * s, u.height() * s}; }
271
273 SkASSERT(fCanvas.imageInfo().dimensions().isZero());
274 if (fPages.empty()) {
275 // if this is the first page if the document.
276 {
277 SkAutoMutexExclusive autoMutexAcquire(fMutex);
278 serializeHeader(&fOffsetMap, this->getStream());
279
280 }
281
282 fInfoDict = this->emit(*SkPDFMetadata::MakeDocumentInformationDict(fMetadata));
283 if (fMetadata.fPDFA) {
284 fUUID = SkPDFMetadata::CreateUUID(fMetadata);
285 // We use the same UUID for Document ID and Instance ID since this
286 // is the first revision of this document (and Skia does not
287 // support revising existing PDF documents).
288 // If we are not in PDF/A mode, don't use a UUID since testing
289 // works best with reproducible outputs.
290 fXMP = SkPDFMetadata::MakeXMPObject(fMetadata, fUUID, fUUID, this);
291 }
292 }
293 // By scaling the page at the device level, we will create bitmap layer
294 // devices at the rasterized scale, not the 72dpi scale. Bitmap layer
295 // devices are created when saveLayer is called with an ImageFilter; see
296 // SkPDFDevice::onCreateDevice().
297 SkISize pageSize = (SkSize{width, height} * fRasterScale).toRound();
298 SkMatrix initialTransform;
299 // Skia uses the top left as the origin but PDF natively has the origin at the
300 // bottom left. This matrix corrects for that, as well as the raster scale.
301 initialTransform.setScaleTranslate(fInverseRasterScale, -fInverseRasterScale,
302 0, fInverseRasterScale * pageSize.height());
303 fPageDevice = sk_make_sp<SkPDFDevice>(pageSize, this, initialTransform);
304 reset_object(&fCanvas, fPageDevice);
305 fCanvas.scale(fRasterScale, fRasterScale);
306 fPageRefs.push_back(this->reserveRef());
307 return &fCanvas;
308}
309
310static void populate_link_annotation(SkPDFDict* annotation, const SkRect& r) {
311 annotation->insertName("Subtype", "Link");
312 annotation->insertInt("F", 4); // required by ISO 19005
313 // Border: 0 = Horizontal corner radius.
314 // 0 = Vertical corner radius.
315 // 0 = Width, 0 = no border.
316 annotation->insertObject("Border", SkPDFMakeArray(0, 0, 0));
317 annotation->insertObject("Rect", SkPDFMakeArray(r.fLeft, r.fTop, r.fRight, r.fBottom));
318}
319
321 SkPDFDocument* doc,
322 const std::vector<SkPDFNamedDestination>& namedDestinations)
323{
324 SkPDFDict destinations;
325 for (const SkPDFNamedDestination& dest : namedDestinations) {
326 auto pdfDest = SkPDFMakeArray();
327 pdfDest->reserve(5);
328 pdfDest->appendRef(dest.fPage);
329 pdfDest->appendName("XYZ");
330 pdfDest->appendScalar(dest.fPoint.x());
331 pdfDest->appendScalar(dest.fPoint.y());
332 pdfDest->appendInt(0); // Leave zoom unchanged
333 destinations.insertObject(ToValidUtf8String(*dest.fName), std::move(pdfDest));
334 }
335 return doc->emit(destinations);
336}
337
338std::unique_ptr<SkPDFArray> SkPDFDocument::getAnnotations() {
339 std::unique_ptr<SkPDFArray> array;
340 size_t count = fCurrentPageLinks.size();
341 if (0 == count) {
342 return array; // is nullptr
343 }
344 array = SkPDFMakeArray();
345 array->reserve(count);
346 for (const auto& link : fCurrentPageLinks) {
347 SkPDFDict annotation("Annot");
348 populate_link_annotation(&annotation, link->fRect);
349 if (link->fType == SkPDFLink::Type::kUrl) {
350 std::unique_ptr<SkPDFDict> action = SkPDFMakeDict("Action");
351 action->insertName("S", "URI");
352 // This is documented to be a 7 bit ASCII (byte) string.
353 action->insertByteString("URI", ToValidUtf8String(*link->fData));
354 annotation.insertObject("A", std::move(action));
355 } else if (link->fType == SkPDFLink::Type::kNamedDestination) {
356 annotation.insertName("Dest", ToValidUtf8String(*link->fData));
357 } else {
358 SkDEBUGFAIL("Unknown link type.");
359 }
360
361 if (link->fNodeId) {
362 int structParentKey = createStructParentKeyForNodeId(link->fNodeId);
363 if (structParentKey != -1) {
364 annotation.insertInt("StructParent", structParentKey);
365 }
366 }
367
368 SkPDFIndirectReference annotationRef = emit(annotation);
369 array->appendRef(annotationRef);
370 if (link->fNodeId) {
371 fTagTree.addNodeAnnotation(link->fNodeId, annotationRef, SkToUInt(this->currentPageIndex()));
372 }
373 }
374 return array;
375}
376
378 SkASSERT(!fCanvas.imageInfo().dimensions().isZero());
379 reset_object(&fCanvas);
380 SkASSERT(fPageDevice);
381
382 auto page = SkPDFMakeDict("Page");
383
384 SkSize mediaSize = fPageDevice->imageInfo().dimensions() * fInverseRasterScale;
385 std::unique_ptr<SkStreamAsset> pageContent = fPageDevice->content();
386 auto resourceDict = fPageDevice->makeResourceDict();
387 SkASSERT(!fPageRefs.empty());
388 fPageDevice = nullptr;
389
390 page->insertObject("Resources", std::move(resourceDict));
391 page->insertObject("MediaBox", SkPDFUtils::RectToArray(SkRect::MakeSize(mediaSize)));
392
393 if (std::unique_ptr<SkPDFArray> annotations = getAnnotations()) {
394 page->insertObject("Annots", std::move(annotations));
395 fCurrentPageLinks.clear();
396 }
397
398 page->insertRef("Contents", SkPDFStreamOut(nullptr, std::move(pageContent), this));
399 // The StructParents unique identifier for each page is just its
400 // 0-based page index.
401 page->insertInt("StructParents", SkToInt(this->currentPageIndex()));
402 fPages.emplace_back(std::move(page));
403}
404
406 this->waitForJobs();
407}
408
410 // Source: http://www.argyllcms.com/icclibsrc.html
411 static const char kProfile[] =
412 "\0\0\14\214argl\2 \0\0mntrRGB XYZ \7\336\0\1\0\6\0\26\0\17\0:acspM"
413 "SFT\0\0\0\0IEC sRGB\0\0\0\0\0\0\0\0\0\0\0\0\0\0\366\326\0\1\0\0\0\0"
414 "\323-argl\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
415 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\21desc\0\0\1P\0\0\0\231cprt\0"
416 "\0\1\354\0\0\0gdmnd\0\0\2T\0\0\0pdmdd\0\0\2\304\0\0\0\210tech\0\0\3"
417 "L\0\0\0\14vued\0\0\3X\0\0\0gview\0\0\3\300\0\0\0$lumi\0\0\3\344\0\0"
418 "\0\24meas\0\0\3\370\0\0\0$wtpt\0\0\4\34\0\0\0\24bkpt\0\0\0040\0\0\0"
419 "\24rXYZ\0\0\4D\0\0\0\24gXYZ\0\0\4X\0\0\0\24bXYZ\0\0\4l\0\0\0\24rTR"
420 "C\0\0\4\200\0\0\10\14gTRC\0\0\4\200\0\0\10\14bTRC\0\0\4\200\0\0\10"
421 "\14desc\0\0\0\0\0\0\0?sRGB IEC61966-2.1 (Equivalent to www.srgb.co"
422 "m 1998 HP profile)\0\0\0\0\0\0\0\0\0\0\0?sRGB IEC61966-2.1 (Equiva"
423 "lent to www.srgb.com 1998 HP profile)\0\0\0\0\0\0\0\0text\0\0\0\0C"
424 "reated by Graeme W. Gill. Released into the public domain. No Warr"
425 "anty, Use at your own risk.\0\0desc\0\0\0\0\0\0\0\26IEC http://www"
426 ".iec.ch\0\0\0\0\0\0\0\0\0\0\0\26IEC http://www.iec.ch\0\0\0\0\0\0\0"
427 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
428 "\0\0\0\0\0\0desc\0\0\0\0\0\0\0.IEC 61966-2.1 Default RGB colour sp"
429 "ace - sRGB\0\0\0\0\0\0\0\0\0\0\0.IEC 61966-2.1 Default RGB colour "
430 "space - sRGB\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0sig \0\0\0"
431 "\0CRT desc\0\0\0\0\0\0\0\rIEC61966-2.1\0\0\0\0\0\0\0\0\0\0\0\rIEC6"
432 "1966-2.1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
433 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0view\0\0\0\0"
434 "\0\23\244|\0\24_0\0\20\316\2\0\3\355\262\0\4\23\n\0\3\\g\0\0\0\1XY"
435 "Z \0\0\0\0\0L\n=\0P\0\0\0W\36\270meas\0\0\0\0\0\0\0\1\0\0\0\0\0\0\0"
436 "\0\0\0\0\0\0\0\0\0\0\0\2\217\0\0\0\2XYZ \0\0\0\0\0\0\363Q\0\1\0\0\0"
437 "\1\26\314XYZ \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0XYZ \0\0\0\0\0\0o\240"
438 "\0\0008\365\0\0\3\220XYZ \0\0\0\0\0\0b\227\0\0\267\207\0\0\30\331X"
439 "YZ \0\0\0\0\0\0$\237\0\0\17\204\0\0\266\304curv\0\0\0\0\0\0\4\0\0\0"
440 "\0\5\0\n\0\17\0\24\0\31\0\36\0#\0(\0-\0002\0007\0;\0@\0E\0J\0O\0T\0"
441 "Y\0^\0c\0h\0m\0r\0w\0|\0\201\0\206\0\213\0\220\0\225\0\232\0\237\0"
442 "\244\0\251\0\256\0\262\0\267\0\274\0\301\0\306\0\313\0\320\0\325\0"
443 "\333\0\340\0\345\0\353\0\360\0\366\0\373\1\1\1\7\1\r\1\23\1\31\1\37"
444 "\1%\1+\0012\0018\1>\1E\1L\1R\1Y\1`\1g\1n\1u\1|\1\203\1\213\1\222\1"
445 "\232\1\241\1\251\1\261\1\271\1\301\1\311\1\321\1\331\1\341\1\351\1"
446 "\362\1\372\2\3\2\14\2\24\2\35\2&\2/\0028\2A\2K\2T\2]\2g\2q\2z\2\204"
447 "\2\216\2\230\2\242\2\254\2\266\2\301\2\313\2\325\2\340\2\353\2\365"
448 "\3\0\3\13\3\26\3!\3-\0038\3C\3O\3Z\3f\3r\3~\3\212\3\226\3\242\3\256"
449 "\3\272\3\307\3\323\3\340\3\354\3\371\4\6\4\23\4 \4-\4;\4H\4U\4c\4q"
450 "\4~\4\214\4\232\4\250\4\266\4\304\4\323\4\341\4\360\4\376\5\r\5\34"
451 "\5+\5:\5I\5X\5g\5w\5\206\5\226\5\246\5\265\5\305\5\325\5\345\5\366"
452 "\6\6\6\26\6'\0067\6H\6Y\6j\6{\6\214\6\235\6\257\6\300\6\321\6\343\6"
453 "\365\7\7\7\31\7+\7=\7O\7a\7t\7\206\7\231\7\254\7\277\7\322\7\345\7"
454 "\370\10\13\10\37\0102\10F\10Z\10n\10\202\10\226\10\252\10\276\10\322"
455 "\10\347\10\373\t\20\t%\t:\tO\td\ty\t\217\t\244\t\272\t\317\t\345\t"
456 "\373\n\21\n'\n=\nT\nj\n\201\n\230\n\256\n\305\n\334\n\363\13\13\13"
457 "\"\0139\13Q\13i\13\200\13\230\13\260\13\310\13\341\13\371\14\22\14"
458 "*\14C\14\\\14u\14\216\14\247\14\300\14\331\14\363\r\r\r&\r@\rZ\rt\r"
459 "\216\r\251\r\303\r\336\r\370\16\23\16.\16I\16d\16\177\16\233\16\266"
460 "\16\322\16\356\17\t\17%\17A\17^\17z\17\226\17\263\17\317\17\354\20"
461 "\t\20&\20C\20a\20~\20\233\20\271\20\327\20\365\21\23\0211\21O\21m\21"
462 "\214\21\252\21\311\21\350\22\7\22&\22E\22d\22\204\22\243\22\303\22"
463 "\343\23\3\23#\23C\23c\23\203\23\244\23\305\23\345\24\6\24'\24I\24j"
464 "\24\213\24\255\24\316\24\360\25\22\0254\25V\25x\25\233\25\275\25\340"
465 "\26\3\26&\26I\26l\26\217\26\262\26\326\26\372\27\35\27A\27e\27\211"
466 "\27\256\27\322\27\367\30\33\30@\30e\30\212\30\257\30\325\30\372\31"
467 " \31E\31k\31\221\31\267\31\335\32\4\32*\32Q\32w\32\236\32\305\32\354"
468 "\33\24\33;\33c\33\212\33\262\33\332\34\2\34*\34R\34{\34\243\34\314"
469 "\34\365\35\36\35G\35p\35\231\35\303\35\354\36\26\36@\36j\36\224\36"
470 "\276\36\351\37\23\37>\37i\37\224\37\277\37\352 \25 A l \230 \304 \360"
471 "!\34!H!u!\241!\316!\373\"'\"U\"\202\"\257\"\335#\n#8#f#\224#\302#\360"
472 "$\37$M$|$\253$\332%\t%8%h%\227%\307%\367&'&W&\207&\267&\350'\30'I'"
473 "z'\253'\334(\r(?(q(\242(\324)\6)8)k)\235)\320*\2*5*h*\233*\317+\2+"
474 "6+i+\235+\321,\5,9,n,\242,\327-\14-A-v-\253-\341.\26.L.\202.\267.\356"
475 "/$/Z/\221/\307/\376050l0\2440\3331\0221J1\2021\2721\3622*2c2\2332\324"
476 "3\r3F3\1773\2703\3614+4e4\2364\3305\0235M5\2075\3025\375676r6\2566"
477 "\3517$7`7\2347\3278\0248P8\2148\3109\0059B9\1779\2749\371:6:t:\262"
478 ":\357;-;k;\252;\350<'<e<\244<\343=\"=a=\241=\340> >`>\240>\340?!?a"
479 "?\242?\342@#@d@\246@\347A)AjA\254A\356B0BrB\265B\367C:C}C\300D\3DG"
480 "D\212D\316E\22EUE\232E\336F\"FgF\253F\360G5G{G\300H\5HKH\221H\327I"
481 "\35IcI\251I\360J7J}J\304K\14KSK\232K\342L*LrL\272M\2MJM\223M\334N%"
482 "NnN\267O\0OIO\223O\335P'PqP\273Q\6QPQ\233Q\346R1R|R\307S\23S_S\252"
483 "S\366TBT\217T\333U(UuU\302V\17V\\V\251V\367WDW\222W\340X/X}X\313Y\32"
484 "YiY\270Z\7ZVZ\246Z\365[E[\225[\345\\5\\\206\\\326]']x]\311^\32^l^\275"
485 "_\17_a_\263`\5`W`\252`\374aOa\242a\365bIb\234b\360cCc\227c\353d@d\224"
486 "d\351e=e\222e\347f=f\222f\350g=g\223g\351h?h\226h\354iCi\232i\361j"
487 "Hj\237j\367kOk\247k\377lWl\257m\10m`m\271n\22nkn\304o\36oxo\321p+p"
488 "\206p\340q:q\225q\360rKr\246s\1s]s\270t\24tpt\314u(u\205u\341v>v\233"
489 "v\370wVw\263x\21xnx\314y*y\211y\347zFz\245{\4{c{\302|!|\201|\341}A"
490 "}\241~\1~b~\302\177#\177\204\177\345\200G\200\250\201\n\201k\201\315"
491 "\2020\202\222\202\364\203W\203\272\204\35\204\200\204\343\205G\205"
492 "\253\206\16\206r\206\327\207;\207\237\210\4\210i\210\316\2113\211\231"
493 "\211\376\212d\212\312\2130\213\226\213\374\214c\214\312\2151\215\230"
494 "\215\377\216f\216\316\2176\217\236\220\6\220n\220\326\221?\221\250"
495 "\222\21\222z\222\343\223M\223\266\224 \224\212\224\364\225_\225\311"
496 "\2264\226\237\227\n\227u\227\340\230L\230\270\231$\231\220\231\374"
497 "\232h\232\325\233B\233\257\234\34\234\211\234\367\235d\235\322\236"
498 "@\236\256\237\35\237\213\237\372\240i\240\330\241G\241\266\242&\242"
499 "\226\243\6\243v\243\346\244V\244\307\2458\245\251\246\32\246\213\246"
500 "\375\247n\247\340\250R\250\304\2517\251\251\252\34\252\217\253\2\253"
501 "u\253\351\254\\\254\320\255D\255\270\256-\256\241\257\26\257\213\260"
502 "\0\260u\260\352\261`\261\326\262K\262\302\2638\263\256\264%\264\234"
503 "\265\23\265\212\266\1\266y\266\360\267h\267\340\270Y\270\321\271J\271"
504 "\302\272;\272\265\273.\273\247\274!\274\233\275\25\275\217\276\n\276"
505 "\204\276\377\277z\277\365\300p\300\354\301g\301\343\302_\302\333\303"
506 "X\303\324\304Q\304\316\305K\305\310\306F\306\303\307A\307\277\310="
507 "\310\274\311:\311\271\3128\312\267\3136\313\266\3145\314\265\3155\315"
508 "\265\3166\316\266\3177\317\270\3209\320\272\321<\321\276\322?\322\301"
509 "\323D\323\306\324I\324\313\325N\325\321\326U\326\330\327\\\327\340"
510 "\330d\330\350\331l\331\361\332v\332\373\333\200\334\5\334\212\335\20"
511 "\335\226\336\34\336\242\337)\337\257\3406\340\275\341D\341\314\342"
512 "S\342\333\343c\343\353\344s\344\374\345\204\346\r\346\226\347\37\347"
513 "\251\3502\350\274\351F\351\320\352[\352\345\353p\353\373\354\206\355"
514 "\21\355\234\356(\356\264\357@\357\314\360X\360\345\361r\361\377\362"
515 "\214\363\31\363\247\3644\364\302\365P\365\336\366m\366\373\367\212"
516 "\370\31\370\250\3718\371\307\372W\372\347\373w\374\7\374\230\375)\375"
517 "\272\376K\376\334\377m\377\377";
518 const size_t kProfileLength = 3212;
519 static_assert(kProfileLength == sizeof(kProfile) - 1, "");
520 return SkData::MakeWithoutCopy(kProfile, kProfileLength);
521}
522
524 std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict();
525 dict->insertInt("N", 3);
526 dict->insertObject("Range", SkPDFMakeArray(0, 1, 0, 1, 0, 1));
527 return SkPDFStreamOut(std::move(dict), SkMemoryStream::Make(SkSrgbIcm()),
529}
530
531static std::unique_ptr<SkPDFArray> make_srgb_output_intents(SkPDFDocument* doc) {
532 // sRGB is specified by HTML, CSS, and SVG.
533 auto outputIntent = SkPDFMakeDict("OutputIntent");
534 outputIntent->insertName("S", "GTS_PDFA1");
535 outputIntent->insertTextString("RegistryName", "http://www.color.org");
536 outputIntent->insertTextString("OutputConditionIdentifier", "Custom");
537 outputIntent->insertTextString("Info", "sRGB IEC61966-2.1");
538 outputIntent->insertRef("DestOutputProfile", make_srgb_color_profile(doc));
539 auto intentArray = SkPDFMakeArray();
540 intentArray->appendObject(std::move(outputIntent));
541 return intentArray;
542}
543
545 SkASSERT(pageIndex < fPageRefs.size());
546 return fPageRefs[pageIndex];
547}
548
550 static constexpr const SkMatrix gIdentity;
551 // If not on a page (like when emitting a Type3 glyph) return identity.
552 if (!this->hasCurrentPage()) {
553 return gIdentity;
554 }
555 return fPageDevice->initialTransform();
556}
557
559 // If the mark isn't on a page (like when emitting a Type3 glyph)
560 // return a temporary mark not attached to the tag tree, node id, or page.
561 if (!this->hasCurrentPage()) {
562 return SkPDFTagTree::Mark();
563 }
564 return fTagTree.createMarkIdForNodeId(nodeId, SkToUInt(this->currentPageIndex()), p);
565}
566
568 fTagTree.addNodeTitle(nodeId, std::move(title));
569}
570
572 // Structure elements are tied to pages, so don't emit one if not on a page.
573 if (!this->hasCurrentPage()) {
574 return -1;
575 }
576 return fTagTree.createStructParentKeyForNodeId(nodeId, SkToUInt(this->currentPageIndex()));
577}
578
579static std::vector<const SkPDFFont*> get_fonts(const SkPDFDocument& canon) {
580 std::vector<const SkPDFFont*> fonts;
581 fonts.reserve(canon.fFontMap.count());
582 // Sort so the output PDF is reproducible.
583 for (const auto& [unused, font] : canon.fFontMap) {
584 fonts.push_back(&font);
585 }
586 std::sort(fonts.begin(), fonts.end(), [](const SkPDFFont* u, const SkPDFFont* v) {
587 return u->indirectReference().fValue < v->indirectReference().fValue;
588 });
589 return fonts;
590}
591
593 // PDF 32000-1:2008 Section 9.6.4 FontSubsets "The tag shall consist of six uppercase letters"
594 // "followed by a plus sign" "different subsets in the same PDF file shall have different tags."
595 // There are 26^6 or 308,915,776 possible values. So start in range then increment and mod.
596 uint32_t thisFontSubsetTag = fNextFontSubsetTag;
597 fNextFontSubsetTag = (fNextFontSubsetTag + 1u) % 308915776u;
598
599 SkString subsetTag(7);
600 char* subsetTagData = subsetTag.data();
601 for (size_t i = 0; i < 6; ++i) {
602 subsetTagData[i] = 'A' + (thisFontSubsetTag % 26);
603 thisFontSubsetTag /= 26;
604 }
605 subsetTagData[6] = '+';
606 return subsetTag;
607}
608
610 SkASSERT(fCanvas.imageInfo().dimensions().isZero());
611 if (fPages.empty()) {
612 this->waitForJobs();
613 return;
614 }
615 auto docCatalog = SkPDFMakeDict("Catalog");
616 if (fMetadata.fPDFA) {
618 docCatalog->insertRef("Metadata", fXMP);
619 // Don't specify OutputIntents if we are not in PDF/A mode since
620 // no one has ever asked for this feature.
621 docCatalog->insertObject("OutputIntents", make_srgb_output_intents(this));
622 }
623
624 docCatalog->insertRef("Pages", generate_page_tree(this, std::move(fPages), fPageRefs));
625
626 if (!fNamedDestinations.empty()) {
627 docCatalog->insertRef("Dests", append_destinations(this, fNamedDestinations));
628 fNamedDestinations.clear();
629 }
630
631 // Handle tagged PDFs.
632 if (SkPDFIndirectReference root = fTagTree.makeStructTreeRoot(this)) {
633 // In the document catalog, indicate that this PDF is tagged.
634 auto markInfo = SkPDFMakeDict("MarkInfo");
635 markInfo->insertBool("Marked", true);
636 docCatalog->insertObject("MarkInfo", std::move(markInfo));
637 docCatalog->insertRef("StructTreeRoot", root);
638
639 if (SkPDFIndirectReference outline = fTagTree.makeOutline(this)) {
640 docCatalog->insertRef("Outlines", outline);
641 }
642 }
643
644 // If ViewerPreferences DisplayDocTitle isn't set to true, accessibility checks will fail.
645 if (!fMetadata.fTitle.isEmpty()) {
646 auto viewerPrefs = SkPDFMakeDict("ViewerPreferences");
647 viewerPrefs->insertBool("DisplayDocTitle", true);
648 docCatalog->insertObject("ViewerPreferences", std::move(viewerPrefs));
649 }
650
651 SkString lang = fMetadata.fLang;
652 if (lang.isEmpty()) {
653 lang = fTagTree.getRootLanguage();
654 }
655 if (!lang.isEmpty()) {
656 docCatalog->insertTextString("Lang", lang);
657 }
658
659 auto docCatalogRef = this->emit(*docCatalog);
660
661 for (const SkPDFFont* f : get_fonts(*this)) {
662 f->emitSubset(this);
663 }
664
665 this->waitForJobs();
666 {
667 SkAutoMutexExclusive autoMutexAcquire(fMutex);
668 serialize_footer(fOffsetMap, this->getStream(), fInfoDict, docCatalogRef, fUUID);
669 }
670}
671
672void SkPDFDocument::incrementJobCount() { fJobCount++; }
673
675
676void SkPDFDocument::waitForJobs() {
677 // fJobCount can increase while we wait.
678 while (fJobCount > 0) {
679 fSemaphore.wait();
680 --fJobCount;
681 }
682}
683
684///////////////////////////////////////////////////////////////////////////////
685
686void SkPDF::SetNodeId(SkCanvas* canvas, int nodeID) {
687 sk_sp<SkData> payload = SkData::MakeWithCopy(&nodeID, sizeof(nodeID));
688 const char* key = SkPDFGetNodeIdKey();
689 canvas->drawAnnotation({0, 0, 0, 0}, key, payload.get());
690}
691
693 SkPDF::Metadata meta = metadata;
694 if (meta.fRasterDPI <= 0) {
695 meta.fRasterDPI = 72.0f;
696 }
697 if (meta.fEncodingQuality < 0) {
698 meta.fEncodingQuality = 0;
699 }
700 return stream ? sk_make_sp<SkPDFDocument>(stream, std::move(meta)) : nullptr;
701}
702
703///////////////////////////////////////////////////////////////////////////////
705 if (dst) {
706 int timeZoneMinutes = SkToInt(fTimeZoneMinutes);
707 char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-';
708 int timeZoneHours = SkTAbs(timeZoneMinutes) / 60;
709 timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60;
710 dst->printf("%04u-%02u-%02uT%02u:%02u:%02u%c%02d:%02d",
711 static_cast<unsigned>(fYear), static_cast<unsigned>(fMonth),
712 static_cast<unsigned>(fDay), static_cast<unsigned>(fHour),
713 static_cast<unsigned>(fMinute),
714 static_cast<unsigned>(fSecond), timezoneSign, timeZoneHours,
715 timeZoneMinutes);
716 }
717}
static bool unused
int count
Definition: FontMgrTest.cpp:50
static float next(float f)
#define SkDEBUGFAIL(message)
Definition: SkAssert.h:118
#define SkASSERT(cond)
Definition: SkAssert.h:116
static std::vector< SkPDFIndirectReference > sort(const THashSet< SkPDFIndirectReference > &src)
static void end_indirect_object(SkWStream *s)
static SkPDFIndirectReference make_srgb_color_profile(SkPDFDocument *doc)
static void populate_link_annotation(SkPDFDict *annotation, const SkRect &r)
#define SKPDF_MAGIC
static SkSize operator*(SkISize u, SkScalar s)
static SkString ToValidUtf8String(const SkData &d)
const char * SkPDFGetNodeIdKey()
static sk_sp< SkData > SkSrgbIcm()
static void serializeHeader(SkPDFOffsetMap *offsetMap, SkWStream *wStream)
static SkPDFIndirectReference generate_page_tree(SkPDFDocument *doc, std::vector< std::unique_ptr< SkPDFDict > > pages, const std::vector< SkPDFIndirectReference > &pageRefs)
static size_t difference(size_t minuend, size_t subtrahend)
static SkPDFIndirectReference append_destinations(SkPDFDocument *doc, const std::vector< SkPDFNamedDestination > &namedDestinations)
static void reset_object(T *dst, Args &&... args)
static std::unique_ptr< SkPDFArray > make_srgb_output_intents(SkPDFDocument *doc)
static void serialize_footer(const SkPDFOffsetMap &offsetMap, SkWStream *wStream, SkPDFIndirectReference infoDict, SkPDFIndirectReference docCatalog, SkUUID uuid)
static void begin_indirect_object(SkPDFOffsetMap *offsetMap, SkPDFIndirectReference ref, SkWStream *s)
static std::vector< const SkPDFFont * > get_fonts(const SkPDFDocument &canon)
SkPDFIndirectReference SkPDFStreamOut(std::unique_ptr< SkPDFDict > dict, std::unique_ptr< SkStreamAsset > content, SkPDFDocument *doc, SkPDFSteamCompressionEnabled compress)
Definition: SkPDFTypes.cpp:591
static std::unique_ptr< SkPDFDict > SkPDFMakeDict(const char *type=nullptr)
Definition: SkPDFTypes.h:185
static std::unique_ptr< SkPDFArray > SkPDFMakeArray(Args... args)
Definition: SkPDFTypes.h:125
static T SkTAbs(T value)
Definition: SkTemplates.h:43
#define SK_REQUIRES(...)
constexpr size_t SkToSizeT(S x)
Definition: SkTo.h:31
constexpr int SkToInt(S x)
Definition: SkTo.h:29
constexpr unsigned SkToUInt(S x)
Definition: SkTo.h:30
void drawAnnotation(const SkRect &rect, const char key[], SkData *value)
Definition: SkCanvas.cpp:1824
void scale(SkScalar sx, SkScalar sy)
Definition: SkCanvas.cpp:1289
SkImageInfo imageInfo() const
Definition: SkCanvas.cpp:1206
Definition: SkData.h:25
static sk_sp< SkData > MakeWithoutCopy(const void *data, size_t length)
Definition: SkData.h:116
static sk_sp< SkData > MakeWithCopy(const void *data, size_t length)
Definition: SkData.cpp:111
const SkImageInfo & imageInfo() const
Definition: SkDevice.h:117
SkWStream * getStream()
Definition: SkDocument.h:77
void close()
Definition: SkDocument.cpp:52
void setScaleTranslate(SkScalar sx, SkScalar sy, SkScalar tx, SkScalar ty)
Definition: SkMatrix.h:1803
static std::unique_ptr< SkMemoryStream > Make(sk_sp< SkData > data)
Definition: SkStream.cpp:314
std::unique_ptr< SkStreamAsset > content()
std::unique_ptr< SkPDFDict > makeResourceDict()
const SkMatrix & initialTransform() const
Definition: SkPDFDevice.h:124
void insertName(const char key[], const char nameValue[])
Definition: SkPDFTypes.cpp:512
void insertObject(const char key[], std::unique_ptr< SkPDFObject > &&)
Definition: SkPDFTypes.cpp:484
void insertInt(const char key[], int32_t value)
Definition: SkPDFTypes.cpp:496
void insertRef(const char key[], SkPDFIndirectReference)
Definition: SkPDFTypes.cpp:476
void emitObject(SkWStream *stream) const override
Definition: SkPDFTypes.cpp:456
void onClose(SkWStream *) override
SkPDFIndirectReference emit(const SkPDFObject &, SkPDFIndirectReference)
size_t currentPageIndex()
void addNodeTitle(int nodeId, SkSpan< const char >)
void signalJobComplete()
const SkMatrix & currentPageTransform() const
std::vector< SkPDFNamedDestination > fNamedDestinations
void incrementJobCount()
SkPDFTagTree::Mark createMarkIdForNodeId(int nodeId, SkPoint)
skia_private::THashMap< uint64_t, SkPDFFont > fFontMap
std::unique_ptr< SkPDFArray > getAnnotations()
std::vector< std::unique_ptr< SkPDFLink > > fCurrentPageLinks
void onAbort() override
int createStructParentKeyForNodeId(int nodeId)
SkCanvas * onBeginPage(SkScalar, SkScalar) override
SkPDFDocument(SkWStream *, SkPDF::Metadata)
SkString nextFontSubsetTag()
~SkPDFDocument() override
void onEndPage() override
SkPDFIndirectReference reserveRef()
SkPDFIndirectReference getPage(size_t pageIndex) const
bool hasCurrentPage() const
void markStartOfObject(int referenceNumber, const SkWStream *)
void markStartOfDocument(const SkWStream *)
int emitCrossReferenceTable(SkWStream *s) const
int objectCount() const
SkPDFIndirectReference makeStructTreeRoot(SkPDFDocument *doc)
Definition: SkPDFTag.cpp:364
int createStructParentKeyForNodeId(int nodeId, unsigned pageIndex)
Definition: SkPDFTag.cpp:238
void init(SkPDF::StructureElementNode *, SkPDF::Metadata::Outline)
Definition: SkPDFTag.cpp:202
SkPDFIndirectReference makeOutline(SkPDFDocument *doc)
Definition: SkPDFTag.cpp:559
void addNodeAnnotation(int nodeId, SkPDFIndirectReference annotationRef, unsigned pageIndex)
Definition: SkPDFTag.cpp:329
SkString getRootLanguage()
Definition: SkPDFTag.cpp:583
Mark createMarkIdForNodeId(int nodeId, unsigned pageIndex, SkPoint)
Definition: SkPDFTag.cpp:218
void addNodeTitle(int nodeId, SkSpan< const char >)
Definition: SkPDFTag.cpp:344
void ref() const
Definition: SkRefCnt.h:62
void signal(int n=1)
Definition: SkSemaphore.h:56
void wait()
Definition: SkSemaphore.h:74
const char * data() const
Definition: SkString.h:132
bool isEmpty() const
Definition: SkString.h:130
bool writeBigDecAsText(int64_t, int minDigits=0)
Definition: SkStream.cpp:88
bool writeText(const char text[])
Definition: SkStream.h:247
T * get() const
Definition: SkRefCnt.h:303
int count() const
Definition: SkTHash.h:471
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE auto & d
Definition: main.cc:19
float SkScalar
Definition: extension.cpp:12
struct MyStruct s
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
GAsyncResult * result
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)
std::unique_ptr< SkPDFArray > RectToArray(const SkRect &rect)
Definition: SkPDFUtils.cpp:63
SK_API sk_sp< SkDocument > MakeDocument(SkWStream *stream, const Metadata &metadata)
SK_API void SetNodeId(SkCanvas *dst, int nodeID)
SK_SPI int CountUTF8(const char *utf8, size_t byteLength)
Definition: SkUTF.cpp:47
def link(from_root, to_root)
Definition: dart_pkg.py:44
it will be possible to load the file into Perfetto s trace viewer disable asset fonts
Definition: switches.h:213
font
Font Metadata and Metrics.
dst
Definition: cp.py:12
string root
Definition: scale_cpu.py:20
Definition: ref_ptr.h:256
dest
Definition: zip.py:79
#define T
Definition: precompiler.cc:65
int32_t height
int32_t width
SeparatedVector2 offset
Definition: SkSize.h:16
constexpr int32_t width() const
Definition: SkSize.h:36
constexpr int32_t height() const
Definition: SkSize.h:37
bool isZero() const
Definition: SkSize.h:28
SkISize dimensions() const
Definition: SkImageInfo.h:421
uint8_t fMinute
0..59
Definition: SkPDFDocument.h:77
uint8_t fMonth
1..12
Definition: SkPDFDocument.h:73
uint8_t fDay
1..31
Definition: SkPDFDocument.h:75
uint16_t fYear
e.g. 2005
Definition: SkPDFDocument.h:72
void toISO8601(SkString *dst) const
uint8_t fSecond
0..59
Definition: SkPDFDocument.h:78
int16_t fTimeZoneMinutes
Definition: SkPDFDocument.h:70
uint8_t fHour
0..23
Definition: SkPDFDocument.h:76
SkExecutor * fExecutor
enum SkPDF::Metadata::Outline fOutline
SkScalar fRasterDPI
StructureElementNode * fStructureElementTreeRoot
SkScalar fBottom
larger y-axis bounds
Definition: extension.cpp:17
SkScalar fLeft
smaller x-axis bounds
Definition: extension.cpp:14
SkScalar fRight
larger x-axis bounds
Definition: extension.cpp:16
static constexpr SkRect MakeSize(const SkSize &size)
Definition: SkRect.h:633
SkScalar fTop
smaller y-axis bounds
Definition: extension.cpp:15
Definition: SkSize.h:52
SkScalar width() const
Definition: SkSize.h:76
SkScalar height() const
Definition: SkSize.h:77
Definition: SkUUID.h:9