Skip to content

Commit 4392c3c

Browse files
authored
Add ImageRenderer demo (#198)
1 parent 5766bca commit 4392c3c

File tree

1 file changed

+43
-11
lines changed

1 file changed

+43
-11
lines changed

Examples/Demo/Demo/RepositoryReadmeView.swift

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ struct RepositoryReadmeView: View {
77
`README.md` file and how to implement a custom `OpenURLAction` that
88
scrolls to the corresponding heading when the user taps on an anchor
99
link.
10+
11+
Additionally, it shows how to use an `ImageRenderer` to render the `README.md`
12+
file into a PDF.
1013
"""
1114

1215
@State private var owner = "apple"
@@ -59,24 +62,33 @@ private struct ReadmeView: View {
5962
} else {
6063
ScrollViewReader { proxy in
6164
ScrollView {
62-
Group {
63-
if let response, let content = response.decodedContent {
64-
Markdown(content, baseURL: response.baseURL, imageBaseURL: response.imageBaseURL)
65-
} else {
66-
Markdown("Oops! Something went wrong while fetching the README file.")
67-
}
68-
}
69-
.padding()
70-
.background(Theme.gitHub.textBackgroundColor)
71-
.markdownTheme(.gitHub)
72-
.scrollToMarkdownHeadings(using: proxy)
65+
content
66+
.scrollToMarkdownHeadings(using: proxy)
7367
}
7468
}
7569
}
7670
}
7771
.onAppear {
7872
self.loadContent()
7973
}
74+
.toolbar {
75+
if !self.isLoading {
76+
ShareLink(item: self.renderPDF())
77+
}
78+
}
79+
}
80+
81+
private var content: some View {
82+
Group {
83+
if let response, let content = response.decodedContent {
84+
Markdown(content, baseURL: response.baseURL, imageBaseURL: response.imageBaseURL)
85+
} else {
86+
Markdown("Oops! Something went wrong while fetching the README file.")
87+
}
88+
}
89+
.padding()
90+
.background(Theme.gitHub.textBackgroundColor)
91+
.markdownTheme(.gitHub)
8092
}
8193

8294
private func loadContent() {
@@ -86,6 +98,26 @@ private struct ReadmeView: View {
8698
self.isLoading = false
8799
}
88100
}
101+
102+
@MainActor private func renderPDF() -> URL {
103+
let url = URL.documentsDirectory.appending(path: "README.pdf")
104+
let renderer = ImageRenderer(content: self.content.padding())
105+
renderer.proposedSize = .init(width: UIScreen.main.bounds.width, height: nil)
106+
107+
renderer.render { size, render in
108+
var mediaBox = CGRect(origin: .zero, size: size)
109+
guard let context = CGContext(url as CFURL, mediaBox: &mediaBox, nil) else {
110+
return
111+
}
112+
113+
context.beginPDFPage(nil)
114+
render(context)
115+
context.endPDFPage()
116+
context.closePDF()
117+
}
118+
119+
return url
120+
}
89121
}
90122

91123
// MARK: - Heading anchor scrolling

0 commit comments

Comments
 (0)