Skip to content

Commit

Permalink
Add ImageRenderer demo (#198)
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzalezreal authored Mar 11, 2023
1 parent 5766bca commit 4392c3c
Showing 1 changed file with 43 additions and 11 deletions.
54 changes: 43 additions & 11 deletions Examples/Demo/Demo/RepositoryReadmeView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ struct RepositoryReadmeView: View {
`README.md` file and how to implement a custom `OpenURLAction` that
scrolls to the corresponding heading when the user taps on an anchor
link.
Additionally, it shows how to use an `ImageRenderer` to render the `README.md`
file into a PDF.
"""

@State private var owner = "apple"
Expand Down Expand Up @@ -59,24 +62,33 @@ private struct ReadmeView: View {
} else {
ScrollViewReader { proxy in
ScrollView {
Group {
if let response, let content = response.decodedContent {
Markdown(content, baseURL: response.baseURL, imageBaseURL: response.imageBaseURL)
} else {
Markdown("Oops! Something went wrong while fetching the README file.")
}
}
.padding()
.background(Theme.gitHub.textBackgroundColor)
.markdownTheme(.gitHub)
.scrollToMarkdownHeadings(using: proxy)
content
.scrollToMarkdownHeadings(using: proxy)
}
}
}
}
.onAppear {
self.loadContent()
}
.toolbar {
if !self.isLoading {
ShareLink(item: self.renderPDF())
}
}
}

private var content: some View {
Group {
if let response, let content = response.decodedContent {
Markdown(content, baseURL: response.baseURL, imageBaseURL: response.imageBaseURL)
} else {
Markdown("Oops! Something went wrong while fetching the README file.")
}
}
.padding()
.background(Theme.gitHub.textBackgroundColor)
.markdownTheme(.gitHub)
}

private func loadContent() {
Expand All @@ -86,6 +98,26 @@ private struct ReadmeView: View {
self.isLoading = false
}
}

@MainActor private func renderPDF() -> URL {
let url = URL.documentsDirectory.appending(path: "README.pdf")
let renderer = ImageRenderer(content: self.content.padding())
renderer.proposedSize = .init(width: UIScreen.main.bounds.width, height: nil)

renderer.render { size, render in
var mediaBox = CGRect(origin: .zero, size: size)
guard let context = CGContext(url as CFURL, mediaBox: &mediaBox, nil) else {
return
}

context.beginPDFPage(nil)
render(context)
context.endPDFPage()
context.closePDF()
}

return url
}
}

// MARK: - Heading anchor scrolling
Expand Down

0 comments on commit 4392c3c

Please sign in to comment.