Swift中的函数将Pdf文件附加到另一个Pdf

时间:2016-05-10 08:26:48

标签: swift pdf

我使用以下代码在两个不同的视图中创建了两个不同的pdf文件:

private func toPDF(views: [UIView]) -> NSData? {

    if views.isEmpty {return nil}

    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, CGRect(x: 0, y: 0, width: 1024, height: 1448), nil)
    let context = UIGraphicsGetCurrentContext()

    for view in views {
        UIGraphicsBeginPDFPage()
        view.layer.renderInContext(context!)
    }

    UIGraphicsEndPDFContext()

    return pdfData
}

在最终视图中,我使用以下方法调用两个文件:

let firstPDF = NSUserDefaults.standardUserDefaults().dataForKey("PDFone")
let secondPDF = NSUserDefaults.standardUserDefaults().dataForKey("PDFtwo")

我的问题是:有人可以建议将第二个文件附加到第一个文件的函数吗? (两者都是NSData格式)

3 个答案:

答案 0 :(得分:4)

快捷键4:

func merge(pdfs:Data...) -> Data
{
    let out = NSMutableData()
    UIGraphicsBeginPDFContextToData(out, .zero, nil)

    guard let context = UIGraphicsGetCurrentContext() else {
        return out as Data
    }

    for pdf in pdfs {
        guard let dataProvider = CGDataProvider(data: pdf as CFData), let document = CGPDFDocument(dataProvider) else { continue }

        for pageNumber in 1...document.numberOfPages {
            guard let page = document.page(at: pageNumber) else { continue }
            var mediaBox = page.getBoxRect(.mediaBox)
            context.beginPage(mediaBox: &mediaBox)
            context.drawPDFPage(page)
            context.endPage()
        }
    }

    context.closePDF()
    UIGraphicsEndPDFContext()

    return out as Data
}

答案 1 :(得分:1)

使用PDFKit及其PDFDocument可以很容易地做到这一点。

我正在使用此扩展程序:

    import PDFKit
    
    extension PDFDocument {
    
        func addPages(from document: PDFDocument) {
            let pageCountAddition = document.pageCount
    
            for pageIndex in 0..<pageCountAddition {
                guard let addPage = document.page(at: pageIndex) else {
                    break
                }
    
                self.insert(addPage, at: self.pageCount) // unfortunately this is very very confusing. The index is the page *after* the insertion. Every normal programmer would assume insert at self.pageCount-1
            }
        }
    
    }

答案 2 :(得分:0)

快捷键5:

像这样合并pdf以保留链接等...

See answer here