如何将网页另存为PDF? [英] How to save web page as PDF?

查看:623
本文介绍了如何将网页另存为PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序中有一个Web视图,该Web视图顶部有一个保存"按钮.

There is a webview in the app and a "Save" button on top of the webview.

单击保存"按钮后,currenturl将被保存到另一个ViewController上的TableView中.一切正常.

After clicking the "Save" button currenturl will be saved to a TableView on another ViewController. Everything works fine.

现在,我还要将网页另存为PDF到同一TableView中,并可以在单击后将其打开.我怎样才能做到这一点?

Now I would like to also save the web page as PDF to the same TableView and can open it after clicking. How can I do that?

以下是用于保存currenturl的代码. savedURLs是用于将所有网址保存在另一个ViewController上的数组.

The following is codes for saving currenturl. savedURLs is the array to save all urls on another ViewController.

import UIKit

class BrowserViewController: UIViewController {

    @IBOutlet weak var browser: UIWebView!

    @IBAction func saveButtonPressed(sender: AnyObject) {
        if let currentURL = browser.request?.URL?.absoluteString  {
            savedURLs.append(currentURL)
            NSUserDefaults.standardUserDefaults().setObject(currentURL, forKey: "currenturl")
            NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: "savedURLs")
            self.performSegueWithIdentifier("toSavingVC", sender: self)
        }
    }

推荐答案

下面是将WebPage转换为图像的Swift代码,然后可以将其转换为PDF:

Here is the Swift code for converting webPage to image, then you can convert it to PDF:

    let sizevid = CGSizeMake(1024, 1100)

    UIGraphicsBeginImageContext(sizevid);

    webview.layer.renderInContext(UIGraphicsGetCurrentContext()!)

    let viewImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    var imageData = NSData()

    imageData = UIImagePNGRepresentation(viewImage)!

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

    let pathFolder = String(String(format:"%@", "new.png"))

    let defaultDBPathURL = NSURL(fileURLWithPath: documentsPath).URLByAppendingPathComponent(pathFolder)

    let defaultDBPath = "\(defaultDBPathURL)"

    imageData.writeToFile(defaultDBPath, atomically: true)

    // After converting it in to an image you can easily convert it as pdf.

这篇关于如何将网页另存为PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆