Swift convert Html to PDF but the CSS formatting disappear - html

I am now have UIWebView in my view controller , and I have the html file ( Template.html, including the css inside),using the Mustache to load the data to the html, just like this:
let template = Template(named: "Template")!
let rendering = template.render(Box(self.data))!
and then show it on the webview using this
self.webView.loadHTMLString(rendering, baseURL: nil))
self.webView.scalesPageToFit = true;
all it works well. Then I wanna transform this html to pdf and also show on the same web view, but it looks that all my css layout doesn't work anymore. It only show me the html text and without layout setting by the css.
I used this method to convert to pdf: https://gist.github.com/nyg/b8cd742250826cb1471f
and the only change is
let fmt = UIMarkupTextPrintFormatter(markupText: rendering)
render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)
and then save the pdf, and load it again by the web view
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
var pdfFile = documentsPath.stringByAppendingPathComponent("invoice.PDF")
pdfData.writeToFile(pdfFile, atomically: true)
let url : NSURL! = NSURL(string: pdfFile)
webView.loadRequest(NSURLRequest(URL: url))
But now the pdf has no layout provided by the css(such like the color, the position), but still has the html layout(such like the <\br>), I don't know why, please help me!!!
Thanks !!!

Related

Can't load from documents folder into webView on iOS

I'm unsuccessfully trying to load some html and images from documents folder on iOS. Can someone help me to understand why this code does not work?
let html = "<html><body><font size='20>oi</font></body></html>"
let saveHTML = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("sample.html")
try? html.data(using: .utf8)!.write(to: saveHTML)
webView.load(URLRequest(url: saveHTML))
The problem was simple to solve, it was a lack of rights:
webView.loadFileURL(saveHTML, allowingReadAccessTo: saveHTML)

Edit and Load HTML from local file in Swift

I have a .html file stored in my project bundle. When I load it in WebView.(UIWebview/WKWebview) the data is loaded but the table structure in it isn't visible. The table borders, columns , rows. The values are just floating . In Chrome browser it opens properly.
let myURL = Bundle.main.url(forResource: "prescription", withExtension: "html")
let myURLRequest:URLRequest = URLRequest(url: myURL!)
webView.loadRequest(myURLRequest)
Chrome browser :
iOS App UIWebView :
The Html page is made responsive to fit in any sizes but I am not able to load in UIWebview properly as Web.
I need to store the file locally because I need to make changes to its values and show on webview.
Found the solution :
If you are applying some local css whose path is there in HTML file.
viz.
Add that css file "myDefault.css" to your xcode project directory.
Convert the HTML to string and replace the path of css in HTML file with your local path. :
Load the content of HTML to UIWebView with base url. (Providing local file path as baseUrl is important)
webView = UIWebView()
let pathToInvoiceHTMLTemplate = Bundle.main.path(forResource: "presc", ofType: "html")
let pathToHTMLCSS = Bundle.main.path(forResource: "myDefault", ofType: "css")
do {
var strHTMLContent = try String(contentsOfFile: pathToInvoiceHTMLTemplate!)
strHTMLContent = strHTMLContent.replacingOccurrences(of: "./assets/stylesheets/myDefault.css", with: pathToHTMLCSS!)
let pdfURL = URL(fileURLWithPath: pathToInvoiceHTMLTemplate!)
webView.loadHTMLString(strHTMLContent, baseURL: pdfURL)
}catch let err{
print(err)
}
When loading local content into the WKWebView, you shoudl use loadHTMLString(_:baseURL:) instead of loadRequest. The first function allows you to provide a base URL, which you will also let point into the bundle - so you clearly need to add all the relevant files to your application bundle.
guard let indexPath = Bundle.main.path(forResource: "index", ofType: "html"),
let content = try String(contentsOfFile: indexPath, encoding: .utf8),
let baseUrl = URL(fileURLWithPath: indexPath) else {
// Error handling
}
webView.loadHTMLString(content, baseURL: baseUrl)

Video thumbnail image moving for inset image using jwplayer video embedded Html content in web view from navigate in swift

I am using html content for uiwebview in swift but going to one view controller to another controller navigate suddenly moving inner video image.i tried to clear web view- refer link How To Clear A UIWebView and
also used autoresizing autoresizingMask = .flexibleWidth but didn't solved.Clear web view cache using in viewDiddisappear cann't get solution[
Swift 3.0 code:
let htmlString:String = descriptionHtml
webView.loadHTMLString(htmlString, baseURL: nil)
webView.scrollView.isScrollEnabled = false
webView.allowsInlineMediaPlayback = true
let aStr = String(format: "%#%x", "document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ", webView.frame.size.width)
webView.stringByEvaluatingJavaScript(from: aStr)
webView.delegate = self
I would appreciate if someone could help.

Swift: UIActivityViewController with HTML content

How can send an email with HTML text? I use this code to send email from my swift application:
let subject = "Email test"
let content = "This is some text that I want to share."
// set up activity view controller
let objectsToShare = [content]
let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityViewController.setValue(subject, forKey: "Subject")
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
I want that the content had some HTML tags and to be interpreted as HTML.
How can I do that? Can anyone please provide me an exmaple?
I don't know if you're still looking for an answer but if you are, you just have to put the html tags around your content:
let content = "<html><body>This is some text that I want to share.</body></html>"
You can also create a subclass of UIActivityItemProvider so you can convert the html to an NSAttributedString depending on the application (e.g. the mail app supports html, but for the notes app you can convert it to an NSAttributedString).

load html file to UIWebview from documents directory on ios with swift

I have an html file and other files that html uses(css,.png) that is saved in the documents directory.How can I load this html file in a UIWebView or wkwebview
using swift?I have found some examples in objective-c but nothing in swift.I don't know anything about objective-c..
let path=getCurrenttHtmlStartPage()
var hContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
webView!.loadHTMLString(hContent, baseURL: nil)
webView!.hidden=false
Path is the path in documents folder. /Users/pmdevios/Library/.../Documents/Content/Html/index.html.
With this way the other files inside html aren't showing(images) so I want to do it with another way like this
webView!.loadFileURL(path, allowingReadAccessToURL: path)
With the below code it worked!
let filePath = (folder as NSString).stringByAppendingPathComponent(_currentHtmlStartPage!)
var url:NSURL=NSURL(fileURLWithPath:filePath)
var request:NSURLRequest=NSURLRequest(URL:url)
webView!.loadRequest(request)
folder:string that represents the path in the documents folder
_currentHtmlStartPage:string of file's name (e.g. index.html)
EDIT
Get URL using NSFileManger instance method URLsForDirectory(inDomains:)
Append the file name (myFile.html) to the URL we get back from NSFileManager
Initialize a NSURLRequest object with the URL.
Use the UIWebView or WKWebView class to load the request.
let fileManager = NSFileManager.defaultManager()
var URL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
URL = URL.URLByAppendingPathComponent("myFile.html")
let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)
Of the top of my head:
if let fileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "html") {
let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)
}
You'll need a flat directory structure in your html and css files because that's how they end up in the app.