aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/pdf/SkPDFDocument.cpp
blob: 4009cef9b6210251de6738bec0f327ecf9223487 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */


#include "SkPDFCatalog.h"
#include "SkPDFDevice.h"
#include "SkPDFDocument.h"
#include "SkPDFFont.h"
#include "SkPDFPage.h"
#include "SkPDFTypes.h"
#include "SkStream.h"


static void perform_font_subsetting(SkPDFCatalog* catalog,
                                    const SkTDArray<SkPDFPage*>& pages,
                                    SkTDArray<SkPDFObject*>* substitutes) {
    SkASSERT(catalog);
    SkASSERT(substitutes);

    SkPDFGlyphSetMap usage;
    for (int i = 0; i < pages.count(); ++i) {
        usage.merge(pages[i]->getFontGlyphUsage());
    }
    SkPDFGlyphSetMap::F2BIter iterator(usage);
    const SkPDFGlyphSetMap::FontGlyphSetPair* entry = iterator.next();
    while (entry) {
        SkPDFFont* subsetFont =
            entry->fFont->getFontSubset(entry->fGlyphSet);
        if (subsetFont) {
            catalog->setSubstitute(entry->fFont, subsetFont);
            substitutes->push(subsetFont);  // Transfer ownership to substitutes
        }
        entry = iterator.next();
    }
}

SkPDFDocument::SkPDFDocument() {}

SkPDFDocument::~SkPDFDocument() { fPageDevices.unrefAll(); }

static void emit_pdf_header(SkWStream* stream) {
    stream->writeText("%PDF-1.4\n%");
    // The PDF spec recommends including a comment with four bytes, all
    // with their high bits set.  This is "Skia" with the high bits set.
    stream->write32(0xD3EBE9E1);
    stream->writeText("\n");
}

static void emit_pdf_footer(SkWStream* stream,
                            SkPDFCatalog* catalog,
                            SkPDFObject* docCatalog,
                            int64_t objCount,
                            int32_t xRefFileOffset) {
    SkPDFDict trailerDict;
    // TODO(vandebo): Linearized format will take a Prev entry too.
    // TODO(vandebo): PDF/A requires an ID entry.
    trailerDict.insertInt("Size", int(objCount));
    trailerDict.insert("Root", new SkPDFObjRef(docCatalog))->unref();

    stream->writeText("trailer\n");
    trailerDict.emitObject(stream, catalog);
    stream->writeText("\nstartxref\n");
    stream->writeBigDecAsText(xRefFileOffset);
    stream->writeText("\n%%EOF");
}

bool SkPDFDocument::emitPDF(SkWStream* stream) {
    // SkTDArray<SkPDFDevice*> fPageDevices;
    if (fPageDevices.isEmpty()) {
        return false;
    }
    SkTDArray<SkPDFPage*> pages;
    for (int i = 0; i < fPageDevices.count(); i++) {
        // Reference from new passed to pages.
        pages.push(SkNEW_ARGS(SkPDFPage, (fPageDevices[i])));
    }
    SkPDFCatalog catalog;

    SkTDArray<SkPDFDict*> pageTree;
    SkAutoTUnref<SkPDFDict> docCatalog(SkNEW_ARGS(SkPDFDict, ("Catalog")));
    SkTSet<SkPDFObject*> firstPageResources;
    SkTSet<SkPDFObject*> otherPageResources;
    SkTDArray<SkPDFObject*> substitutes;
    catalog.addObject(docCatalog.get(), true);

    SkPDFDict* pageTreeRoot;
    SkPDFPage::GeneratePageTree(pages, &catalog, &pageTree, &pageTreeRoot);
    docCatalog->insert("Pages", new SkPDFObjRef(pageTreeRoot))->unref();

    /* TODO(vandebo): output intent
    SkAutoTUnref<SkPDFDict> outputIntent = new SkPDFDict("OutputIntent");
    outputIntent->insert("S", new SkPDFName("GTS_PDFA1"))->unref();
    outputIntent->insert("OutputConditionIdentifier",
                         new SkPDFString("sRGB"))->unref();
    SkAutoTUnref<SkPDFArray> intentArray = new SkPDFArray;
    intentArray->append(outputIntent.get());
    docCatalog->insert("OutputIntent", intentArray.get());
    */

    SkAutoTUnref<SkPDFDict> dests(SkNEW(SkPDFDict));

    bool firstPage = true;
    /* The references returned in newResources are transfered to
     * firstPageResources or otherPageResources depending on firstPage and
     * knownResources doesn't have a reference but just relies on the other
     * two sets to maintain a reference.
     */
    SkTSet<SkPDFObject*> knownResources;

    // mergeInto returns the number of duplicates.
    // If there are duplicates, there is a bug and we mess ref counting.
    SkDEBUGCODE(int duplicates = ) knownResources.mergeInto(firstPageResources);
    SkASSERT(duplicates == 0);

    for (int i = 0; i < pages.count(); i++) {
        if (i == 1) {
            firstPage = false;
            SkDEBUGCODE(duplicates = )
                    knownResources.mergeInto(otherPageResources);
        }
        SkTSet<SkPDFObject*> newResources;
        pages[i]->finalizePage(&catalog, firstPage, knownResources,
                               &newResources);
        for (int j = 0; j < newResources.count(); j++) {
            catalog.addObject(newResources[i], firstPage);
        }
        if (firstPage) {
            SkDEBUGCODE(duplicates = )
                    firstPageResources.mergeInto(newResources);
        } else {
            SkDEBUGCODE(duplicates = )
                    otherPageResources.mergeInto(newResources);
        }
        SkASSERT(duplicates == 0);

        SkDEBUGCODE(duplicates = ) knownResources.mergeInto(newResources);
        SkASSERT(duplicates == 0);

        pages[i]->appendDestinations(dests);
    }

    if (dests->size() > 0) {
        SkPDFDict* raw_dests = dests.get();
        firstPageResources.add(dests.detach());  // Transfer ownership.
        catalog.addObject(raw_dests, true /* onFirstPage */);
        docCatalog->insert("Dests", SkNEW_ARGS(SkPDFObjRef, (raw_dests)))
                ->unref();
    }

    // Build font subsetting info before proceeding.
    perform_font_subsetting(&catalog, pages, &substitutes);

    SkTSet<SkPDFObject*> resourceSet;
    if (resourceSet.add(docCatalog.get())) {
        docCatalog->addResources(&resourceSet, &catalog);
    }
    size_t baseOffset = SkToOffT(stream->bytesWritten());
    emit_pdf_header(stream);
    for (int i = 0; i < resourceSet.count(); ++i) {
        SkPDFObject* object = resourceSet[i];
        catalog.setFileOffset(object,
                              SkToOffT(stream->bytesWritten() - baseOffset));
        SkASSERT(object == catalog.getSubstituteObject(object));
        stream->writeDecAsText(catalog.getObjectNumber(object));
        stream->writeText(" 0 obj\n");  // Generation number is always 0.
        object->emitObject(stream, &catalog);
        stream->writeText("\nendobj\n");
    }
    int32_t xRefFileOffset = SkToS32(stream->bytesWritten() - baseOffset);
    int64_t objCount = catalog.emitXrefTable(stream, pages.count() > 1);

    emit_pdf_footer(stream, &catalog, docCatalog.get(), objCount,
                    xRefFileOffset);

    // The page tree has both child and parent pointers, so it creates a
    // reference cycle.  We must clear that cycle to properly reclaim memory.
    for (int i = 0; i < pageTree.count(); i++) {
        pageTree[i]->clear();
    }
    pageTree.safeUnrefAll();
    pages.unrefAll();

    firstPageResources.safeUnrefAll();
    otherPageResources.safeUnrefAll();

    substitutes.unrefAll();
    docCatalog.reset(NULL);
    return true;
}

// TODO(halcanary): expose notEmbeddableCount in SkDocument
void SkPDFDocument::getCountOfFontTypes(
        int counts[SkAdvancedTypefaceMetrics::kOther_Font + 1],
        int* notSubsettableCount,
        int* notEmbeddableCount) const {
    sk_bzero(counts, sizeof(int) *
                     (SkAdvancedTypefaceMetrics::kOther_Font + 1));
    SkTDArray<SkFontID> seenFonts;
    int notSubsettable = 0;
    int notEmbeddable = 0;

    for (int pageNumber = 0; pageNumber < fPageDevices.count(); pageNumber++) {
        const SkTDArray<SkPDFFont*>& fontResources =
                fPageDevices[pageNumber]->getFontResources();
        for (int font = 0; font < fontResources.count(); font++) {
            SkFontID fontID = fontResources[font]->typeface()->uniqueID();
            if (seenFonts.find(fontID) == -1) {
                counts[fontResources[font]->getType()]++;
                seenFonts.push(fontID);
                if (!fontResources[font]->canSubset()) {
                    notSubsettable++;
                }
                if (!fontResources[font]->canEmbed()) {
                    notEmbeddable++;
                }
            }
        }
    }
    if (notSubsettableCount) {
        *notSubsettableCount = notSubsettable;

    }
    if (notEmbeddableCount) {
        *notEmbeddableCount = notEmbeddable;
    }
}