我正在尝试生成一个包含多个页面的 PDF 文件。我正在使用这个代码:
-(void)createPDFfromUI:(UIWebView *)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
UIWebView *myView = [[UIWebView alloc] init];
[myView setBounds:CGRectMake(0,0, 320, 480)];
UIGraphicsBeginPDFContextToData(pdfData, myView.bounds, nil);
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
for (int i = 0; i < 4; i++) {
UIGraphicsBeginPDFPage();
aView.layer.bounds = CGRectMake(0,480* -i , 320, 480);
[aView.layer renderInContext:pdfContext];
}
[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];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
}
这段代码的问题是,它只是生成一个包含 4 个相似页面的 PDF 文件,而且它们都是我原始页面的最后 480 px。 (aView) 另外,当我移动 `[aView.layer renderInContext:pdfContext]; 时从 FOR 循环中退出,它会生成一个 4 页的 PDF 文件,但前 3 页将为空白,最后一页有一些数据。
你们知道我该如何解决这个问题吗?!
bounds 表示图层在其父图层中的位置。因此,当您渲染图层时,它会使用其
frame
来确定其内容。
您必须将该视图作为子视图放置在另一个视图中,例如 aView2
。然后像您已经做的那样设置 aView
的边界,然后渲染 aView2
。
应该可以。
添加字符串数组并尝试刷新应用程序
您还必须将物理 pdf 文件添加到您的 xcode 项目中 您可以通过将其拖放到左侧菜单浏览来完成此操作
另一种可以使用的方法是使用 URL 远程访问 pdf
点击运行看看是否有效
希望这有帮助