使用长文本在Swift中创建PDF

时间:2015-07-27 17:38:55

标签: ios swift pdf

我的应用是日记,我希望允许用户将应用内容导出为PDF,但我不知道如何将长文本分成多个页面。

创建页面(包含图像,文本等)我已经创建了一个XIB文件作为模板;例如,PDF中的文本是从模板中包含的UITextView生成的。

以下是从UITextView生成文本的代码:

func drawTextFromTextView(textview: UITextView) {


    var frame: CGRect = textview.frame
    frame.size.height = textview.contentSize.height
    textview.frame = frame
    textview.sizeToFit()

    if textview.text?.isEmpty == false {

        let theFont = textview.font
        let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = textview.textAlignment
        paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping

        let theAttributedFont: [NSObject : AnyObject] = [NSFontAttributeName: theFont!, NSParagraphStyleAttributeName: paragraphStyle]

        let theText = textview.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) as NSString
        let theFrame = CGRectMake(textview.frame.origin.x, textview.frame.origin.y, textview.frame.size.width, textview.frame.size.height)

        theText.drawInRect(theFrame, withAttributes: theAttributedFont)

    }

}

PDFpage 是链接到XIB文件的模板UIView。 在 parseSubviews 中,我从PDF页面的子视图(UILabels,UIImageView,UITextView等)生成PDF中的文本和图像。

func parseViewsToRender(viewsToRender: [PDFpage]) {

    for aView in viewsToRender /*as! [UIView]*/ {

        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil)

        parseSubviews(aView)

    }

}

func create(viewsToRender: [PDFpage], filename: String) -> NSURL {

    // Create filename

    //let tempDir     = NSTemporaryDirectory()
    //let pdfFilename = tempDir.stringByAppendingPathComponent(filename)
    let pdfFilename = filename

    UIGraphicsBeginPDFContextToFile(pdfFilename, CGRectZero, nil)

    // begin to render the views in this context

    parseViewsToRender(viewsToRender)

    UIGraphicsEndPDFContext()

    return NSURL(fileURLWithPath: pdfFilename)!

}

0 个答案:

没有答案