iOS开发之Quartz2D生成PDF-Part2
在上一节当中,我们创建了一个基于Quartz2D的PDF,并在PDF中添加一线条。
在这一节,主要是添加一个logo,和绘制一个table。
添加logo
下载图片资源,然后添加到工程当中。
在`PDFRenderer.m`文件中添加下面方法:
//绘制图像
+ (void)drawImage:(UIImage*)image inRect:(CGRect)rect {
[image drawInRect:rect];
}
在PDFRenderer.h
中添加下面方法:
+ (void)drawImage:(UIImage*)image inRect:(CGRect)rect;
为了能在PDF上显示此logo,在PDFRenderer.m
的drawPDF
方法中添加下面代码,此代码写在UIGraphicsEndPDFContext();
之前:
UIImage *logo = [UIImage imageNamed:@"ray-logo"];
CGRect frame = CGRectMake(20, 100, 300, 60);
[PDFRenderer drawImage:logo inRect:frame];
在上面的代码中,创建一个UIImage对象,并定义图像的位置和大小,调用drawImage
方法将两个参数传过去进行绘制。
完整代码如下:
+ (void)drawPDF:(NSString*)fileName {
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
CGPoint from = CGPointMake(0, 0);
CGPoint to = CGPointMake(200, 300);
[PDFRenderer drawLineFromPoint:from toPoint:to];
UIImage *logo = [UIImage imageNamed:@"ray-logo"];
CGRect frame = CGRectMake(20, 100, 300, 60);
[PDFRenderer drawImage:logo inRect:frame];
[self drawText];
UIGraphicsEndPDFContext();
}
至此了解到如何绘制清单的基本元素:文本、线条、图片。接下来将运用这些所有元素构建更为完美的布局。
绘制Labels
创建一个xib,并命名为InvoiceView
,选中InvoiceView
IB,设置View的width: 612 和height: 792,这些都是A4PDF的默认尺寸。下面拖拽8个UILabel,并按如下命名:
- Recipient [Name]
- Recipient’s Address
- Recipient’s City
- Recipient’s Postal Code
- Invoicer [Name]
- Invoicer’s Address
- Invoicer’s City
- Invoicer’s Postal Code
这些labels的位置将会在PDF上进行布局。给每个label从0-7设置tag。例如:Recipient
的tag是0,Recipient’s Address
的tag事1,以此类推。
打开PDFRenderer.m
文件,并重构drawText
方法。代码清单如下:
+(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect {
CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
CFRange currentRange = CFRangeMake(0, 0