iOS繪圖和打印編程指導(dǎo)(五)-生成PDF內(nèi)容

UIKit提供大量函數(shù)支持使用原生代碼生成PDF內(nèi)容. 這些函數(shù)允許你創(chuàng)建一個以PDF文件或PDF數(shù)據(jù)為目標(biāo)的繪圖上下文. 然后你可以創(chuàng)建一個或多個PDF頁面, 使用的UIKit和Core Graphic技術(shù), 和繪制到屏幕一樣的步驟將PDF繪制到這些頁面. 當(dāng)你完成后, 剩下的就是PDF文件.

整個繪制PDF過程看起來很像繪制image(本系列文章四已講), 包括一些步驟:

  1. 創(chuàng)建PDF上下文, 然后將它push到Graphic堆棧
  2. 創(chuàng)建頁面(page)
  3. 使用UIKit或者Core Graphic常規(guī)方法繪制內(nèi)容到頁面
  4. 如果需要, 可以添加鏈接
  5. 重復(fù)2,3,4這三個步驟, 如果需要的話
  6. 最后將PDF context從堆棧中pop出來, 然后將結(jié)果寫入到具體的PDF文件或者保存到制定的NSMutableData對象, 這取決于context是如何創(chuàng)建的.

下面的章節(jié)就是圍繞上面的步驟具體展開的, 包括使用代碼展示如何實現(xiàn)上的步驟.

創(chuàng)建和配置PDF上下文


創(chuàng)建PDF上下文的函數(shù)有兩個, 分別是UIGraphicsBeginPDFContextToDataUIGraphicsBeginPDFContextToFile. 這兩個函數(shù)將不同PDF數(shù)據(jù)輸出地和圖形上下文綁定, UIGraphicsBeginPDFContextToData函數(shù)式將數(shù)據(jù)輸出到NSMutableData對象, 而UIGraphicsBeginPDFContextToFile函數(shù)是將內(nèi)容輸出到PDF文件(APP的home路徑下)

PDF文件是以頁結(jié)構(gòu)來管理內(nèi)容的. 所以在繪制時有兩個限制如下:

  • 在將內(nèi)容繪制到page之前, 你需要open該page
  • 你必須設(shè)置page的大小.

在創(chuàng)建PDF繪圖上下文時, 那兩個函數(shù)會默認(rèn)指定page的大小, 但不會自動打開page. 創(chuàng)建上下文后, 必須使用UIGraphicsBeginPDFPageUIGraphicsBeginPDFPageWithInfo函數(shù)顯式打開新page. 每次創(chuàng)建新page時, 必須再次調(diào)用這些函數(shù)中的一個來標(biāo)記新page的開始. UIGraphicsBeginPDFPage函數(shù)使用默認(rèn)大小創(chuàng)建一個page, UIGraphicsBeginPDFPageWithInfo函數(shù)允許你自定義page大小和其他屬性.

完成繪制后, 通過調(diào)用UIGraphicsBeginPDFPage函數(shù)來關(guān)閉PDF上下文. 同時還會關(guān)閉最后一頁, 并將PDF內(nèi)容寫入到創(chuàng)建上下文時指定的文件或者數(shù)據(jù)對象中. 此函數(shù)還從上下文堆棧中移除PDF上下文.

代碼5-1展示了應(yīng)用程序在textView中獲取文本然后循環(huán)寫入PDF文件中. 除了配置和管理PDF上下文的函數(shù)調(diào)用之外, 大多數(shù)代碼都與繪制所需的內(nèi)容有關(guān). textView是一個成員變量保存包含所文本的text view對象. 該應(yīng)用程序使用Core Text框架(更具體的說是CTFramesetterRef數(shù)據(jù)類型)來處理連續(xù)頁面上的文本布局和頁面管理. 自定義方法renderPageWithTextRange:andFramesetter:drawPageNumber:方的實現(xiàn)如代碼5-2所示

代碼清單4-1 創(chuàng)建一個新的PDF文件

- (IBAction)savePDFFile:(id)sender {
    // Prepare the text using a Core Text Framesetter.
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (CFStringRef)textView.text, NULL);
    if (currentText) {
        CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
        if (framesetter) {
 
            NSString *pdfFileName = [self getPDFFileName];
            // Create the PDF context using the default page size of 612 x 792.
            UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
 
            CFRange currentRange = CFRangeMake(0, 0);
            NSInteger currentPage = 0;
            BOOL done = NO;
 
            do {
                // Mark the beginning of a new page.
                UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
 
                // Draw a page number at the bottom of each page.
                currentPage++;
                [self drawPageNumber:currentPage];
 
                // Render the current page and update the current range to
                // point to the beginning of the next page.
                currentRange = [self renderPageWithTextRange:currentRange andFramesetter:framesetter];
 
                // If we're at the end of the text, exit the loop.
                if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)currentText))
                    done = YES;
            } while (!done);
 
            // Close the PDF context and write the contents out.
            UIGraphicsEndPDFContext();
 
            // Release the framewetter.
            CFRelease(framesetter);
 
        } else {
            NSLog(@"Could not create the framesetter needed to lay out the atrributed string.");
        }
        // Release the attributed string.
        CFRelease(currentText);
    } else {
            NSLog(@"Could not create the attributed string for the framesetter");
    }
}

繪制PDF頁面


所有的PDF內(nèi)容繪制需要在page中完成. 每個PDF文檔至少有一個page, 但是多數(shù)是多個page. 你通過調(diào)用UIGraphicsBeginPDFPageUIGraphicsBeginPDFPageWithInfo函數(shù)來指定新的page. 這些函數(shù)關(guān)閉前一個page(如果它打開的話), 然后創(chuàng)建一個新的page, 并為繪圖做好準(zhǔn)備.

創(chuàng)建page之后, PDF繪圖上下文將捕獲所有繪圖命令, 并將其轉(zhuǎn)換為PDF命令. 你可以在頁面中繪制任何你想要的東西, 包括文本, 矢量形狀和圖像, 就像在APP中的自定義view中一樣. 你發(fā)出的繪圖命令會被PDF上下文捕獲并翻譯成PDF數(shù)據(jù). 在頁面上放置內(nèi)容完全取決于你, 但必須在page中size范圍內(nèi)進(jìn)行.

代碼5-2展示了在PDF頁中繪制內(nèi)容的兩種自定義方法. renderPageWithTextRange:andFramesetter:方法使用Core Text創(chuàng)建一個適合頁面的文本框架, 然后在該框架中布局一些文本. 在布局文本之后, 它返回一個更新的range, 該range反映了當(dāng)前頁面的結(jié)束和下一頁的開始. drawPageNumber:方法使用NSString的繪制功能在PDF的每頁底部繪制一個頁碼字符串.

注意:此代碼片段使用了Core Text框架, 你需要手動添加該框架到你的項目中

代碼清單5-2 繪制PDF頁面內(nèi)容

// Use Core Text to draw the text in a frame on the page.
- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange
                 andFramesetter:(CTFramesetterRef)framesetter {
   // Get the graphics context.
   CGContextRef    currentContext = UIGraphicsGetCurrentContext();
 
   // Put the text matrix into a known state. This ensures
   // that no old scaling factors are left in place.
   CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
 
   // Create a path object to enclose the text. Use 72 point
   // margins all around the text.
   CGRect    frameRect = CGRectMake(72, 72, 468, 648);
   CGMutablePathRef framePath = CGPathCreateMutable();
   CGPathAddRect(framePath, NULL, frameRect);
 
   // Get the frame that will do the rendering.
   // The currentRange variable specifies only the starting point. The framesetter
   // lays out as much text as will fit into the frame.
   CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
   CGPathRelease(framePath);
 
   // Core Text draws from the bottom-left corner up, so flip
   // the current transform prior to drawing.
   CGContextTranslateCTM(currentContext, 0, 792);
   CGContextScaleCTM(currentContext, 1.0, -1.0);
 
   // Draw the frame.
   CTFrameDraw(frameRef, currentContext);
 
   // Update the current range based on what was drawn.
   currentRange = CTFrameGetVisibleStringRange(frameRef);
   currentRange.location += currentRange.length;
   currentRange.length = 0;
   CFRelease(frameRef);
 
   return currentRange;
}
 
- (void)drawPageNumber:(NSInteger)pageNum {
   NSString *pageString = [NSString stringWithFormat:@"Page %d", pageNum];
   UIFont *theFont = [UIFont systemFontOfSize:12];
   CGSize maxSize = CGSizeMake(612, 72);
 
   CGSize pageStringSize = [pageString sizeWithFont:theFont
                                       constrainedToSize:maxSize
                                       lineBreakMode:UILineBreakModeClip];
   CGRect stringRect = CGRectMake(((612.0 - pageStringSize.width) / 2.0),
                                  720.0 + ((72.0 - pageStringSize.height) / 2.0),
                                  pageStringSize.width,
                                  pageStringSize.height);
 
   [pageString drawInRect:stringRect withFont:theFont];
}

創(chuàng)建PDF內(nèi)容鏈接


除了繪制PDF內(nèi)容外, 可以在內(nèi)容中加入鏈接(將用戶帶到同一PDF文檔中其他位置或者外部URL鏈接). 創(chuàng)建單個鏈接, 必須向PDF文檔頁面添加鏈接的源矩形區(qū)域和鏈接的目的地. 鏈接目的地的屬性之一是作為該鏈接的唯一表示符(字符串). 要創(chuàng)建到特定目的地的鏈接, 需要在創(chuàng)建源矩形區(qū)域時, 指定鏈接目的地的標(biāo)識符.

若要向PDF內(nèi)容添加新的鏈接目的地, 請使用UIGraphicsAddPDFContextDestinationAtPoint函數(shù). 這個函數(shù)將一個命名(唯一標(biāo)識符)好的目的地和當(dāng)前page中的具體點(diǎn)關(guān)聯(lián)起來. 當(dāng)希望鏈接到該目的地時, 可以使用UIGraphicsSetPDFContextDestinationForRect函數(shù)將鏈接目的地和鏈接原矩形區(qū)域關(guān)聯(lián)起來. 圖5-1顯示了上面兩個函數(shù)的關(guān)系. 當(dāng)用戶點(diǎn)擊"see Chapter 1"文本時, PDF會跳到目的地-"第一章", 該目的點(diǎn)位于第一章的頂部

圖5-1 創(chuàng)建一個鏈接目的地并跳轉(zhuǎn)到點(diǎn)

另外, 如果要在PDF中創(chuàng)建指向外部URL的鏈接時, 可以使用UIGraphicsSetPDFContextURLForRect函數(shù)來設(shè)置.

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容