I have a custom view that adds a WKWebView like this:
override func awakeFromNib() {
super.awakeFromNib()
loadWebView()
}
func loadWebView() {
pdfWebView = WKWebView(frame: .zero)
pdfWebView.navigationDelegate = self
pdfWebView.translatesAutoresizingMaskIntoConstraints = false
pdfWebView.isHidden = true
self.addSubview(pdfWebView)
... add constrains to self anchors - top, left, right, bottom
}
When loads finishes, I have this:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: {
SVProgressHUD.dismiss()
webView.isHidden = false
webView.isOpaque = true
webView.adjustInsets()
})
}
I had to adjust the insets, because on iPhone X, sometimes the pdf sticked to the bottom, instead to the top.
extension WKWebView {
func adjustInsets() {
parentViewController?.automaticallyAdjustsScrollViewInsets = false
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
scrollView.contentOffset = .zero
}
}
The result is this:
There is a gray border.
I have tried this:
setting view's, pdfWebView and pdfWebView.scrollView background with .white or .clear
webView.isOpaque = false ( this is the single one that removes the bottom part of the gray - but not the border)
I have used an extension to set the .clear color to all child views
extension UIView {
func clearBackgrounds() {
self.backgroundColor = UIColor.clear
for subview in self.subviews {
subview.clearBackgrounds()
}
}
}
Nothing works to remove the border. I can not edit the pdf, because this one is downloaded from ws and used in multiple apps.
Solution : I found a trick to do this, I think you can use this with pdf that has white background. It has the idea, you can manipulate this with your design.
self.view.backgroundColor = UIColor.white
let urlString = "http://www.africau.edu/images/default/sample.pdf"
let string = "<html><body marginwidth=\"0\" marginheight=\"0\" style=\"background-color: transparent\"><embed width=\"100%\" height=\"100%\" name=\"plugin\" src=\"\(urlString)\" type=\"application/pdf\"></body></html>"
webView.loadHTMLString(string, baseURL: nil)
Edit : If you want to use this with base64 encoded pdf data, you can use with that :
var pdfBase64String = "" //Your pdf data
if let decodedData = Data(base64Encoded: pdfBase64String, options: .ignoreUnknownCharacters) {
pdfWebView.load(decodedData, mimeType: "application/pdf", characterEncodingName: "utf-8", baseURL: URL(fileURLWithPath: ""))
}
Old Answer : Turning off "WebKitDiskImageCacheEnabled" can be fix this problem. Can you try this before load the pdf ?
UserDefaults.standard.set(false, forKey: "WebKitDiskImageCacheEnabled")
UserDefaults.standard.synchronize()
I will use PDFKit for iOS 11 + in this custom view with the fallback to WKWebView for earlier versions. PDFView does not have any gray background.