我正在尝试生成一个包含多个页面的 PDF 文件。我正在使用此代码:
-(void)createPDFfromUIUIWebView *)aView saveToDocumentsWithFileNameNSString*)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 像素。 (aView) 当我移动 `[aView.layer renderInContext:pdfContext];在 FOR 循环之外,它会生成一个包含 4 页的 PDF 文件,但前 3 页将为空白,最后一页有一些数据。
你们知道我该如何解决这个问题吗?!
Best Answer-推荐答案 strong>
bounds 表示层在其父层中的位置。所以当你渲染一个层时,它使用它的 frame 来确定它的内容。
您必须将 View 作为 subview 放置在另一个 View 中,例如 aView2 。然后像你已经做的那样设置 aView 的边界,然后渲染 aView2 。
它应该可以工作。
关于ios - 在 Xcode 中生成多页 PDF 文件,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/15499859/
|