2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkDocument.h"
9 #include "SkPDFCanon.h"
10 #include "SkPDFCatalog.h"
11 #include "SkPDFDevice.h"
12 #include "SkPDFFont.h"
13 #include "SkPDFResourceDict.h"
14 #include "SkPDFStream.h"
15 #include "SkPDFTypes.h"
18 static void emit_pdf_header(SkWStream* stream) {
19 stream->writeText("%PDF-1.4\n%");
20 // The PDF spec recommends including a comment with four bytes, all
21 // with their high bits set. This is "Skia" with the high bits set.
22 stream->write32(0xD3EBE9E1);
23 stream->writeText("\n");
26 static void emit_pdf_footer(SkWStream* stream,
27 SkPDFCatalog* catalog,
28 SkPDFObject* docCatalog,
30 int32_t xRefFileOffset) {
31 SkPDFDict trailerDict;
32 // TODO(vandebo): Linearized format will take a Prev entry too.
33 // TODO(vandebo): PDF/A requires an ID entry.
34 trailerDict.insertInt("Size", int(objCount));
35 trailerDict.insert("Root", new SkPDFObjRef(docCatalog))->unref();
37 stream->writeText("trailer\n");
38 trailerDict.emitObject(stream, catalog);
39 stream->writeText("\nstartxref\n");
40 stream->writeBigDecAsText(xRefFileOffset);
41 stream->writeText("\n%%EOF");
44 static void perform_font_subsetting(
45 const SkTDArray<const SkPDFDevice*>& pageDevices,
46 SkPDFCatalog* catalog) {
49 SkPDFGlyphSetMap usage;
50 for (int i = 0; i < pageDevices.count(); ++i) {
51 usage.merge(pageDevices[i]->getFontGlyphUsage());
53 SkPDFGlyphSetMap::F2BIter iterator(usage);
54 const SkPDFGlyphSetMap::FontGlyphSetPair* entry = iterator.next();
56 SkAutoTUnref<SkPDFFont> subsetFont(
57 entry->fFont->getFontSubset(entry->fGlyphSet));
59 catalog->setSubstitute(entry->fFont, subsetFont.get());
61 entry = iterator.next();
65 static SkPDFDict* create_pdf_page(const SkPDFDevice* pageDevice) {
66 SkAutoTUnref<SkPDFDict> page(SkNEW_ARGS(SkPDFDict, ("Page")));
67 SkAutoTUnref<SkPDFResourceDict> deviceResourceDict(
68 pageDevice->createResourceDict());
69 page->insert("Resources", deviceResourceDict.get());
71 SkAutoTUnref<SkPDFArray> mediaBox(pageDevice->copyMediaBox());
72 page->insert("MediaBox", mediaBox.get());
74 SkPDFArray* annots = pageDevice->getAnnotations();
75 if (annots && annots->size() > 0) {
76 page->insert("Annots", annots);
79 SkAutoTDelete<SkStreamAsset> content(pageDevice->content());
80 SkAutoTUnref<SkPDFStream> contentStream(
81 SkNEW_ARGS(SkPDFStream, (content.get())));
82 page->insert("Contents", new SkPDFObjRef(contentStream.get()))->unref();
86 static void generate_page_tree(const SkTDArray<SkPDFDict*>& pages,
87 SkTDArray<SkPDFDict*>* pageTree,
88 SkPDFDict** rootNode) {
89 // PDF wants a tree describing all the pages in the document. We arbitrary
90 // choose 8 (kNodeSize) as the number of allowed children. The internal
91 // nodes have type "Pages" with an array of children, a parent pointer, and
92 // the number of leaves below the node as "Count." The leaves are passed
93 // into the method, have type "Page" and need a parent pointer. This method
94 // builds the tree bottom up, skipping internal nodes that would have only
96 static const int kNodeSize = 8;
98 SkAutoTUnref<SkPDFName> kidsName(new SkPDFName("Kids"));
99 SkAutoTUnref<SkPDFName> countName(new SkPDFName("Count"));
100 SkAutoTUnref<SkPDFName> parentName(new SkPDFName("Parent"));
102 // curNodes takes a reference to its items, which it passes to pageTree.
103 SkTDArray<SkPDFDict*> curNodes;
104 curNodes.setReserve(pages.count());
105 for (int i = 0; i < pages.count(); i++) {
107 curNodes.push(pages[i]);
110 // nextRoundNodes passes its references to nodes on to curNodes.
111 SkTDArray<SkPDFDict*> nextRoundNodes;
112 nextRoundNodes.setReserve((pages.count() + kNodeSize - 1)/kNodeSize);
114 int treeCapacity = kNodeSize;
116 for (int i = 0; i < curNodes.count(); ) {
117 if (i > 0 && i + 1 == curNodes.count()) {
118 nextRoundNodes.push(curNodes[i]);
122 SkPDFDict* newNode = new SkPDFDict("Pages");
123 SkAutoTUnref<SkPDFObjRef> newNodeRef(new SkPDFObjRef(newNode));
125 SkAutoTUnref<SkPDFArray> kids(new SkPDFArray);
126 kids->reserve(kNodeSize);
129 for (; i < curNodes.count() && count < kNodeSize; i++, count++) {
130 curNodes[i]->insert(parentName.get(), newNodeRef.get());
131 kids->append(new SkPDFObjRef(curNodes[i]))->unref();
133 // TODO(vandebo): put the objects in strict access order.
134 // Probably doesn't matter because they are so small.
135 if (curNodes[i] != pages[0]) {
136 pageTree->push(curNodes[i]); // Transfer reference.
138 SkSafeUnref(curNodes[i]);
142 // treeCapacity is the number of leaf nodes possible for the
143 // current set of subtrees being generated. (i.e. 8, 64, 512, ...).
144 // It is hard to count the number of leaf nodes in the current
145 // subtree. However, by construction, we know that unless it's the
146 // last subtree for the current depth, the leaf count will be
147 // treeCapacity, otherwise it's what ever is left over after
148 // consuming treeCapacity chunks.
149 int pageCount = treeCapacity;
150 if (i == curNodes.count()) {
151 pageCount = ((pages.count() - 1) % treeCapacity) + 1;
153 newNode->insert(countName.get(), new SkPDFInt(pageCount))->unref();
154 newNode->insert(kidsName.get(), kids.get());
155 nextRoundNodes.push(newNode); // Transfer reference.
158 curNodes = nextRoundNodes;
159 nextRoundNodes.rewind();
160 treeCapacity *= kNodeSize;
161 } while (curNodes.count() > 1);
163 pageTree->push(curNodes[0]); // Transfer reference.
165 *rootNode = curNodes[0];
169 static bool emit_pdf_document(const SkTDArray<const SkPDFDevice*>& pageDevices,
171 if (pageDevices.isEmpty()) {
175 SkTDArray<SkPDFDict*> pages;
176 SkAutoTUnref<SkPDFDict> dests(SkNEW(SkPDFDict));
178 for (int i = 0; i < pageDevices.count(); i++) {
179 SkASSERT(pageDevices[i]);
181 pageDevices[i - 1]->getCanon() == pageDevices[i]->getCanon());
182 SkAutoTUnref<SkPDFDict> page(create_pdf_page(pageDevices[i]));
183 pageDevices[i]->appendDestinations(dests, page.get());
184 pages.push(page.detach());
186 SkPDFCatalog catalog;
188 SkTDArray<SkPDFDict*> pageTree;
189 SkAutoTUnref<SkPDFDict> docCatalog(SkNEW_ARGS(SkPDFDict, ("Catalog")));
191 SkPDFDict* pageTreeRoot;
192 generate_page_tree(pages, &pageTree, &pageTreeRoot);
194 docCatalog->insert("Pages", new SkPDFObjRef(pageTreeRoot))->unref();
196 /* TODO(vandebo): output intent
197 SkAutoTUnref<SkPDFDict> outputIntent = new SkPDFDict("OutputIntent");
198 outputIntent->insert("S", new SkPDFName("GTS_PDFA1"))->unref();
199 outputIntent->insert("OutputConditionIdentifier",
200 new SkPDFString("sRGB"))->unref();
201 SkAutoTUnref<SkPDFArray> intentArray = new SkPDFArray;
202 intentArray->append(outputIntent.get());
203 docCatalog->insert("OutputIntent", intentArray.get());
206 if (dests->size() > 0) {
207 docCatalog->insert("Dests", SkNEW_ARGS(SkPDFObjRef, (dests.get())))
211 // Build font subsetting info before proceeding.
212 perform_font_subsetting(pageDevices, &catalog);
214 if (catalog.addObject(docCatalog.get())) {
215 docCatalog->addResources(&catalog);
217 size_t baseOffset = SkToOffT(stream->bytesWritten());
218 emit_pdf_header(stream);
219 SkTDArray<int32_t> offsets;
220 for (int i = 0; i < catalog.objects().count(); ++i) {
221 SkPDFObject* object = catalog.objects()[i];
222 offsets.push(SkToS32(stream->bytesWritten() - baseOffset));
223 SkASSERT(object == catalog.getSubstituteObject(object));
224 SkASSERT(catalog.getObjectNumber(object) == i + 1);
225 stream->writeDecAsText(i + 1);
226 stream->writeText(" 0 obj\n"); // Generation number is always 0.
227 object->emitObject(stream, &catalog);
228 stream->writeText("\nendobj\n");
230 int32_t xRefFileOffset = SkToS32(stream->bytesWritten() - baseOffset);
232 int32_t objCount = SkToS32(offsets.count() + 1);
234 stream->writeText("xref\n0 ");
235 stream->writeDecAsText(objCount + 1);
236 stream->writeText("\n0000000000 65535 f \n");
237 for (int i = 0; i < offsets.count(); i++) {
238 SkASSERT(offsets[i] > 0);
239 stream->writeBigDecAsText(offsets[i], 10);
240 stream->writeText(" 00000 n \n");
242 emit_pdf_footer(stream, &catalog, docCatalog.get(), objCount,
245 // The page tree has both child and parent pointers, so it creates a
246 // reference cycle. We must clear that cycle to properly reclaim memory.
247 for (int i = 0; i < pageTree.count(); i++) {
248 pageTree[i]->clear();
250 pageTree.safeUnrefAll();
256 // TODO(halcanary): expose notEmbeddableCount in SkDocument
257 void GetCountOfFontTypes(
258 const SkTDArray<SkPDFDevice*>& pageDevices,
259 int counts[SkAdvancedTypefaceMetrics::kOther_Font + 1],
260 int* notSubsettableCount,
261 int* notEmbeddableCount) {
262 sk_bzero(counts, sizeof(int) *
263 (SkAdvancedTypefaceMetrics::kOther_Font + 1));
264 SkTDArray<SkFontID> seenFonts;
265 int notSubsettable = 0;
266 int notEmbeddable = 0;
268 for (int pageNumber = 0; pageNumber < pageDevices.count(); pageNumber++) {
269 const SkTDArray<SkPDFFont*>& fontResources =
270 pageDevices[pageNumber]->getFontResources();
271 for (int font = 0; font < fontResources.count(); font++) {
272 SkFontID fontID = fontResources[font]->typeface()->uniqueID();
273 if (seenFonts.find(fontID) == -1) {
274 counts[fontResources[font]->getType()]++;
275 seenFonts.push(fontID);
276 if (!fontResources[font]->canSubset()) {
279 if (!fontResources[font]->canEmbed()) {
285 if (notSubsettableCount) {
286 *notSubsettableCount = notSubsettable;
289 if (notEmbeddableCount) {
290 *notEmbeddableCount = notEmbeddable;
294 ////////////////////////////////////////////////////////////////////////////////
297 class SkDocument_PDF : public SkDocument {
299 SkDocument_PDF(SkWStream* stream,
300 void (*doneProc)(SkWStream*, bool),
302 : SkDocument(stream, doneProc)
303 , fRasterDpi(rasterDpi) {}
305 virtual ~SkDocument_PDF() {
306 // subclasses must call close() in their destructors
311 virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height,
312 const SkRect& trimBox) override {
313 SkASSERT(!fCanvas.get());
315 SkISize pageSize = SkISize::Make(
316 SkScalarRoundToInt(width), SkScalarRoundToInt(height));
317 SkAutoTUnref<SkPDFDevice> device(
318 SkPDFDevice::Create(pageSize, fRasterDpi, &fCanon));
319 fCanvas.reset(SkNEW_ARGS(SkCanvas, (device.get())));
320 fPageDevices.push(device.detach());
321 fCanvas->clipRect(trimBox);
322 fCanvas->translate(trimBox.x(), trimBox.y());
323 return fCanvas.get();
326 void onEndPage() override {
327 SkASSERT(fCanvas.get());
332 bool onClose(SkWStream* stream) override {
333 SkASSERT(!fCanvas.get());
335 bool success = emit_pdf_document(fPageDevices, stream);
336 fPageDevices.unrefAll();
341 void onAbort() override {
342 fPageDevices.unrefAll();
348 SkTDArray<const SkPDFDevice*> fPageDevices;
349 SkAutoTUnref<SkCanvas> fCanvas;
353 ///////////////////////////////////////////////////////////////////////////////
355 SkDocument* SkDocument::CreatePDF(SkWStream* stream, SkScalar dpi) {
356 return stream ? SkNEW_ARGS(SkDocument_PDF, (stream, NULL, dpi)) : NULL;
359 SkDocument* SkDocument::CreatePDF(const char path[], SkScalar dpi) {
360 SkFILEWStream* stream = SkNEW_ARGS(SkFILEWStream, (path));
361 if (!stream->isValid()) {
365 auto delete_wstream = [](SkWStream* stream, bool) { SkDELETE(stream); };
366 return SkNEW_ARGS(SkDocument_PDF, (stream, delete_wstream, dpi));