iphone - 需要将 UITextView 完整内容渲染成 PDF

标签 iphone objective-c ios pdf uitextview

我有以下方法在我的@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 种方法 -

  1. 我看到一些代码正在执行 [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];。当我尝试时,我发现它导致我失去了文本清晰度。所以我不能使用这个方法。
  2. 这是更传统的方法。即你提取文本并绘制​​它。这段代码坚如磐石,并且已经看到了一些用法。因此,您需要做的就是从 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/

相关文章:

ios - 如何保护应用程序文档目录中的文件不被外部工具(iFunbox/iTools 等)读取

iphone - CLLocationmanager "locationServicesEnabled"方法在 iOS 4 中已弃用?

ios - 获取 Kontakt iBeacon 的属性

android - 可分配-是否支持-fno-objc-arc

ios - 如何构建/获取共享点文档的 Office Web App URL

iphone - 当始终插入时,您如何管理开发设备的电池健康状况?

iphone - 哪些类可以用作 NSDictionary 中的键?

ios - 如何在uicollectionview中的两个单元格之间画线

objective-c - Mac OS X View 交换

ios - 使用 Swift 对 TableViewController 中的字典数据进行分组和排序