ios - 从 UIScrollView Objective C 创建 PDF

标签 ios objective-c uiscrollview

此问题之前已发布(Creating PDF from UIScrollView in iphone app),我使用的代码来自here .

这是代码

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
    // 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, aView.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

    [aView.layer renderInContext:pdfContext];

    // remove PDF rendering context
    UIGraphicsEndPDFContext();

    // Retrieves the document directories from the iOS device
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    // instructs the mutable data object to write its context to a file on disk
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
}

设置:我有一个 UIScrollView,里面是一个 UIView。我想保存整个 UIView (950,500px),它位于 (520,500) 的空间(UIScrollView 大小)中。生成的PDF只有UIScrollView的大小(520,500)

我读了answer但他显然更改了代码,但它对我不起作用。我整天都在努力解决这个问题。

我是初学者,所以请指出我应该在我的问题中添加我遗漏的任何内容。谢谢。

PS - 这是一款 iPad 应用。

最佳答案

上下文的大小应该是 ScrollView 的内容大小,而不是边界。

然后您需要临时将 ScrollView 的大小调整为其内容大小,在 PDF 上下文中呈现它,并将 ScrollView 的大小恢复为其原始大小。

UIGraphicsBeginPDFContextToData(pdfData, (CGRect){0,0, scrollView.contentSize}, nil);

CGRect origSize = scrollView.frame;
CGRect newSize = origSize;
newSize.size = scrollView.contentSize;
[scrollView setFrame:newSize];

[scrollView.layer renderInContext:pdfContext];

[scrollView setFrame:origSize];

关于ios - 从 UIScrollView Objective C 创建 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562085/

相关文章:

uiscrollview - UIScrollView.contentInset 如何向上滚动内容 View ?

iphone - 将触摸手势发送到 UIScrollView 的 UIImageView subview

ios - 真的没有办法设置 SKLabelNode 的样式吗?

ios - View Controller 层次结构中 IBOutlet subview Controller 的引用类型(弱或强)?

ios - 错误 : could not find included file 'Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' )

ios - 状态栏在 iOS 6 上消失了

iphone - 如何将控件很好地粘贴到 IB 中的 UIScrollView 中?

ios - 在 UIView 子类中执行计算会破坏 MVC 的设计模式吗?

ios - UITableViewCell 子类在重新显示时重新加载 subview

ios - 安装 cocoa pod 时出错