view to pdf & html to pdf

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

view to pdf & html to pdf

文章rusli » 週六 12月 05, 2015 7:03 pm

PDFMaker.zip
(24.9 KiB) 已下載 14 次


代碼: 選擇全部

import Foundation
import UIKit

class PathUtil
{
    class func Root() -> String
    {
        return NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true).first! + NSBundle.mainBundle().bundleIdentifier!
    }
   
    class func FullPath(pathName: String) -> String
    {
        var fullPath: String = "\(self.Root())/\(pathName)"
        if(pathName.characters.count == 0)
        {
            fullPath = self.Root()
        }
       
        do{
            try NSFileManager.defaultManager().createDirectoryAtPath(fullPath, withIntermediateDirectories: true, attributes: nil)
        }catch{
            print("path Error")
        }
       
        return fullPath
    }
   
    class func Path(pathName: String, fileName: String) -> String
    {
        return "\(self.FullPath(pathName))/\(fileName)"
    }
}



代碼: 選擇全部


class PDFMaker
{
    static var FileName: String = ""
    static var FolderName: String = "Attachments"
    static var FileNameExtension: String = ".pdf"
   
    static func Init(fileName: String)
    {
        self.FileName = "\(fileName)\(FileNameExtension)"
    }
   
    static func FullPath() -> String
    {
        let dir : NSString = PathUtil.FullPath(self.FolderName)
        return dir.stringByAppendingPathComponent(self.FileName)
    }
   
    static private func WriteToFile(data: NSData, fileName: String)
    {
        if let dir : NSString = PathUtil.FullPath(self.FolderName) {
            let documentPath = dir.stringByAppendingPathComponent(self.FileName);
            print("pdf: \(documentPath)")
            data.writeToFile(documentPath, atomically: true)
        }
    }
   
    static func ViewToPdf(fileName: String, views: [UIView])
    {
        self.Init(fileName)
       
        if views.isEmpty
        {
            return
        }
       
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, CGRect(x: 0, y: 0, width: 612, height: 792), nil)
       
        let context = UIGraphicsGetCurrentContext()
       
        for view in views {
            UIGraphicsBeginPDFPage()
            view.layer.renderInContext(context!)
        }
       
        UIGraphicsEndPDFContext()
       
        self.WriteToFile(pdfData, fileName: fileName)
    }
   
    static func HtmlToPdf(fileName: String, html: String)
    {
        self.Init(fileName)
       
        // 1. Create a print formatter
        let fmt = UIMarkupTextPrintFormatter(markupText: html)
       
        // 2. Assign print formatter to UIPrintPageRenderer
        let render = UIPrintPageRenderer()
        render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)
       
        // 3. Assign paperRect and printableRect
        let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
        let printable = CGRectInset(page, 0, 0)
       
        render.setValue(NSValue(CGRect: page), forKey: "paperRect")
        render.setValue(NSValue(CGRect: printable), forKey: "printableRect")
       
        // 4. Create PDF context and draw
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)
       
        for i in 1...render.numberOfPages() {
            UIGraphicsBeginPDFPage();
            let bounds = UIGraphicsGetPDFContextBounds()
            render.drawPageAtIndex(i - 1, inRect: bounds)
        }
       
        UIGraphicsEndPDFContext()
        self.WriteToFile(pdfData, fileName: fileName)
    }
}


代碼: 選擇全部

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        PDFMaker.ViewToPdf("contacts_views", views: [self.view])
        PDFMaker.HtmlToPdf("contacts_html", html: "<table><tr><td>FOO</td><td>BAR</td></tr></table>")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


回到「Swift」

誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 1 位訪客