Ios 从UIScrollView目标C创建PDF

Ios 从UIScrollView目标C创建PDF,ios,objective-c,uiscrollview,Ios,Objective C,Uiscrollview,这个问题在()之前已经发布过,我使用的代码来自 这是密码 -(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename { // Creates a mutable data object for updating with binary data, like a byte array NSMutableData *pdfData = [NSMutableDat

这个问题在()之前已经发布过,我使用的代码来自

这是密码

-(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(950500px),它位于(520500)的空间(UIScrollView大小)中。生成的PDF只有UIScrollView(520500)的大小

我读了那封信,但他显然改变了密码,但对我不起作用。我一整天都在努力解决这个问题

我是一个初学者,所以请指出任何我应该补充到我的问题,我错过了。多谢各位


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];

如果有人想知道,我找到了解决方法

由于我的UIView位于UIScrollView中,并且我为UIView使用了另一个类,因此当我调用该方法并选择参数
aView
时,我只需输入
self

因此,在我的UIView类中,当我想要生成PDF时,我输入

[self-createPDFfromUIView:self-saveToDocumentsWithFileName:UIViewPDF]

检查示例,您将了解需要做什么

它使用相同的
scrollview的
渲染上下文
,但这里的PDF是根据您的要求创建的,例如一页PDF或多页PDF


注意:它捕获ScrollView的所有可见和不可见部分是
createPDFfromUIView:
内部
UIView
UIScrollView
的第一个参数?我认为应该是UIView,如果不是这样的话。@Taum是的,我使用的是UIView。我试过这个,它使PDF大小正确,但延伸出原始图片。@KChockey Stretch如何?您是否正确调整了scrollview的大小?是否可以编辑我的代码?我认为这是因为代码行的顺序通过拉伸,我的意思是它只占UIView的一部分(大约600像素——比UIScrollView大,这是一个好的开始),但将600px的图像拉伸到950px@Popeye当前位置正在改进我的答案,并收到了您的消息,但仍然感谢您的关注。