iOS開發之Quartz2D生成PDF Part1

2021-07-04 15:58:45 字數 2380 閱讀 8566

使用ios的quartz2d 生成pdf檔案

首先建立乙個工程,匯入coretext.framework框架。在pdfviewcontroller.h檔案中引入coretext檔案

#import
pdfviewcontroller.m檔案中建立乙個新方法:

-(void)drawtext

此方法有點長,在此分段解釋下:

在沙盒目錄下建立pdf檔案,並命名為invoice.pdf

nsstring* filename = @"invoice.pdf";

nsarray *arraypaths =

nssearchpathfordirectoriesindomains(

nsdocumentdirectory,

nsuserdomainmask,

yes);

nsstring *path = [arraypaths objectatindex:0];

下面的**塊是建立乙個已「hello,world」為內容的pdf,將string轉換為cfstringref格式

nsstring* texttodraw = @"hello world";

cfstringref stringref = (__bridge cfstringref)texttodraw;

cfattributedstringref currenttext = cfattributedstringcreate(null, stringref, null);

ctframesetterref framesetter = ctframesettercreatewithattributedstring(currenttext);

然後是建立乙個cgrect用於定義文字的大小

cgrect framerect = cgrectmake(0, 0, 300, 50);

cgmutablepathref framepath = cgpathcreatemutable();

cgpathaddrect(framepath, null, framerect);

cfrange currentrange = cfrangemake(0, 0);

ctframeref frameref = ctframesettercreateframe(framesetter, currentrange, framepath, null);

cgpathrelease(framepath);

接下來,我們建立乙個pdf上下文和標記的pdf的起始頁。 pdf的每個頁面都有開始並呼叫uigraphicsbeginpdfpagewithinfo 。

uigraphicsbeginpdfcontexttofile(pdffilename, cgrectzero, nil);

uigraphicsbeginpdfpagewithinfo(cgrectmake(0, 0, 612, 792), nil);

cgcontextref currentcontext = uigraphicsgetcurrentcontext();

由於core graphics 的座標是從左下角開始,而uikit的座標是從左上角開始,所以需做乙個變換:

cgcontextsettextmatrix(currentcontext, cgaffinetransformidentity);

cgcontexttranslatectm(currentcontext, 0, 100);

cgcontextscalectm(currentcontext, 1.0, -1.0);

我們繪製文字實際幀,釋放core graphics物件,並關閉pdf上下文至此pdf寫入到沙盒目錄下。

ctframedraw(frameref, currentcontext);

cfrelease(frameref);

cfrelease(stringref);

cfrelease(framesetter);

uigraphicsendpdfcontext();

使用uiwebview展示pdf檔案

pdfviewcontroller.m中的drawtext方法後新增下面方法:

-(void)showpdffile

viewdidload中新增

- (void)viewdidload

iOS開發 Quartz2D簡單介紹

一 什麼是quartz2d quartz 2d是 個二維繪圖引擎,同時支援ios和mac系統 quartz 2d能完成的工作 繪製圖形 線條 三角形 矩形 圓 弧等 繪製 生成 影象 讀取 生成pdf 截圖 裁剪 二 quartz2d開發中的價值 為了便於搭建美觀的uikit框架,有各種各樣的 ui...

iOS 使用Quartz 2D畫線

畫虛線需要用到函式 cgcontextsetlinedash 此函式需要四個引數 cgcontextref context uigraphicsgetcurrentcontext cgcontextbeginpath context cgcontextsetlinewidth context,2.0...

iOS開發UI篇 Quartz2D簡單使用 二

一 畫文字 畫文字 nsstring str 英國首相卡梅倫接受採訪時明確表示,中英關係處在 時代 不得不說,中英關係的 時代 一詞是由卡梅倫開創的。從中也可以看出,英方 對發展中英關係的殷切希望和美好預期。中方對英方提出的 時代 予以積極回應,表明中方對發展中英關係的高度重視和最大誠意。時代 可謂...