Convert WKWebView to PDF / Swift

110 views Asked by At

I need to covert web page to PDF.

I want to come up with a way to covert web page to pdf with the original size that is shown while you are scrolling this page in browser on iPhone.

What I have done for now: converting webpage to PDF, but with printing format only. Print option is not enough for me as the size of the page changes as for printing.

But what I would like to achieve is generating a PDF from a webpage in the same way how we can create a screenshot of the page and then create it as PDF. (so the original size and content is not changed and looks exactly how it looks on iPhone)

ViewController.swift

import UIKit
import WebKit
import PDFKit

class ViewController: UIViewController, UISearchBarDelegate, WKNavigationDelegate {
    
    @IBOutlet weak var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        
        searchBar.resignFirstResponder()
        let url = URL(string: "\(searchBar.text!)")//zrobic opt bind if let+https if else
        let request = URLRequest(url: url!)
        webView.load(request)
    }
    

    @IBAction func convertButton(_ sender: UIButton) {
      
       let url : NSURL! = NSURL(string: "\(String(describing: webView.url))")!
        webView.load(NSURLRequest(url: url as URL) as URLRequest)
       
        let printFormatter = webView.viewPrintFormatter()
        let renderer = UIPrintPageRenderer()
        renderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
        
        
        let pageSize = CGSize(width: 595.2, height: 841.8) //set desired sizes
    
        let margin = CGFloat(20.0)
        
       
        renderer.setValue(NSValue(cgRect: CGRect(x: margin, y: margin, width: pageSize.width, height: pageSize.height - margin * 2.0)), forKey: "paperRect")
        renderer.setValue(NSValue(cgRect: CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height)), forKey: "printableRect")
        
        
        let pdfData = NSMutableData()
        
        UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
        webView.drawHierarchy(in: webView.bounds, afterScreenUpdates: true)
        
        for i in 0..<renderer.numberOfPages {
            UIGraphicsBeginPDFPage()
            renderer.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
        }
        UIGraphicsEndPDFContext()

            let filePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("webview.pdf")
            try? pdfData.write(to: filePath, options: .atomic)
            let activityViewController = UIActivityViewController(activityItems: [filePath], applicationActivities: [])
            present(activityViewController, animated: true, completion: nil)
       
    } 
}
0

There are 0 answers