我正在尝试用Swift创建一个简单的PDF。我得到一个错误:在"Optional"上引用静态方法"buildBlock"要求"UIView"符合"View">
可能做错了很多事。我认为我需要能够以某种方式将UIView更改为要显示的视图。
下面的我的代码:
import SwiftUI
import PDFKit
public var documentData: Data?
let pdfView = PDFView()
func myPDF() -> Data {
let pdfMetaData = [
kCGPDFContextCreator: "my PDF",
kCGPDFContextAuthor: "etienne"
]
let format = UIGraphicsPDFRendererFormat()
format.documentInfo = pdfMetaData as [String: Any]
let pageWidth = 8.5 * 72.0
let pageHeight = 11 * 72.0
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
let data = renderer.pdfData { (context) in
context.beginPage()
let attributes = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
]
let text = "Hello World!"
text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
}
return data
}
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
.onAppear(perform: {
if let data = documentData {
pdfView.document = PDFDocument(data: createFlyer())
pdfView.autoScales = true
}
})
pdfView.documentView
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我设法用以下方法实现了这一点:
import SwiftUI
import PDFKit
public var documentData: Data?
let pdfView = PDFView()
func myPDF() -> Data {
let pdfMetaData = [
kCGPDFContextCreator: "my PDF",
kCGPDFContextAuthor: "etienne"
]
let format = UIGraphicsPDFRendererFormat()
format.documentInfo = pdfMetaData as [String: Any]
let pageWidth = 8.5 * 72.0
let pageHeight = 11 * 72.0
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
let data = renderer.pdfData { (context) in
context.beginPage()
let attributes = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
]
let text = "Hello World!"
text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
}
return data
}
struct GeneratePDFView: UIViewRepresentable {
init() {
}
func makeUIView(context: UIViewRepresentableContext<GeneratePDFView>) -> GeneratePDFView.UIViewType {
let pdfView = PDFView()
pdfView.document = PDFDocument(data: myPDF())
return pdfView
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<GeneratePDFView>) {
}
}
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
.onAppear(perform: {
})
GeneratePDFView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
创建了返回生成的PDFView的UIViewRepresentable。
我真的不明白。因此,对此发表任何评论都是非常好的。
谢谢