我想在iOS 6应用程序中生成一个好看的PDF.
我试过了:
> UIView在上下文中渲染
>使用CoreText
>使用Nsstring drawInRect
>使用UILabel drawRect
这是一个代码示例:
-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(Nsstring *) path
{
CGContextRef myOutContext = NULL;
NSURL * url;
url = [NSURL fileURLWithPath:path];
if (url != NULL) {
myOutContext = CGPDFContextCreateWithURL ((__bridge CFURLRef) url,&inMediaBox,NULL);
}
return myOutContext;
}
-(void)savePdf:(Nsstring *)outputPath
{
if (!pageViews.count)
return;
UIView * first = [pageViews objectAtIndex:0];
CGContextRef pdfContext = [self createPDFContext:CGRectMake(0,first.frame.size.width,first.frame.size.height) path:outputPath];
for(UIView * v in pageViews)
{
CGContextBeginPage (pdfContext,nil);
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformMakeTranslation(0,(int)(v.frame.size.height));
transform = CGAffineTransformScale(transform,1,-1);
CGContextConcatCTM(pdfContext,transform);
CGContextSetFillColorWithColor(pdfContext,[UIColor whiteColor].CGColor);
CGContextFillRect(pdfContext,v.frame);
[v.layer renderInContext:pdfContext];
CGContextEndPage (pdfContext);
}
CGContextRelease (pdfContext);
}
呈现的UIViews只包含UIImageView一堆UILabel(一些带有和一些没有边框).
我还尝试了在stackoverflow上找到的建议:继承UILabel并执行此操作:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds());
if (!layer.shouldRasterize && isPDF)
[self drawRect:self.bounds]; // draw unrasterized
else
[super drawLayer:layer inContext:ctx];
}
但这也没有改变任何事情.
无论我做什么,当在预览中打开PDF时,文本部分可以选择作为块,但不是每个字符的字符,并且缩放pdf显示它实际上是位图图像.
有什么建议?
解决方法
This Tutorial From Raywenderlich保存了我的Day.Hope它也适合你.
http://www.raywenderlich.com/6818/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-2
http://www.raywenderlich.com/6818/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-2