Вам необходимо преобразовать все данные в формат HTML и использовать WebView для отображения данных. Чтобы получить распечатку из приложения iPhone, вам нужно создать файл PDF из содержимого веб-просмотра, а затем вынуть распечатку из этого файла PDF. Здесь я даю вам пример кода, он правильно работает в моем приложении.
1) включает каркас QuartzCore и импортирует «QuartzCore / QuartzCore.h» в файл ViewController.h.
2) В файле ViewController.h используйте следующий код
@interface ViewController : UIViewController<UIScrollViewDelegate, UIPrintInteractionControllerDelegate>
{
UIWebView *theWebView;
int imageName;
double webViewHeight;
}
-(void) takeSnapshot;
- (void) drawPdf;
-(void) printContent:(NSData *) data;
3) Для метода viewDidLoad используйте следующий код:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *htmlString=@"<html><body><img src=\"blue.png\" alt=\"Blue Image\" /> <h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p></body></html>";
UIBarButtonItem *generate=[[UIBarButtonItem alloc] initWithTitle:@"Print" style:UIBarButtonItemStylePlain target:self action:@selector(printBtnPressed)];
[self.navigationItem setRightBarButtonItem:generate];
theWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
[theWebView loadHTMLString:htmlString baseURL:nil];
theWebView.scrollView.bounces=NO;
[self.view addSubview:theWebView];
imageName=0;
webViewHeight=0.0;
}
4) определения методов
-(void) printBtnPressed
{
[self takeSnapshot];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *filePath=[documentDir stringByAppendingPathComponent:@"Demo.pdf"];
NSData *data=[[NSData alloc] initWithContentsOfFile:filePath];
[self printContent:data];
}
-(void) takeSnapshot
{
webViewHeight=[[theWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];
CGRect screenRect=theWebView.frame;
double currentWebViewHeight = webViewHeight;
while (currentWebViewHeight > 0)
{
imageName ++;
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
[theWebView.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",imageName]];
if(currentWebViewHeight < 416)
{
CGRect lastImageRect = CGRectMake(0, 416 - currentWebViewHeight, theWebView.frame.size.width, currentWebViewHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
newImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
[UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];
[theWebView stringByEvaluatingJavaScriptFromString:@"window.scrollBy(0,416);"];
currentWebViewHeight -= 416;
}
[self drawPdf];
}
- (void) drawPdf
{
CGSize pageSize = CGSizeMake(612, webViewHeight);
NSString *fileName = @"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", index]];
UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();
}
-(void) printContent:(NSData *) data
{
UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
print.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
//printInfo.jobName = @"Information";
printInfo.duplex = UIPrintInfoDuplexLongEdge;
print.printInfo = printInfo;
print.showsPageRange = YES;
print.printingItem = data;
UIViewPrintFormatter *viewFormatter = [self.view viewPrintFormatter];
viewFormatter.startPage = 0;
print.printFormatter = viewFormatter;
UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {};
[print presentAnimated:YES completionHandler:completionHandler];
}