2011-04-21 83 views

回答

0

我也知道這個問題是很老,芽我注意到它沒有得到回答。

PDF可以使用CoteText在iOS中創建。關於如何在Apple的iOS developer library中創建PDF並向其中添加一些文本,有一個相當不錯的教程。我發現本教程稍微過時了,並沒有完全回答這個問題,所以我將一些代碼放在一起,包括創建PDF,繪製文本,繪製圖像和顯示PDF。

下面的代碼將繪製一個圖像和文本的PDF。然後保存到提供的。

+(void)drawPDF:(NSString*)fileName 
{ 
    // Create the PDF context using the default page size of 612 x 792 
    UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil); 
    // Mark the beginning of a new page with a sample size 
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil); 

    [self drawTextWithString:@"Hello World" inFrame:CGRectMake(20, 20, 300, 50)]; 

    UIImage* image = [UIImage imageNamed:@"helloWorld.png"]; 
    CGRect frame = CGRectMake(30, 30, 200, 50); 

    [self drawImage:image inRect:frame]; 

    UIGraphicsEndPDFContext(); 
} 

這是繪製文本的代碼。請注意,它沒有考慮剪裁或包裝,所以如果字符串比框架大,它仍然會被繪製。

+(void)drawTextWithString:(NSString *)stringToDraw inFrame:(CGRect)frameRect { 
    UIFont *theFont = [UIFont systemFontOfSize:12]; 

    NSDictionary *attributes = @{ NSFontAttributeName: theFont}; 

    // The text will be drawin in the frameRect, where (0,0) is the top left corner 
    [stringToDraw drawInRect:frameRect withAttributes:attributes]; 
} 

這是繪製圖像的代碼。這很簡單。

+(void)drawImage:(UIImage*)image inRect:(CGRect)rect { 
    [image drawInRect:rect]; 
} 

下面的函數將使用UIWebView呈現PDF。

-(void)renderPdfFile:(NSString *)fileName 
{ 
    // This is here for demo purposes only. In a real world example the UIWebView 
    // will probably be linked directly from the story board 
    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; 

    NSURL *url = [NSURL fileURLWithPath:fileName]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [webView setScalesPageToFit:YES]; 
    [webView loadRequest:request]; 

    [self.view addSubview:webView]; 
} 

如果你有興趣在渲染PDF文件,我有另外一個帖子here,這可能是有用的。

相關問題