我只需要在我的iPhone应用程序中使用SWIFT创建一个pdf文件,以便稍后通过电子邮件发送。
pdf创建好并显示所有好(标签和图像),但应在WebView中显示的HTML内容无法正确呈现(只显示白色的空WebView)。
以下是我正在尝试的测试代码
func generatePdf() -> String
{
var pdfLoacation: String = ""
var pageSize: CGSize! = CGSize(width: 612, height: 792)
var fileName: String = "MySimpleDoc.pdf"
var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as NSArray
var documentDirectory = path.objectAtIndex(0) as! String
pdfLoacation = documentDirectory.stringByAppendingPathComponent(fileName)
println("Document Directory: \(pdfLoacation)")
UIGraphicsBeginPDFContextToFile(pdfLoacation, CGRectZero, nil)
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil)
var pdfContext: CGContextRef = UIGraphicsGetCurrentContext()
var testView = UIView(frame: CGRectMake(0, 0, pageSize.width, pageSize.height))
testView.backgroundColor = UIColor.yellowColor()
// Adding a Label to 'testView'
var label = UILabel(frame: CGRectMake(10, 10, 200, 20))
label.textColor = UIColor.redColor()
label.backgroundColor = UIColor.lightGrayColor()
label.text = "I'am a test label"
testView.addSubview(label)
// PROBLEM::: [NOT DISPLAY HTML????]
// Adding a Webview 'testView'
let htmlString: String = "<html> <body> <h1> Hello from WebView! </h1> </body> </html>"
var webView = UIWebView(frame: CGRectMake(10, 35, 300, 200))
webView.loadHTMLString(htmlString, baseURL: nil)
testView.addSubview(webView)
// Adding a saved image to 'testView'
let defaults = NSUserDefaults.standardUserDefaults()
if let imageData = defaults.objectForKey("MyImage") as? NSData
{
var myImage = UIImageView(frame: CGRectMake(10, 260, 150, 100))
myImage.image = UIImage(data: imageData)
testView.addSubview(myImage)
}
// adding 'testView' to pdf context...
testView.layer.renderInContext(pdfContext)
UIGraphicsEndPDFContext()
return pdfLoacation
}
我在pdf中获得的所有内容如下。
所有内容(标签和图像)都按照我的预期显示,但WebView根本无法呈现它的HTML内容(h1标记内容 - &#34;来自WebView的好消息!&#34;) ...而只是以白色显示空WebView ......