在 Swift、iOS 中将 tableView 转换为多页 PDF 的最佳方式之一

问题描述 投票:0回答:3

使用此函数获取多页 pdf 版本的 tableView,只需将您的 tableView 名称传递给此函数即可:-

func pdfDataWithTableView(tableView: UITableView) {


        let priorBounds = tableView.bounds
        let fittedSize = tableView.sizeThatFits(CGSizeMake(priorBounds.size.width, tableView.contentSize.height))
        tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height)
        let pdfPageBounds = CGRectMake(0, 0, tableView.frame.width, self.view.frame.height)
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds,nil)
        var pageOriginY: CGFloat = 0
        while pageOriginY < fittedSize.height {
            UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
            CGContextSaveGState(UIGraphicsGetCurrentContext())
            CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, -pageOriginY)
            tableView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
            CGContextRestoreGState(UIGraphicsGetCurrentContext())
            pageOriginY += pdfPageBounds.size.height
        }
        UIGraphicsEndPDFContext()
        tableView.bounds = priorBounds

        var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last! as NSURL
        docURL = docURL.URLByAppendingPathComponent( "myDocument.pdf")
        pdfData.writeToURL(docURL, atomically: true)
    }
ios swift uitableview pdf
3个回答
14
投票

快速更新

   func pdfDataWithTableView(tableView: UITableView) {    
        let priorBounds = tableView.bounds
        let fittedSize = tableView.sizeThatFits(CGSize(width:priorBounds.size.width, height:tableView.contentSize.height))
        tableView.bounds = CGRect(x:0, y:0, width:fittedSize.width, height:fittedSize.height)
        let pdfPageBounds = CGRect(x:0, y:0, width:tableView.frame.width, height:self.view.frame.height)    
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds,nil)
        var pageOriginY: CGFloat = 0
        while pageOriginY < fittedSize.height {
            UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
            UIGraphicsGetCurrentContext()!.saveGState()
            UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: -pageOriginY)
            tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
            UIGraphicsGetCurrentContext()!.restoreGState()
            pageOriginY += pdfPageBounds.size.height
        }
        UIGraphicsEndPDFContext()
        tableView.bounds = priorBounds
        var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
        docURL = docURL.appendingPathComponent("myDocument.pdf")
        pdfData.write(to: docURL as URL, atomically: true)
    }

2
投票

为了使 Raj Joshi 解决方案渲染具有不同单元格高度的整个表格,您需要在每个渲染周期更改表格视图的内容偏移量。

完整片段:

func pdfDataWithTableView(tableView: UITableView) {    
  let priorBounds = tableView.bounds

  let fittedSize = tableView.sizeThatFits(CGSize(
    width: priorBounds.size.width, 
    height: tableView.contentSize.height
  ))

  tableView.bounds = CGRect(
    x: 0, y: 0,
    width: fittedSize.width,
    height: fittedSize.height
  )

  let pdfPageBounds = CGRect(
    x :0, y: 0,
    width: tableView.frame.width, 
    height: self.view.frame.height
  )    

  let pdfData = NSMutableData()
  UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)

  var pageOriginY: CGFloat = 0
  while pageOriginY < fittedSize.height {
    UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
    UIGraphicsGetCurrentContext()!.saveGState()
    UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: -pageOriginY)
    tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
    UIGraphicsGetCurrentContext()!.restoreGState()
    pageOriginY += pdfPageBounds.size.height
    tableView.contentOffset = CGPoint(x: 0, y: pageOriginY) // move "renderer"
  }
  UIGraphicsEndPDFContext()

  tableView.bounds = priorBounds
  var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
  docURL = docURL.appendingPathComponent("myDocument.pdf")
  pdfData.write(to: docURL as URL, atomically: true)
}

0
投票
extension UITableView{

    func exportAsPdfFromTable() -> String? {
        //Render entire tableview content as UIImage and put it in UIImageView
        UIGraphicsBeginImageContextWithOptions(self.contentSize, false, 0)
        self.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)

        let interationCount: Int = Int(ceil(self.contentSize.height / self.bounds.size.height))
        for i in 0..<interationCount {
            self.setContentOffset(CGPoint(x: 0, y: Int(self.bounds.size.height) * i), animated: false)
            self.layer.render(in: UIGraphicsGetCurrentContext()!)
        }

        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        let pdfImg: UIImageView = UIImageView(image: image)
        UIGraphicsEndImageContext()

        if let pdfData = self.createPDFFromUIView(pdfImg: pdfImg){
            let data = NSMutableData(data: pdfData)
            return saveTablePdf(data: data)
        }
        return nil
    }

    //Convert UIImageView(which contains image of pdf) to pdf
    private func createPDFFromUIView(pdfImg: UIView) -> Data? {
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfImg.bounds, nil)
        UIGraphicsBeginPDFPage()
        pdfImg.layer.render(in: UIGraphicsGetCurrentContext()!)
        UIGraphicsEndPDFContext()

        return pdfData.copy() as? Data
    }

    // Save pdf file in document directory
    func saveTablePdf(data: NSMutableData) -> String {

        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let docDirectoryPath = paths[0]
        let pdfPath = docDirectoryPath.appendingPathComponent("tablePdf.pdf")
        if data.write(to: pdfPath, atomically: true) {
            return pdfPath.path
        } else {
            return ""
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.