我正在尝试创建PDF,然后在webview中加载PDF以进行预览。现在我可以成功创建pdf。接下来,我想通过按下按钮创建pdf,然后在webview中加载。我参考了this link和this link。虽然PDF已成功创建,但PDF无法加载到Web视图中。 任何人都可以提供建议吗?非常感谢你。ios - 在webview中创建和加载pdf
代码:
-(IBAction)preview:(id)sender
{
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
NSDate*todayDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd-MM-yyyy "];
NSString *mytext = [NSString stringWithFormat:@"form%@",[dateFormatter stringFromDate:todayDate]];
[self createPDFfromUIView:_myView saveToDocumentsWithFileName:mytext];
NSLog(@"is saved in %@", mytext);
NSString *path = [self createPDFfromUIView:_myView saveToDocumentsWithFileName:mytext];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
}
-(NSMutableData *)createPDFDatafromUIView:(UIView*)aView
{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[aView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
return pdfData;
}
-(NSString*)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableData *pdfData = [self createPDFDatafromUIView:aView];
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[aView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
NSLog(@"saved in %@", documentDirectoryFilename);
return documentDirectoryFilename;
}
你在上面的评论暗示这个问题是一个重复?如果是这样,我不理解非接近投票或答案。 – danh
@danh在阅读代码之后,我已经收回了重复标记,然后在阅读完代码后,我看到所有与这个问题无关的错误,我花时间给他解决方案,但让评论仍然存在在未来的参考之下,有人会遇到这个问题,并回答这个问题的实际问题。 – 2017-02-18 17:11:27
我明白。也许用这些链接改进这个答案作为进一步的参考?然后重复的暗示评论可以消失。 – danh