1. 程式人生 > 其它 >【iOS】儲存PDF檔案和列印功能

【iOS】儲存PDF檔案和列印功能

技術標籤:ios技術點ios資料儲存讀取

新的需求又來了,這次的需求是使用者可以在App中列印當前頁面,也可以將當前頁面儲存成pdf檔案,以便日後列印。

首先解決一下儲存檔案的問題,使用者需要在檔案管理中能檢視pdf檔案。iOS允許暴露給使用者的只有Documents目錄,暴露Documents目錄只需要在info裡新增兩個欄位
Application requires iPhone environment
Supports opening documents in place
暴露documents的key

ok,執行一下已經能在檔案管理中看見documents的檔案了。接下來處理儲存成pdf的功能。

	//儲存view
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(pdfData, [[[viewArray firstObject] layer] bounds], nil);
    //迴圈
    for (UIView *view in viewArray) {
        UIGraphicsBeginPDFPage();
        CGContextRef pdfContext = UIGraphicsGetCurrentContext();
        [[view layer] renderInContext:pdfContext];
    }
    UIGraphicsEndPDFContext();
    
    NSString *path = [ZYFileManager getDocumentFilePathWithName:@"xx.pdf"];
    BOOL isComplete = [ZYFileManager saveDataForPath:path withData:pdfData];
    if (show) {
        if (isComplete) {
            [ZYSVProgressHUD showSuccessWithStatus: @"儲存PDF成功,請前往檔案管理檢視"];
        }else{
            [ZYSVProgressHUD showErrorWithStatus: @"儲存PDF失敗,請檢查是否有足夠空間"];
        }
    }

如果只儲存一頁pdf的話就不需要迴圈部分,直接去掉外層的forin。我這裡是不確定pdf會有幾頁,所以將需要儲存的view新增進陣列,迴圈陣列來新增page。

這裡有個問題,最開始UIGraphicsBeginPDFContextToData這裡我用的是view.bounds,儲存成pdf之後是正常的,但是在列印時會縮到1/2大小。研究了一下發現是ui給的設計圖中這個view的尺寸只有a4紙標準尺寸(21.0 / 2.54 * 72, 29.7 / 2.54 * 72)的一半。可view擴大之後頁面顯示就有問題。最後想了個笨辦法,view建立的時候按照a4的尺寸建立,然後按比例縮小到顯示的大小。所以在儲存pdf的時候我用了view.layer.bounds來繪製,這樣列印的時候a4是正好的大小。

最後就是列印。列印可以列印文字,照片,pdf檔案等等,列印資訊也可以選擇文字,nsdata等等。我這裡需求就是列印pdf檔案,所以寫的比較簡單。思路就是先把要列印的view儲存成pdf,然後獲取pdf檔案進行列印,列印結束後再刪除pdf檔案。

	//先儲存pdf,列印結束之後再刪除pdf檔案
    [self SX_XT_PrintViewPDFButtonClickHandleWithSource:viewArray isShow:show];
    //獲取到剛剛的地址
    NSString *path = [ZYFileManager getDocumentFilePathWithName:@"xx.pdf"];
    //通過地址取檔案
    NSData *pdfData = [NSData dataWithContentsOfFile:path];
    //建立列印物件
    UIPrintInteractionController *printer = [UIPrintInteractionController sharedPrintController];
    printer.delegate = self;
    //配置列印資訊
    UIPrintInfo *Pinfo = [UIPrintInfo printInfo];
    Pinfo.outputType = UIPrintInfoOutputPhoto;//可列印文字、圖形、影象
    Pinfo.jobName = @"xx";//可選屬性,用於在列印中心中標識列印作業
    Pinfo.duplex = UIPrintInfoDuplexNone;//NONE為禁止雙面
    Pinfo.orientation = UIPrintInfoOrientationPortrait;//列印縱向還是橫向
    printer.printInfo = Pinfo;
    
    printer.printingItem = pdfData;
    [printer presentAnimated:YES completionHandler:^(UIPrintInteractionController * _Nonnull printInteractionController, BOOL completed, NSError * _Nullable error) {
        if (!completed && error) {
            [ZYSVProgressHUD showErrorWithStatus:@"列印失敗"];
            NSLog(@"Error");
        }
    }];

最後在列印成功的協議方法裡刪掉pdf檔案就ok了。

PS:列印測試我用的是蘋果官方的印表機模擬器,附一個模擬器網盤備份。
https://pan.baidu.com/s/1CXbpSIbTjNsoipPPYAj5sQ 提取碼: wcmx