1 /*
2 * Copyright 2020 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 #include "include/core/SkTypes.h"
8
9 #ifdef SK_SUPPORT_PDF
10 #include "include/core/SkAnnotation.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkDocument.h"
15 #include "include/core/SkFont.h"
16 #include "include/core/SkPaint.h"
17 #include "include/core/SkRect.h"
18 #include "include/core/SkRefCnt.h"
19 #include "include/core/SkScalar.h"
20 #include "include/core/SkSize.h"
21 #include "include/core/SkStream.h"
22 #include "include/core/SkString.h"
23 #include "include/core/SkTypeface.h"
24 #include "include/docs/SkPDFDocument.h"
25 #include "src/pdf/SkPDFUtils.h"
26 #include "tests/Test.h"
27 #include "tools/fonts/FontToolUtils.h"
28
29 #include <memory>
30 #include <utility>
31 #include <vector>
32
33 using PDFTag = SkPDF::StructureElementNode;
34
35 // Test building a tagged PDF with links.
36 // Add this to args.gn to output the PDF to a file:
37 // extra_cflags = [ "-DSK_PDF_TEST_TAGS_OUTPUT_PATH=\"/tmp/links.pdf\"" ]
DEF_TEST(SkPDF_tagged_links,r)38 DEF_TEST(SkPDF_tagged_links, r) {
39 REQUIRE_PDF_DOCUMENT(SkPDF_tagged_links, r);
40 #ifdef SK_PDF_TEST_TAGS_OUTPUT_PATH
41 SkFILEWStream outputStream(SK_PDF_TEST_TAGS_OUTPUT_PATH);
42 #else
43 SkDynamicMemoryWStream outputStream;
44 #endif
45
46 SkSize pageSize = SkSize::Make(612, 792); // U.S. Letter
47
48 SkPDF::Metadata metadata;
49 metadata.fTitle = "Example Tagged PDF With Links";
50 metadata.fCreator = "Skia";
51 SkPDF::DateTime now;
52 SkPDFUtils::GetDateTime(&now);
53 metadata.fCreation = now;
54 metadata.fModified = now;
55
56 // The document tag.
57 auto root = std::make_unique<PDFTag>();
58 root->fNodeId = 1;
59 root->fTypeString = "Document";
60 root->fLang = "en-US";
61
62 // A link.
63 auto l1 = std::make_unique<PDFTag>();
64 l1->fNodeId = 2;
65 l1->fTypeString = "Link";
66 root->fChildVector.push_back(std::move(l1));
67
68 metadata.fStructureElementTreeRoot = root.get();
69 sk_sp<SkDocument> document = SkPDF::MakeDocument(
70 &outputStream, metadata);
71
72 SkPaint paint;
73 paint.setColor(SK_ColorBLUE);
74
75 SkCanvas* canvas =
76 document->beginPage(pageSize.width(),
77 pageSize.height());
78 SkFont font(ToolUtils::DefaultTypeface(), 20);
79
80 // The node ID should cover both the text and the annotation.
81 SkPDF::SetNodeId(canvas, 2);
82 canvas->drawString("Click to visit Google.com", 72, 72, font, paint);
83 SkRect linkRect = SkRect::MakeXYWH(
84 SkIntToScalar(72), SkIntToScalar(54),
85 SkIntToScalar(218), SkIntToScalar(24));
86 sk_sp<SkData> url(SkData::MakeWithCString("http://www.google.com"));
87 SkAnnotateRectWithURL(canvas, linkRect, url.get());
88
89 document->endPage();
90 document->close();
91 outputStream.flush();
92 }
93
94 #endif
95