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"
4 REG_FIDDLE(PDF, 256, 256, true, 0) {
6 // Here is an example of using Skia’s PDF backend (SkPDF) via the SkDocument
8 void WritePDF(SkWStream* outputStream,
9 const char* documentTitle,
10 void (*writePage)(SkCanvas*, int page),
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(),
23 writePage(pageCanvas, page);
24 pdfDocument->endPage();
29 // Print binary data to stdout as hex.
30 void print_data(const SkData* data, const char* name) {
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]);
39 SkDebugf("\nEOF\n\n");
43 // example function that draws on a SkCanvas.
44 void write_page(SkCanvas* canvas, int) {
45 const SkScalar R = 115.2f, C = 128.0f;
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));
53 paint.setStyle(SkPaint::kStroke_Style);
54 canvas->drawPath(path, paint);
57 void 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");