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