Generate PDF with share option in Swift

import UIKit
import WebKit

class YourViewController: UIViewController {

    @IBOutlet weak var webview: WKWebView!
    override func viewDidLoad() {

        let html = "<b>Hello <i>World!</i></b>"
               let fmt = UIMarkupTextPrintFormatter(markupText: html)

               // 2. Assign print formatter to UIPrintPageRenderer
               let render = UIPrintPageRenderer()
               render.addPrintFormatter(fmt, startingAtPageAt: 0)

               // 3. Assign paperRect and printableRect
               let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
               render.setValue(page, forKey: "paperRect")
               render.setValue(page, forKey: "printableRect")

               // 4. Create PDF context and draw
               let pdfData = NSMutableData()
               UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)

               for i in 0..<render.numberOfPages {
                   render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())


               // 5. Save PDF file
               guard let outputURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("output").appendingPathExtension("pdf")
                   else { fatalError("Destination URL not created") }

               pdfData.write(to: outputURL, atomically: true)
               print("open \(outputURL.path)") // command to open the generated file
               let url = Bundle.main.url(forAuxiliaryExecutable: outputURL.path)

               if let url = url {
                   let urlRequest = URLRequest(url: url)
                let activityController = UIActivityViewController(activityItems: [webview.url], applicationActivities: nil)
                         let popover = activityController.popoverPresentationController
                         popover?.sourceView = self.view
                         popover?.barButtonItem = self.navigationItem.rightBarButtonItem
                         present(activityController, animated: true, completion: nil)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s