创建tableview的pdf所有数据

时间:2016-11-17 05:40:36

标签: ios swift uitableview pdf

我创建了tablef所有单元格的pdf。但是我创建了pdf,它没有显示tableview&的所有数据。当pdf页面高度根据单元格数据设置时。我不知道如何解决这个问题。我正在使用此代码创建pdf.please帮助我。

window.onload=function(){

var auto = setTimeout(function(){ autoRefresh(); }, 100);

function submitform(){

  document.forms["myForm"].submit();
}

function autoRefresh(){
    clearTimeout(auto);
    auto = setTimeout(function(){ submitform(); autoRefresh(); }, 3000);

    }

}


 </script>


   <h2 class="form-signin-heading">Schedule Management</h2><hr />
    <button class="btn btn-info" type="button" id="btn-add"> <span class="glyphicon glyphicon-pencil"></span> &nbsp; Add Schedule</button>
    <button class="btn btn-info" type="button" id="btn-view"> <span class="glyphicon glyphicon-eye-open"></span> &nbsp; View Schedule</button>
    <hr />
    <?php

 (isset($_POST["months"])) ? $dropDownVal = $_POST["months"] : $dropDownVal= date("n");

    ?>
    <div class="content-loader">
           <form method="post" action="index.php" id="myForm" name="myForm" > 
    Select a month <select name="months"  id="months" onchange='if(this.value != 0) { this.form.submit(); }'>
    <option value="0" <?php if ($dropDownVal==0) echo 'selected'; ?>>--------------</option>
    <option value="1" <?php if ($dropDownVal==1) echo 'selected'; ?>>January</option>
    <option value="2" <?php if ($dropDownVal==2) echo 'selected'; ?>>February</option>
    <option value="3" <?php if ($dropDownVal==3) echo 'selected'; ?>>March</option>
    <option value="4" <?php if ($dropDownVal==4) echo 'selected'; ?>>April</option>
    <option value="5" <?php if ($dropDownVal==5) echo 'selected'; ?>>May</option>
    <option value="6" <?php if ($dropDownVal==6) echo 'selected'; ?>>June</option>
    <option value="7" <?php if ($dropDownVal==7) echo 'selected'; ?>>July</option>
    <option value="8" <?php if ($dropDownVal==8) echo 'selected'; ?>>August</option>
    <option value="9" <?php if ($dropDownVal==9) echo 'selected'; ?>>September</option>
    <option value="10"<?php if ($dropDownVal==10) echo 'selected'; ?>>October</option>
    <option value="11"<?php if ($dropDownVal==11) echo 'selected';?>>November</option>
    <option value="12"<?php if ($dropDownVal==12) echo 'selected';?>>December</option>
    </select>

    <noscript><input type="submit" value="Submit"></noscript>

5 个答案:

答案 0 :(得分:3)

试试这个。

func createPdfFromTableView()
{
    let priorBounds: CGRect = self.tblView.bounds
    let fittedSize: CGSize = self.tblView.sizeThatFits(CGSize(width: priorBounds.size.width, height: self.tblView.contentSize.height))
    self.tblView.bounds = CGRect(x: 0, y: 0, width: fittedSize.width, height: fittedSize.height)
    self.tblView.reloadData()
    let pdfPageBounds: CGRect = CGRect(x: 0, y: 0, width: fittedSize.width, height: (fittedSize.height))
    let pdfData: NSMutableData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
    UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
    self.tblView.layer.render(in: UIGraphicsGetCurrentContext()!)
    UIGraphicsEndPDFContext()
    let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    let documentsFileName = documentDirectories! + "/" + "pdfName"
    pdfData.write(toFile: documentsFileName, atomically: true)
    print(documentsFileName)
}

答案 1 :(得分:0)

下面对Rajeskumar的答案的一个补充如下:

如果您的UITableView没有占用整个设备屏幕及其原始边界,您可能需要插入以下行:

self.tblview.bounds = priorBounds

渲染(在:)步骤后。否则,该表将以一种覆盖更多原始空间的方式在设备上绘制。

答案 2 :(得分:0)

在表格视图底部滚动后,以上答案均不适用于创建PDF。 滚动后重新加载tableview(reloadData())时,未生成正确的PDF并将其删除,因此不会为卸载的项目生成PDF。 因此,我添加了额外条件并进行了如下重构:

extension UITableView {
    func convertToPDF() -> Data? {
        let priorBounds = self.bounds
        setBoundsForAllItems()
        self.layoutIfNeeded()
        let pdfData = createPDF()
        self.bounds = priorBounds
        return pdfData.copy() as? Data
    }

    private func getContentFrame() -> CGRect {
        return CGRect(x: 0, y: 0, width: self.contentSize.width, height: self.contentSize.height)
    }

    private func createPDF() -> NSMutableData {
        let pdfPageBounds: CGRect = getContentFrame()
        let pdfData: NSMutableData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
        UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        UIGraphicsEndPDFContext()
        return pdfData
    }

    private func setBoundsForAllItems() {
        if self.isEndOfTheScroll() {
            self.bounds = getContentFrame()
        } else {
            self.bounds = getContentFrame()
            self.reloadData()
        }
    }

    private func isEndOfTheScroll() -> Bool  {
        let contentYoffset = contentOffset.y
        let distanceFromBottom = contentSize.height - contentYoffset
        return distanceFromBottom < frame.size.height
    }
}

答案 3 :(得分:0)

使用这种方式创建tableview的PDF

   @IBAction func onClickBtnGeneratePDF(_ sender: Any) {
    if enterPDFNAME.text?.isEmpty() == true{
     Utility.showToast(message: "Please Enter PDF name")
    }else{
        self.viewOverlaySavePDF.isHidden = true
        Utility.showLoading()
        let pdfFilePath = tableview.exportAsPdfFromTable(pdfName: enterPDFNAME.text!)
        if pdfFilePath != nil {

            self.enterPDFNAME.text = ""
            Utility.showToast(message: "Your PDF file saved")
            Utility.hideLoading()
        }
        print(pdfFilePath)
    }
}

}

扩展UITableView {

// Export pdf from UITableView and save pdf in drectory and return pdf file path
func exportAsPdfFromTable(pdfName:String) -> String {

  /*  let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    // 2. Assign print formatter to UIPrintPageRenderer

    let render = UIPrintPageRenderer()
    render.addPrintFormatter(fmt, startingAtPageAt: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
    let printable = page.insetBy(dx: 0, dy: 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, .zero, nil)

    for i in 1...render.numberOfPages {
        UIGraphicsBeginPDFPage();
        let bounds = UIGraphicsGetPDFContextBounds()
        render.drawPage(at: i - 1, in: bounds)
    }

    UIGraphicsEndPDFContext();
    */
    let originalBounds = self.bounds
    self.bounds = CGRect(x:originalBounds.origin.x, y: originalBounds.origin.y, width: self.contentSize.width, height: self.contentSize.height)
    let pdfPageFrame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.contentSize.height)

    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
    UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
    guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
    self.layer.render(in: pdfContext)
    UIGraphicsEndPDFContext()
    self.bounds = originalBounds
    // Save pdf data
    return self.saveTablePdf(data: pdfData,name:pdfName)

}

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

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let docDirectoryPath = paths[0]
    let pdfPath = docDirectoryPath.appendingPathComponent("\(name).pdf")
    if data.write(to: pdfPath, atomically: true) {
        return pdfPath.path
    } else {
        return ""
    }
}

我希望它会有所帮助 按照instagram:styoloholic_007,gunatitsolutions

答案 4 :(得分:-1)

导出所有 tableView 项目的唯一解决方案:将 tableview 的每个部分制作为图像的快照 -> 将它们合并到一个 imageView -> 将 imageView 渲染为 pdf

注意:UIScrollView 和 UICollectionView 也是一样的

func exportPDF() {
    // 1. estimate tableview contentsize
    UIGraphicsBeginImageContextWithOptions(tableView.contentSize, false, 0)
    tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
    tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
    
    // 2. calculate number of part of tableview, loop and get snapshot
    let iterationCount = Int(ceil(tableView.contentSize.height / tableView.bounds.size.height))
    for i in 0..<iterationCount {
        tableView.setContentOffset(CGPoint(x: 0, y: Int(tableView.bounds.size.height) * i), animated: false)
        tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
    }
    
    // 3. merge and make UIImageView from snapshot
    let image = UIGraphicsGetImageFromCurrentImageContext()
    let pdfImageView = UIImageView(image: image)
    
    //4. render imageView to PDF
    let pdfData: NSMutableData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, pdfImageView.bounds, nil)
    UIGraphicsBeginPDFPageWithInfo(pdfImageView.bounds, nil)
    pdfImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    UIGraphicsEndPDFContext()
    let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    let documentsFileName = documentDirectories! + "/" + "MyPDF.pdf"
    pdfData.write(toFile: documentsFileName, atomically: true)
    
    // 5. We have pdf file at documentsFileName
}