首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 將 UITextView 內容導出為 PDF 文件並保存本地

     編輯:程式設計綜合問答

核心思路

利用 UIKit 的 UIGraphicsBeginPDFContextToFile 開啟 PDF 上下文,逐頁繪製 UITextView 的內容,最後關閉上下文。

完整實現代碼

- (void)exportTextViewToPDF:(UITextView *)textView filePath:(NSString *)path {
    // 1. 創建 PDF 上下文
    UIGraphicsBeginPDFContextToFile(path, CGRectZero, nil);
    
    // 2. 計算分頁
    CGSize pageSize = CGSizeMake(595.2, 841.8); // A4 尺寸 (points)
    CGFloat margin = 40;
    CGRect textRect = CGRectMake(margin, margin, pageSize.width - 2*margin, pageSize.height - 2*margin);
    
    NSAttributedString *attrText = textView.attributedText;
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attrText);
    CFRange range = CFRangeMake(0, attrText.length);
    BOOL done = NO;
    
    while (!done) {
        // 3. 開始新頁
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(ctx, 0, pageSize.height);
        CGContextScaleCTM(ctx, 1.0, -1.0); // 翻轉坐標系
        
        // 4. 繪製當前頁內容
        CGMutablePathRef pathRef = CGPathCreateMutable();
        CGPathAddRect(pathRef, NULL, textRect);
        CTFrameRef frame = CTFramesetterCreateFrame(framesetter, range, pathRef, NULL);
        CTFrameDraw(frame, ctx);
        
        // 5. 更新範圍
        CFIndex visibleRange = CTFrameGetVisibleStringRange(frame).length;
        range.location += visibleRange;
        range.length -= visibleRange;
        if (range.length <= 0) done = YES;
        
        CFRelease(frame);
        CFRelease(pathRef);
    }
    CFRelease(framesetter);
    
    // 6. 結束
    UIGraphicsEndPDFContext();
}

調用示例

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths firstObject];
NSString *pdfPath = [docDir stringByAppendingPathComponent:@"export.pdf"];
[self exportTextViewToPDF:self.myTextView filePath:pdfPath];

依賴框架

需引入 CoreText.framework 並 #import <CoreText/CoreText.h>。

替代方案

  • 使用 UIPrintPageRenderer + UIPrintInteractionController 生成 PDF(iOS 10+ 更簡單)。
  • 第三方庫 PDFKit (iOS 11+) 或 PSPDFKit。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved