在iPad上将UIView呈现为PDF格式的vector – 有时呈现为位图,有时呈现为vector

我有一个iPad应用程序,我试图从一个UIView生成PDF,它几乎完美的工作。

代码非常简单,如下所示:

UIGraphicsBeginPDFContextToFile( filename, bounds, nil ); UIGraphicsBeginPDFPage(); CGContextRef pdfContext = UIGraphicsGetCurrentContext(); [view.layer renderInContext:pdfContext]; UIGraphicsEndPDFContext(); 

一个奇怪的例外,这真的很好。 如果视图在呈现为PDF之前已经在屏幕上,那么视图上的UILabels将作为精彩的向量呈现给PDF。 如果视图还没有在屏幕上(IE控制器是initWithNib等,但没有被推入到导航控制器或任何东西),那么文本呈现为'ipad'分辨率的位图。

这就像在屏幕上呈现的行为,当我随后将其呈现为pdf上下文时,将视图设置为向量。

是否有一些我可以调用的方法或属性,我可以在视图或图层或其他地方设置模仿此行为,而无需在屏幕上显示视图?

这与UIViewPrintFormatter有关吗?

我发现使它成为向量化的唯一方法是使用以下方法使用UILabel的子类:

 /** Overriding this CALayer delegate method is the magic that allows us to draw a vector version of the label into the layer instead of the default unscalable ugly bitmap */ - (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视图中是未定义和可选的,并且在渲染到屏幕时performance正常。

如果您在屏幕上添加视图,但是在屏幕外坐标处,那怎么办? 这似乎更像是一个黑客,但它可能工作。

我想build议一个替代mprudhom伟大的解决scheme:使用UIString扩展,你也可以使UILabel的文本呈现为字体(与select'n'copy支持等)。这样字体的字形embedded在PDF正确。

为了支持右和中心文本alignment以及默认的垂直居中alignment,我必须计算drawInRect方法的边界框。

 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds()); if (!layer.shouldRasterize && isPDF) { // [self drawRect:self.bounds]; CGSize fitSize = [self sizeThatFits:self.bounds.size]; float x = self.bounds.origin.x; float y = self.bounds.origin.y; if (self.textAlignment == NSTextAlignmentCenter) { x += (self.bounds.size.width - fitSize.width) / 2.0f; y += (self.bounds.size.height - fitSize.height) / 2.0f; } else if (self.textAlignment == NSTextAlignmentRight) { x += self.bounds.size.width - fitSize.width; y += self.bounds.size.height - fitSize.height; } [self.textColor set]; [self.text drawInRect:CGRectMake(x, y, fitSize.width, fitSize.height) withFont:self.font lineBreakMode:NSLineBreakByWordWrapping alignment:self.textAlignment]; } else { [super drawLayer:layer inContext:ctx]; } } 

使用drawInContext而不是renderInContext

尝试使用视图的viewPrintFormatter。

而不是[view.layer renderInContext:pdfContext];

尝试这个

 CALayer* formattedLayer = [view viewPrintFormatter].view.layer; [formattedLayer renderInContext:pdfContext];