xref: /third_party/skia/docs/examples/PDF.cpp (revision cb93a386)
1// Copyright 2019 Google LLC.
2// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3#include "tools/fiddle/examples.h"
4REG_FIDDLE(PDF, 256, 256, true, 0) {
5
6// Here is an example of using Skia’s PDF backend (SkPDF) via the SkDocument
7// and SkCanvas APIs.
8void WritePDF(SkWStream* outputStream,
9              const char* documentTitle,
10              void (*writePage)(SkCanvas*, int page),
11              int numberOfPages,
12              SkSize pageSize) {
13    SkPDF::Metadata metadata;
14    metadata.fTitle = documentTitle;
15    metadata.fCreator = "Example WritePDF() Function";
16    metadata.fCreation = {0, 2019, 1, 4, 31, 12, 34, 56};
17    metadata.fModified = {0, 2019, 1, 4, 31, 12, 34, 56};
18    auto pdfDocument = SkPDF::MakeDocument(outputStream, metadata);
19    SkASSERT(pdfDocument);
20    for (int page = 0; page < numberOfPages; ++page) {
21        SkCanvas* pageCanvas = pdfDocument->beginPage(pageSize.width(),
22                                                      pageSize.height());
23        writePage(pageCanvas, page);
24        pdfDocument->endPage();
25    }
26    pdfDocument->close();
27}
28
29// Print binary data to stdout as hex.
30void print_data(const SkData* data, const char* name) {
31    if (data) {
32        SkDebugf("\nxxd -r -p > %s << EOF", name);
33        size_t s = data->size();
34        const uint8_t* d = data->bytes();
35        for (size_t i = 0; i < s; ++i) {
36            if (i % 40 == 0) { SkDebugf("\n"); }
37            SkDebugf("%02x", d[i]);
38        }
39        SkDebugf("\nEOF\n\n");
40    }
41}
42
43// example function that draws on a SkCanvas.
44void write_page(SkCanvas* canvas, int) {
45    const SkScalar R = 115.2f, C = 128.0f;
46    SkPath path;
47    path.moveTo(C + R, C);
48    for (int i = 1; i < 8; ++i) {
49        SkScalar a = 2.6927937f * i;
50        path.lineTo(C + R * cos(a), C + R * sin(a));
51    }
52    SkPaint paint;
53    paint.setStyle(SkPaint::kStroke_Style);
54    canvas->drawPath(path, paint);
55}
56
57void draw(SkCanvas*) {
58    constexpr SkSize ansiLetterSize{8.5f * 72, 11.0f * 72};
59    SkDynamicMemoryWStream buffer;
60    WritePDF(&buffer, "SkPDF Example", &write_page, 1, ansiLetterSize);
61    sk_sp<SkData> pdfData = buffer.detachAsData();
62    print_data(pdfData.get(), "skpdf_example.pdf");
63}
64}  // END FIDDLE
65