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:單頁顯示枢赔,滾動只影響當(dāng)前頁
singlePageContinuous :顯示全部頁面嗜逻,默認(rèn)垂直排列
twoUp: 雙頁顯示,滾動只影響當(dāng)前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相當(dāng)掛件的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]; //根據(jù)需求決定是否移除某些掛件
        }
        else if([annotation.fieldName isEqualToString:@"name"]){
            pdfName = annotation.widgetStringValue; //取出用戶添加的內(nèi)容作為文件名
        }
    }
    if (pdfName) {
        pdfName = [pdfName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
        pdfName = [NSString stringWithFormat:@"%@.pdf",pdfName];
       NSString* documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString * filePath = [NSString stringWithFormat:@"%@%@",documentDir,pdfName];
        
        // 保存并設(shè)置密碼
        [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; //設(shè)置后文件輸入框還是可以編輯不知是不是bug。
            }
        }
    }
  • 加水印

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

  document.delegate = self;
  self.pdfView.document = document; //正確
       /*
         self.pdfView.document = document;
         document.delegate = self;   錯誤 代理不會調(diào)用
       */

#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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末在旱,一起剝皮案震驚了整個濱河市摇零,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌桶蝎,老刑警劉巖遂黍,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異俊嗽,居然都是意外死亡雾家,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門绍豁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芯咧,“玉大人,你說我怎么就攤上這事竹揍【挫” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵芬位,是天一觀的道長无拗。 經(jīng)常有香客問我,道長昧碉,這世上最難降的妖魔是什么英染? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮被饿,結(jié)果婚禮上四康,老公的妹妹穿的比我還像新娘。我一直安慰自己狭握,他們只是感情好闪金,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著论颅,像睡著了一般哎垦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上恃疯,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天漏设,我揣著相機(jī)與錄音,去河邊找鬼澡谭。 笑死愿题,一個胖子當(dāng)著我的面吹牛损俭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播潘酗,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼杆兵,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了仔夺?” 一聲冷哼從身側(cè)響起琐脏,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎缸兔,沒想到半個月后日裙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡惰蜜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年昂拂,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抛猖。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡格侯,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出财著,到底是詐尸還是另有隱情联四,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布撑教,位于F島的核電站朝墩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏伟姐。R本人自食惡果不足惜收苏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望玫镐。 院中可真熱鬧倒戏,春花似錦怠噪、人聲如沸恐似。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽矫夷。三九已至,卻和暖如春憋槐,著一層夾襖步出監(jiān)牢的瞬間双藕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工阳仔, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留忧陪,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像嘶摊,于是被迫代替她去往敵國和親延蟹。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容