Debian Codegraph @

docs/examples/PDF.cpp

raw
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) {
5
6 // Here is an example of using Skia’s PDF backend (SkPDF) via the SkDocument
7 // and SkCanvas APIs.
8 void 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 // See also SkPDF::JPEG::MetadataWithCallbacks()
19 metadata.jpegDecoder = SkPDF::JPEG::Decode;
20 metadata.jpegEncoder = SkPDF::JPEG::Encode;
21 auto pdfDocument = SkPDF::MakeDocument(outputStream, metadata);
22 SkASSERT(pdfDocument);
23 for (int page = 0; page < numberOfPages; ++page) {
24 SkCanvas* pageCanvas = pdfDocument->beginPage(pageSize.width(),
25 pageSize.height());
26 writePage(pageCanvas, page);
27 pdfDocument->endPage();
28 }
29 pdfDocument->close();
30 }
31
32 // Print binary data to stdout as hex.
33 void print_data(const SkData* data, const char* name) {
34 if (data) {
35 SkDebugf("\nxxd -r -p > %s << EOF", name);
36 size_t s = data->size();
37 const uint8_t* d = data->bytes();
38 for (size_t i = 0; i < s; ++i) {
39 if (i % 40 == 0) { SkDebugf("\n"); }
40 SkDebugf("%02x", d[i]);
41 }
42 SkDebugf("\nEOF\n\n");
43 }
44 }
45
46 // example function that draws on a SkCanvas.
47 void write_page(SkCanvas* canvas, int) {
48 const SkScalar R = 115.2f, C = 128.0f;
49 SkPathBuilder path;
50 path.moveTo(C + R, C);
51 for (int i = 1; i < 8; ++i) {
52 SkScalar a = 2.6927937f * i;
53 path.lineTo(C + R * cos(a), C + R * sin(a));
54 }
55 SkPaint paint;
56 paint.setStyle(SkPaint::kStroke_Style);
57 canvas->drawPath(path.detach(), paint);
58 }
59
60 void draw(SkCanvas*) {
61 constexpr SkSize ansiLetterSize{8.5f * 72, 11.0f * 72};
62 SkDynamicMemoryWStream buffer;
63 WritePDF(&buffer, "SkPDF Example", &write_page, 1, ansiLetterSize);
64 sk_sp<SkData> pdfData = buffer.detachAsData();
65 print_data(pdfData.get(), "skpdf_example.pdf");
66 }
67 } // END FIDDLE