iOS11 PDFKit

  • 創(chuàng)建Document

PDFDocument就等同 PDF文件,需要借助PDFView顯示出來

- (void)createDocument {
    NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"Sample.pdf" ofType:nil];
    NSURL * url = [NSURL fileURLWithPath:pdfPath];
    PDFDocument *document =[ [PDFDocument alloc] initWithURL:url];
    if (document) {
        self.pdfView.document = document;
        self.pdfView.autoScales = YES;
        self.pdfView.backgroundColor = [UIColor lightGrayColor];
    }
}
  • 修改PDF的顯示模式

顯示模式有4種
singlePage:單頁顯示,滾動只影響當前頁
singlePageContinuous :顯示全部頁面,默認垂直排列
twoUp: 雙頁顯示,滾動只影響當前2頁
twoUpContinuous: 顯示所有頁,雙頁顯示
滾動方向:水平和垂直

 self.pdfView.displayMode = kPDFDisplayTwoUpContinuous;
self.pdfView.displayDirection = kPDFDisplayDirectionVertical;
  • 取出某頁的縮略圖

PDF的每一頁由PDFPage類管理

- (void)createThumbnails {
    PDFPage *page =  [self.document pageAtIndex:0];
    CGSize size = CGSizeMake(300, 300);
    UIImage *image = [page thumbnailOfSize:size forBox:kPDFDisplayBoxCropBox];
    UIImageView * imageview = [[UIImageView alloc] initWithImage:image];
    imageview.frame = CGRectMake(10, 200, 300, 300);
    [self.view addSubview:imageview];
}

  • 添加掛件Annotation

可以添加文本,checkBox,選擇框等等到PDFPage,其掛件的frame要基于Page的大小確定。
fieldName用于給掛件分組。清空事件可以用到
buttonWidgetStateString相當掛件的ID,用來區(qū)分是否多選或單選

/**
 創(chuàng)建文本輸入框

 @param bounds <#bounds description#>
 @param fieldName <#fieldName description#>
 @return <#return value description#>
 */
- (PDFAnnotation *)textWidgetWithBounds:(CGRect)bounds filedName:(NSString *)fieldName {
    PDFAnnotation *textWidget = [[PDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationSubtypeText withProperties:nil];
    textWidget.fieldName = fieldName;
    textWidget.font = [UIFont systemFontOfSize:18];
    return textWidget;
}

 textWidget.maximumLength = 10; //限制文本長度
 textWidget.hasComb = YES; //等分間距


/**
 創(chuàng)建選擇按鈕

 @param fieldName <#fieldName description#>
 @param state <#state description#>
 @param bounds <#bounds description#>
 @return <#return value description#>
 */
- (PDFAnnotation *)radiobuttonWithFieldName:(NSString *)fieldName state:(NSString *)state bounds:(CGRect)bounds {
    PDFAnnotation * button = [[PDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationWidgetSubtypeButton withProperties:nil];
    button.widgetFieldType = PDFAnnotationWidgetSubtypeButton;
    button.widgetControlType = kPDFWidgetRadioButtonControl;
    button.buttonWidgetStateString = state;
    return button;
}
  • 自定義事件 (清除填寫記錄)

創(chuàng)建一個掛件類型為 kPDFWidgetPushButtonControl 的按鈕,PDFActionResetForm類配置清除屬性。clearButton.action = resetFormAction;最后賦值給按鈕

- (void)clearAction {
    CGRect clearButtonBounds = CGRectMake(0, 0, 1, 1);
    PDFAnnotation *clearButton = [[PDFAnnotation alloc] initWithBounds:clearButtonBounds forType:PDFAnnotationSubtypeWidget withProperties:nil];
    clearButton.widgetFieldType = PDFAnnotationWidgetSubtypeButton;
    clearButton.widgetControlType = kPDFWidgetPushButtonControl;
    clearButton.caption = @"Clear";
    clearButton.fieldName =  @"Clear";
    
    PDFPage *page = [self.document pageAtIndex:0];
    
    [page addAnnotation:clearButton];
    
    PDFActionResetForm *resetFormAction = [[PDFActionResetForm alloc] init];
    resetFormAction.fields = @[@"A",@"B",@"C"];
    resetFormAction.fieldsIncludedAreCleared = NO; //FieldName為 @[@"A",@"B",@"C"] 的掛件,不清楚記錄
    clearButton.action = resetFormAction;
}
  • 保存 PDF
- (void)saveDocument {
    PDFPage *page = [self.document pageAtIndex:0];
    if (page == nil) {
        return;
    }
    
    NSString *pdfName = nil;
    for (PDFAnnotation *annotation in page.annotations) {
        if ([annotation.fieldName isEqualToString:@"xxx"]) {
            [page removeAnnotation:annotation]; //根據需求決定是否移除某些掛件
        }
        else if([annotation.fieldName isEqualToString:@"name"]){
            pdfName = annotation.widgetStringValue; //取出用戶添加的內容作為文件名
        }
    }
    if (pdfName) {
        pdfName = [pdfName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
        pdfName = [NSString stringWithFormat:@"%@.pdf",pdfName];
       NSString* documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString * filePath = [NSString stringWithFormat:@"%@%@",documentDir,pdfName];
        
        // 保存并設置密碼
        [self.document writeToURL:[NSURL URLWithString:filePath] withOptions:@{PDFDocumentOwnerPasswordOption:@"mima"}];
    }
}
  • PDF只讀
    PDFPage *page = [self.document pageAtIndex:0];
    if (page) {
        if (self.document.isEncrypted || self.document.isLocked) {
            for (PDFAnnotation *anntation in page.annotations) {
                anntation.readOnly = YES; //設置后文件輸入框還是可以編輯不知是不是bug。
            }
        }
    }
  • 加水印

1.成為PDFDocument代理 有坑,必須設置代理之后再將document賦值給PDFView,否則不會調用
2.實現代理 - (Class)classForPage
3.實現自定類PDFPage,實現- (void)drawWithBox:(PDFDisplayBox)box toContext:(CGContextRef)context 方法

  document.delegate = self;
  self.pdfView.document = document; //正確
       /*
         self.pdfView.document = document;
         document.delegate = self;   錯誤 代理不會調用
       */

#pragma  mark - PDFDocumentDelegate

- (Class)classForPage {
    
    return WaterMark.class;
}

@implementation WaterMark
- (void)drawWithBox:(PDFDisplayBox)box toContext:(CGContextRef)context {
    [super drawWithBox:box toContext:context];
    UIGraphicsPushContext(context);
    CGContextSaveGState(context);

    CGRect pageBounds = [self boundsForBox:box];
    CGContextTranslateCTM(context, 0, pageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, M_PI_4);
    
    NSString *str = @"水印 水印 水印";
    NSDictionary  *attributes = @{
                      NSForegroundColorAttributeName: [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5],
                      NSFontAttributeName: [UIFont systemFontOfSize:64]
                      };
    
    [str drawAtPoint:CGPointMake(250, 40) withAttributes:attributes];
    
    CGContextRestoreGState(context);
    UIGraphicsPopContext();

}
@end

圖片.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容