I have to covert net web page to PDF.
I need to give you a method to covert net web page to pdf with the unique measurement that’s proven while you’re scrolling this web page in browser on iPhone.
What I’ve finished for now: changing webpage to PDF, however with printing format solely.
Print choice is just not sufficient for me as the dimensions of the web page adjustments as for printing.
However what I wish to obtain is producing a PDF from a webpage in the identical manner how we will create a screenshot of the web page after which create it as PDF. (so the unique measurement and content material is just not modified and appears precisely the way it appears to be like on iPhone)
// ViewController.swift
import UIKit
import WebKit
import PDFKit
class ViewController: UIViewController, UISearchBarDelegate, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
tremendous.viewDidLoad()
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
let url = URL(string: "(searchBar.textual content!)")//zrobic choose 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, peak: 841.8) //set desired sizes
let margin = CGFloat(20.0)
renderer.setValue(NSValue(cgRect: CGRect(x: margin, y: margin, width: pageSize.width, peak: pageSize.peak - margin * 2.0)), forKey: "paperRect")
renderer.setValue(NSValue(cgRect: CGRect(x: 0, y: 0, width: pageSize.width, peak: pageSize.peak)), 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")
strive? pdfData.write(to: filePath, choices: .atomic)
let activityViewController = UIActivityViewController(activityItems: [filePath], applicationActivities: [])
current(activityViewController, animated: true, completion: nil)
}
}