xref: /aosp_15_r20/external/skia/example/external_client/src/write_to_pdf.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2023 Google LLC
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 
8 #include "include/core/SkDocument.h"
9 #include "include/core/SkAlphaType.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColor.h"
12 #include "include/core/SkImageInfo.h"
13 #include "include/core/SkRefCnt.h"
14 #include "include/core/SkTypeface.h"
15 #include "include/core/SkFont.h"
16 #include "include/core/SkFontStyle.h"
17 #include "include/core/SkFontMgr.h"
18 #include "include/core/SkPixmap.h"
19 #include "include/core/SkSurface.h"
20 #include "include/core/SkStream.h"
21 #include "include/docs/SkPDFDocument.h"
22 
23 #if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE) && defined(SK_TYPEFACE_FACTORY_FREETYPE)
24 #include "include/ports/SkFontMgr_fontconfig.h"
25 #include "include/ports/SkFontScanner_FreeType.h"
26 #endif
27 
28 #if defined(SK_FONTMGR_CORETEXT_AVAILABLE)
29 #include "include/ports/SkFontMgr_mac_ct.h"
30 #endif
31 
32 #include <cstdio>
33 
main(int argc,char ** argv)34 int main(int argc, char** argv) {
35     if (argc != 2) {
36         printf("Usage: %s <name.pdf>", argv[0]);
37         return 1;
38     }
39     SkFILEWStream output(argv[1]);
40     if (!output.isValid()) {
41         printf("Cannot open output file %s\n", argv[1]);
42         return 1;
43     }
44 
45     SkPDF::Metadata metadata;
46     metadata.fTitle = "Test PDF";
47     metadata.fAuthor = "Skia Demo Writer";
48     metadata.fLang = "eng";
49     metadata.fEncodingQuality = 90;
50 
51     sk_sp<SkDocument> pdf = SkPDF::MakeDocument(&output, metadata);
52     SkCanvas* canvas = pdf->beginPage(100, 50);
53 
54     sk_sp<SkFontMgr> mgr;
55 #if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE) && defined(SK_TYPEFACE_FACTORY_FREETYPE)
56     mgr = SkFontMgr_New_FontConfig(nullptr, SkFontScanner_Make_FreeType());
57 #elif defined(SK_FONTMGR_CORETEXT_AVAILABLE)
58     mgr = SkFontMgr_New_CoreText(nullptr);
59 #endif
60     if (!mgr) {
61         printf("No Font Manager configured\n");
62         return 1;
63     }
64     sk_sp<SkTypeface> face = mgr->matchFamilyStyle("Roboto", SkFontStyle());
65     if (!face) {
66       printf("Cannot open typeface\n");
67       return 1;
68     }
69     SkFont font(face, 14);
70     SkPaint paint;
71     paint.setColor(SK_ColorGREEN);
72     canvas->clear(SK_ColorYELLOW);
73     canvas->drawString("Hello world!", 10, 25, font, paint);
74 
75     pdf->endPage();
76     pdf->close();
77     return 0;
78 }
79