我有以下方法在我的@implementation UIView (SaveToPdf) 类中运行良好
- (NSData *) toPdfData
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, self.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[self.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
return pdfData;
}
我使用此方法将我的 View 打印为 PDF,除一个问题外,它工作正常。我的 View 包含一个 UITextView,而 pdf 仅打印该 UITextView 的可见区域。我需要 PDF 来呈现完整内容(即可滚动文本)
我是 iOS 开发的新手,如果有人能指出正确的方向,我将不胜感激。
*需要注意的一点是,我在 UIView 中还有其他 subview (标签、文本字段等)也需要打印到该 PDF。这目前工作正常,只需使用 [self.layer renderInContext:pdfContext]; 即可将布局保留在我的 PDF 中。因为主视图将遍历它的所有 subview ..
谢谢
最佳答案
我知道 2 种方法 -
- 我看到一些代码正在执行
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
。当我尝试时,我发现它导致我失去了文本清晰度。所以我不能使用这个方法。 - 这是更传统的方法。即你提取文本并绘制它。这段代码坚如磐石,并且已经看到了一些用法。因此,您需要做的就是从
uitextview
中获取所有文本并将其传递到此处...
希望这对您有所帮助。
#define kBorderInset 25.0
#define kMarginInset 15.0
- (void) drawText
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
NSString *textToDraw = @"YOUR TEXT FROM UITEXTVIEW HERE";
UIFont *font = [UIFont systemFontOfSize:16.0];
CGSize stringSize = [textToDraw sizeWithFont:font
constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset)
lineBreakMode:UILineBreakModeWordWrap];
CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 350.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);
[textToDraw drawInRect:renderingRect
withFont:font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
return;
}
关于iphone - 需要将 UITextView 完整内容渲染成 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14133386/