blob: ae0386ab1a389272f531eba51c5e29765c60f619 [file] [log] [blame]
reed@google.com99ac02b2013-06-07 20:30:16 +00001/*
halcanarya43b4152015-03-25 12:15:04 -07002 * Copyright 2011 Google Inc.
reed@google.com99ac02b2013-06-07 20:30:16 +00003 *
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 "SkDocument.h"
halcanarya1f1ee92015-02-20 06:17:26 -08009#include "SkPDFCanon.h"
halcanarya43b4152015-03-25 12:15:04 -070010#include "SkPDFCatalog.h"
reed58677362014-10-09 05:30:10 -070011#include "SkPDFDevice.h"
halcanarya43b4152015-03-25 12:15:04 -070012#include "SkPDFFont.h"
halcanary2f7ebcb2015-03-25 12:45:28 -070013#include "SkPDFResourceDict.h"
14#include "SkPDFStream.h"
halcanarya43b4152015-03-25 12:15:04 -070015#include "SkPDFTypes.h"
16#include "SkStream.h"
17
18static 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");
24}
25
26static void emit_pdf_footer(SkWStream* stream,
27 SkPDFCatalog* catalog,
28 SkPDFObject* docCatalog,
29 int64_t objCount,
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();
36
37 stream->writeText("trailer\n");
38 trailerDict.emitObject(stream, catalog);
39 stream->writeText("\nstartxref\n");
40 stream->writeBigDecAsText(xRefFileOffset);
41 stream->writeText("\n%%EOF");
42}
43
halcanary2f7ebcb2015-03-25 12:45:28 -070044static void perform_font_subsetting(
45 const SkTDArray<const SkPDFDevice*>& pageDevices,
46 SkPDFCatalog* catalog) {
halcanarya43b4152015-03-25 12:15:04 -070047 SkASSERT(catalog);
48
49 SkPDFGlyphSetMap usage;
halcanary2f7ebcb2015-03-25 12:45:28 -070050 for (int i = 0; i < pageDevices.count(); ++i) {
51 usage.merge(pageDevices[i]->getFontGlyphUsage());
halcanarya43b4152015-03-25 12:15:04 -070052 }
53 SkPDFGlyphSetMap::F2BIter iterator(usage);
54 const SkPDFGlyphSetMap::FontGlyphSetPair* entry = iterator.next();
55 while (entry) {
56 SkAutoTUnref<SkPDFFont> subsetFont(
57 entry->fFont->getFontSubset(entry->fGlyphSet));
58 if (subsetFont) {
59 catalog->setSubstitute(entry->fFont, subsetFont.get());
60 }
61 entry = iterator.next();
62 }
63}
64
halcanary2f7ebcb2015-03-25 12:45:28 -070065static 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());
70
71 SkAutoTUnref<SkPDFArray> mediaBox(pageDevice->copyMediaBox());
72 page->insert("MediaBox", mediaBox.get());
73
74 SkPDFArray* annots = pageDevice->getAnnotations();
75 if (annots && annots->size() > 0) {
76 page->insert("Annots", annots);
77 }
78
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();
83 return page.detach();
84}
85
86static 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
95 // one child.
96 static const int kNodeSize = 8;
97
98 SkAutoTUnref<SkPDFName> kidsName(new SkPDFName("Kids"));
99 SkAutoTUnref<SkPDFName> countName(new SkPDFName("Count"));
100 SkAutoTUnref<SkPDFName> parentName(new SkPDFName("Parent"));
101
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++) {
106 SkSafeRef(pages[i]);
107 curNodes.push(pages[i]);
108 }
109
110 // nextRoundNodes passes its references to nodes on to curNodes.
111 SkTDArray<SkPDFDict*> nextRoundNodes;
112 nextRoundNodes.setReserve((pages.count() + kNodeSize - 1)/kNodeSize);
113
114 int treeCapacity = kNodeSize;
115 do {
116 for (int i = 0; i < curNodes.count(); ) {
117 if (i > 0 && i + 1 == curNodes.count()) {
118 nextRoundNodes.push(curNodes[i]);
119 break;
120 }
121
122 SkPDFDict* newNode = new SkPDFDict("Pages");
123 SkAutoTUnref<SkPDFObjRef> newNodeRef(new SkPDFObjRef(newNode));
124
125 SkAutoTUnref<SkPDFArray> kids(new SkPDFArray);
126 kids->reserve(kNodeSize);
127
128 int count = 0;
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();
132
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.
137 } else {
138 SkSafeUnref(curNodes[i]);
139 }
140 }
141
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;
152 }
153 newNode->insert(countName.get(), new SkPDFInt(pageCount))->unref();
154 newNode->insert(kidsName.get(), kids.get());
155 nextRoundNodes.push(newNode); // Transfer reference.
156 }
157
158 curNodes = nextRoundNodes;
159 nextRoundNodes.rewind();
160 treeCapacity *= kNodeSize;
161 } while (curNodes.count() > 1);
162
163 pageTree->push(curNodes[0]); // Transfer reference.
164 if (rootNode) {
165 *rootNode = curNodes[0];
166 }
167}
168
halcanarya43b4152015-03-25 12:15:04 -0700169static bool emit_pdf_document(const SkTDArray<const SkPDFDevice*>& pageDevices,
170 SkWStream* stream) {
171 if (pageDevices.isEmpty()) {
172 return false;
173 }
174
halcanary2f7ebcb2015-03-25 12:45:28 -0700175 SkTDArray<SkPDFDict*> pages;
halcanarya43b4152015-03-25 12:15:04 -0700176 SkAutoTUnref<SkPDFDict> dests(SkNEW(SkPDFDict));
177
178 for (int i = 0; i < pageDevices.count(); i++) {
179 SkASSERT(pageDevices[i]);
180 SkASSERT(i == 0 ||
181 pageDevices[i - 1]->getCanon() == pageDevices[i]->getCanon());
halcanary2f7ebcb2015-03-25 12:45:28 -0700182 SkAutoTUnref<SkPDFDict> page(create_pdf_page(pageDevices[i]));
183 pageDevices[i]->appendDestinations(dests, page.get());
halcanarya43b4152015-03-25 12:15:04 -0700184 pages.push(page.detach());
185 }
186 SkPDFCatalog catalog;
187
188 SkTDArray<SkPDFDict*> pageTree;
189 SkAutoTUnref<SkPDFDict> docCatalog(SkNEW_ARGS(SkPDFDict, ("Catalog")));
190
191 SkPDFDict* pageTreeRoot;
halcanary2f7ebcb2015-03-25 12:45:28 -0700192 generate_page_tree(pages, &pageTree, &pageTreeRoot);
halcanarya43b4152015-03-25 12:15:04 -0700193
194 docCatalog->insert("Pages", new SkPDFObjRef(pageTreeRoot))->unref();
195
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());
204 */
205
206 if (dests->size() > 0) {
207 docCatalog->insert("Dests", SkNEW_ARGS(SkPDFObjRef, (dests.get())))
208 ->unref();
209 }
210
211 // Build font subsetting info before proceeding.
halcanary2f7ebcb2015-03-25 12:45:28 -0700212 perform_font_subsetting(pageDevices, &catalog);
halcanarya43b4152015-03-25 12:15:04 -0700213
214 SkTSet<SkPDFObject*> resourceSet;
215 if (resourceSet.add(docCatalog.get())) {
216 docCatalog->addResources(&resourceSet, &catalog);
217 }
218 for (int i = 0; i < resourceSet.count(); ++i) {
219 SkAssertResult(catalog.addObject(resourceSet[i]));
220 }
221
222 size_t baseOffset = SkToOffT(stream->bytesWritten());
223 emit_pdf_header(stream);
224 SkTDArray<int32_t> offsets;
225 for (int i = 0; i < resourceSet.count(); ++i) {
226 SkPDFObject* object = resourceSet[i];
227 offsets.push(SkToS32(stream->bytesWritten() - baseOffset));
228 SkASSERT(object == catalog.getSubstituteObject(object));
229 SkASSERT(catalog.getObjectNumber(object) == i + 1);
230 stream->writeDecAsText(i + 1);
231 stream->writeText(" 0 obj\n"); // Generation number is always 0.
232 object->emitObject(stream, &catalog);
233 stream->writeText("\nendobj\n");
234 }
235 int32_t xRefFileOffset = SkToS32(stream->bytesWritten() - baseOffset);
236
237 int32_t objCount = SkToS32(offsets.count() + 1);
238
239 stream->writeText("xref\n0 ");
240 stream->writeDecAsText(objCount + 1);
241 stream->writeText("\n0000000000 65535 f \n");
242 for (int i = 0; i < offsets.count(); i++) {
243 SkASSERT(offsets[i] > 0);
244 stream->writeBigDecAsText(offsets[i], 10);
245 stream->writeText(" 00000 n \n");
246 }
247 emit_pdf_footer(stream, &catalog, docCatalog.get(), objCount,
248 xRefFileOffset);
249
250 // The page tree has both child and parent pointers, so it creates a
251 // reference cycle. We must clear that cycle to properly reclaim memory.
252 for (int i = 0; i < pageTree.count(); i++) {
253 pageTree[i]->clear();
254 }
255 pageTree.safeUnrefAll();
256 pages.unrefAll();
257 return true;
258}
259
260#if 0
261// TODO(halcanary): expose notEmbeddableCount in SkDocument
262void GetCountOfFontTypes(
263 const SkTDArray<SkPDFDevice*>& pageDevices,
264 int counts[SkAdvancedTypefaceMetrics::kOther_Font + 1],
265 int* notSubsettableCount,
266 int* notEmbeddableCount) {
267 sk_bzero(counts, sizeof(int) *
268 (SkAdvancedTypefaceMetrics::kOther_Font + 1));
269 SkTDArray<SkFontID> seenFonts;
270 int notSubsettable = 0;
271 int notEmbeddable = 0;
272
273 for (int pageNumber = 0; pageNumber < pageDevices.count(); pageNumber++) {
274 const SkTDArray<SkPDFFont*>& fontResources =
275 pageDevices[pageNumber]->getFontResources();
276 for (int font = 0; font < fontResources.count(); font++) {
277 SkFontID fontID = fontResources[font]->typeface()->uniqueID();
278 if (seenFonts.find(fontID) == -1) {
279 counts[fontResources[font]->getType()]++;
280 seenFonts.push(fontID);
281 if (!fontResources[font]->canSubset()) {
282 notSubsettable++;
283 }
284 if (!fontResources[font]->canEmbed()) {
285 notEmbeddable++;
286 }
287 }
288 }
289 }
290 if (notSubsettableCount) {
291 *notSubsettableCount = notSubsettable;
292
293 }
294 if (notEmbeddableCount) {
295 *notEmbeddableCount = notEmbeddable;
296 }
297}
298#endif
299////////////////////////////////////////////////////////////////////////////////
reed@google.com99ac02b2013-06-07 20:30:16 +0000300
halcanary7a011842015-03-25 07:52:56 -0700301namespace {
reed@google.com99ac02b2013-06-07 20:30:16 +0000302class SkDocument_PDF : public SkDocument {
303public:
halcanary8c92dc12015-02-19 18:50:05 -0800304 SkDocument_PDF(SkWStream* stream,
halcanary792c80f2015-02-20 07:21:05 -0800305 void (*doneProc)(SkWStream*, bool),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000306 SkScalar rasterDpi)
halcanary8c92dc12015-02-19 18:50:05 -0800307 : SkDocument(stream, doneProc)
halcanary8c92dc12015-02-19 18:50:05 -0800308 , fRasterDpi(rasterDpi) {}
skia.committer@gmail.com63193672013-06-08 07:01:13 +0000309
reed@google.com99ac02b2013-06-07 20:30:16 +0000310 virtual ~SkDocument_PDF() {
311 // subclasses must call close() in their destructors
312 this->close();
313 }
314
315protected:
316 virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height,
commit-bot@chromium.org5e009892013-10-14 13:42:12 +0000317 const SkRect& trimBox) SK_OVERRIDE {
halcanarya1f1ee92015-02-20 06:17:26 -0800318 SkASSERT(!fCanvas.get());
reed@google.com99ac02b2013-06-07 20:30:16 +0000319
halcanarya1f1ee92015-02-20 06:17:26 -0800320 SkISize pageSize = SkISize::Make(
321 SkScalarRoundToInt(width), SkScalarRoundToInt(height));
halcanary7a011842015-03-25 07:52:56 -0700322 SkAutoTUnref<SkPDFDevice> device(
323 SkPDFDevice::Create(pageSize, fRasterDpi, &fCanon));
324 fCanvas.reset(SkNEW_ARGS(SkCanvas, (device.get())));
325 fPageDevices.push(device.detach());
halcanarybe519ad2014-11-10 14:22:14 -0800326 fCanvas->clipRect(trimBox);
halcanary93f81612014-11-10 14:01:57 -0800327 fCanvas->translate(trimBox.x(), trimBox.y());
halcanarya1f1ee92015-02-20 06:17:26 -0800328 return fCanvas.get();
reed@google.com99ac02b2013-06-07 20:30:16 +0000329 }
330
mtklein72c9faa2015-01-09 10:06:39 -0800331 void onEndPage() SK_OVERRIDE {
halcanarya1f1ee92015-02-20 06:17:26 -0800332 SkASSERT(fCanvas.get());
reed@google.com99ac02b2013-06-07 20:30:16 +0000333 fCanvas->flush();
halcanarya1f1ee92015-02-20 06:17:26 -0800334 fCanvas.reset(NULL);
reed@google.com99ac02b2013-06-07 20:30:16 +0000335 }
336
mtklein72c9faa2015-01-09 10:06:39 -0800337 bool onClose(SkWStream* stream) SK_OVERRIDE {
halcanarya1f1ee92015-02-20 06:17:26 -0800338 SkASSERT(!fCanvas.get());
reed@google.com99ac02b2013-06-07 20:30:16 +0000339
halcanarya43b4152015-03-25 12:15:04 -0700340 bool success = emit_pdf_document(fPageDevices, stream);
halcanary7a011842015-03-25 07:52:56 -0700341 fPageDevices.unrefAll();
halcanary2e3f9d82015-02-27 12:41:03 -0800342 fCanon.reset();
commit-bot@chromium.orgb5a66512013-10-09 21:09:00 +0000343 return success;
344 }
345
mtklein72c9faa2015-01-09 10:06:39 -0800346 void onAbort() SK_OVERRIDE {
halcanary7a011842015-03-25 07:52:56 -0700347 fPageDevices.unrefAll();
halcanary2e3f9d82015-02-27 12:41:03 -0800348 fCanon.reset();
reed@google.com99ac02b2013-06-07 20:30:16 +0000349 }
350
351private:
halcanarya1f1ee92015-02-20 06:17:26 -0800352 SkPDFCanon fCanon;
halcanary6d622702015-03-25 08:45:42 -0700353 SkTDArray<const SkPDFDevice*> fPageDevices;
halcanarya1f1ee92015-02-20 06:17:26 -0800354 SkAutoTUnref<SkCanvas> fCanvas;
355 SkScalar fRasterDpi;
reed@google.com99ac02b2013-06-07 20:30:16 +0000356};
halcanary7a011842015-03-25 07:52:56 -0700357} // namespace
reed@google.com99ac02b2013-06-07 20:30:16 +0000358///////////////////////////////////////////////////////////////////////////////
359
halcanary8c92dc12015-02-19 18:50:05 -0800360SkDocument* SkDocument::CreatePDF(SkWStream* stream, SkScalar dpi) {
361 return stream ? SkNEW_ARGS(SkDocument_PDF, (stream, NULL, dpi)) : NULL;
reed@google.com99ac02b2013-06-07 20:30:16 +0000362}
363
halcanary8c92dc12015-02-19 18:50:05 -0800364SkDocument* SkDocument::CreatePDF(const char path[], SkScalar dpi) {
reed@google.com99ac02b2013-06-07 20:30:16 +0000365 SkFILEWStream* stream = SkNEW_ARGS(SkFILEWStream, (path));
366 if (!stream->isValid()) {
367 SkDELETE(stream);
368 return NULL;
369 }
halcanarya43b4152015-03-25 12:15:04 -0700370 auto delete_wstream = [](SkWStream* stream, bool) { SkDELETE(stream); };
halcanary8c92dc12015-02-19 18:50:05 -0800371 return SkNEW_ARGS(SkDocument_PDF, (stream, delete_wstream, dpi));
reed@google.com99ac02b2013-06-07 20:30:16 +0000372}