Creating PDF in Swift, UIView to View

I'm trying to create a simple PDF with Swift. I get an error: Referencing static method 'buildBlock' on 'Optional' requires that 'UIView' conform to 'View'

Probably doing a ton of stuff wrong. I think I need to be able to somehow change the UIView to a view to be displayed.

My Code below:

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()
    }
}


Read more here: https://stackoverflow.com/questions/65712343/creating-pdf-in-swift-uiview-to-view

Content Attribution

This content was originally published by Etienne at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: