blob: 591ed33d5479f519fa409461f4a0ef0a2b8505e5 [file] [log] [blame]
Dominic Mazzonic227f4a2020-03-24 08:27:54 -07001/*
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 "tests/Test.h"
8
9#ifdef SK_SUPPORT_PDF
10
11#include "include/core/SkAnnotation.h"
12#include "include/core/SkCanvas.h"
13#include "include/core/SkFont.h"
14#include "include/core/SkStream.h"
15#include "include/docs/SkPDFDocument.h"
16
17using PDFTag = SkPDF::StructureElementNode;
18
19// Test building a tagged PDF with links.
20// Add this to args.gn to output the PDF to a file:
21// extra_cflags = [ "-DSK_PDF_TEST_TAGS_OUTPUT_PATH=\"/tmp/links.pdf\"" ]
22DEF_TEST(SkPDF_tagged_links, r) {
23 REQUIRE_PDF_DOCUMENT(SkPDF_tagged_links, r);
24#ifdef SK_PDF_TEST_TAGS_OUTPUT_PATH
25 SkFILEWStream outputStream(SK_PDF_TEST_TAGS_OUTPUT_PATH);
26#else
27 SkDynamicMemoryWStream outputStream;
28#endif
29
30 SkSize pageSize = SkSize::Make(612, 792); // U.S. Letter
31
32 SkPDF::Metadata metadata;
33 metadata.fTitle = "Example Tagged PDF With Links";
34 metadata.fCreator = "Skia";
35 SkTime::DateTime now;
36 SkTime::GetDateTime(&now);
37 metadata.fCreation = now;
38 metadata.fModified = now;
39
40 // The document tag.
41 auto root = std::make_unique<PDFTag>();
42 root->fNodeId = 1;
43 root->fTypeString = "Document";
44 root->fLang = "en-US";
45
46 // A link.
47 auto l1 = std::make_unique<PDFTag>();
48 l1->fNodeId = 2;
49 l1->fTypeString = "Link";
50 root->fChildVector.push_back(std::move(l1));
51
52 metadata.fStructureElementTreeRoot = root.get();
53 sk_sp<SkDocument> document = SkPDF::MakeDocument(
54 &outputStream, metadata);
55
56 SkPaint paint;
57 paint.setColor(SK_ColorBLUE);
58
59 SkCanvas* canvas =
60 document->beginPage(pageSize.width(),
61 pageSize.height());
62 SkFont font(nullptr, 20);
63
64 // The node ID should cover both the text and the annotation.
65 SkPDF::SetNodeId(canvas, 2);
66 canvas->drawString("Click to visit Google.com", 72, 72, font, paint);
67 SkRect linkRect = SkRect::MakeXYWH(
68 SkIntToScalar(72), SkIntToScalar(54),
69 SkIntToScalar(218), SkIntToScalar(24));
70 sk_sp<SkData> url(SkData::MakeWithCString("http://www.google.com"));
71 SkAnnotateRectWithURL(canvas, linkRect, url.get());
72
73 document->endPage();
74 document->close();
75 outputStream.flush();
76}
77
78#endif