Подтвердить что ты не робот

Как печатать в iOS 4.2?

Я хочу интегрировать функции печати в свое приложение.

Документ, который я хочу напечатать, будет находиться в формате .doc или .txt. Я еще не очень разбираюсь в разработке iPhone, поэтому трудно реализовать его, следуя документации Apple.

Если кто-то может мне помочь, разместив несколько примеров кода, это будет большой помощью.

4b9b3361

Ответ 1

Ознакомьтесь с Руководство по рисованию и печати для iOS. Я связался с разделом печати. Там пример кода и хорошие ссылки на другой пример кода.

Изменить. Теперь я вижу, что вы указываете, что вам трудно найти документацию.

Документы Word сложны - вам нужно проанализировать данные, что довольно сложно.

Текст и HTML проще. Я взял пример Apple для HTML и изменил его для обычного текста:

- (IBAction)printContent:(id)sender {
    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;

    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = self.documentName;
    pic.printInfo = printInfo;

    UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
                                                 initWithText:yourNSStringWithContextOfTextFileHere];
    textFormatter.startPage = 0;
    textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
    textFormatter.maximumContentWidth = 6 * 72.0;
    pic.printFormatter = textFormatter;
    [textFormatter release];
    pic.showsPageRange = YES;

    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
    ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed && error) {
            NSLog(@"Printing could not complete because of error: %@", error);
        }
    };
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        [pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
    } else {
        [pic presentAnimated:YES completionHandler:completionHandler];
    }
}

Ответ 2

привет, это может помочь вам попробовать и отправить, если есть какие-либо запросы.

-(IBAction)printFromIphone:(id)sender {

    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;

    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = self.documentName;
    pic.printInfo = printInfo;

    UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
                                                 initWithText:yourNSStringWithContextOfTextFileHere];
    textFormatter.startPage = 0;
    textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
    textFormatter.maximumContentWidth = 6 * 72.0;
    pic.printFormatter = textFormatter;
    [textFormatter release];
    pic.showsPageRange = YES;

    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
    ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed && error) {
            NSLog(@"Printing could not complete because of error: %@", error);
        }
    };
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        [pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
    } else {
        [pic presentAnimated:YES completionHandler:completionHandler];
    }
}

Ответ 3

Прежде всего добавьте UIPrintInteractionControllerDelegate и создайте переменную

    UIPrintInteractionController *printController;

Ниже приведен код для печати всех изображений, документов, Excel, PowerPoint, файлов PDF для меня:

[self printItem:SomeData withFilePath:YourFilePath];

В приведенном выше коде вы указываете NSData​​strong > вашего документа/изображения и URL (filePath) и ниже следующего кода printItem: withFilePath: метод

-(void)printItem :(NSData*)data withFilePath:(NSString*)filePath{
printController = [UIPrintInteractionController sharedPrintController];
printController.delegate = self;

UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [NSString stringWithFormat:@""];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
printController.printInfo = printInfo;
printController.showsPageRange = YES;


//If NSData contains data of image/PDF
if(printController && [UIPrintInteractionController canPrintData:data]) {
    printController.printingItem = data;

}else{
    UIWebView* webView = [UIWebView new];
    printInfo.jobName = webView.request.URL.absoluteString;
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];

    printController.printFormatter = webView.viewPrintFormatter;

}

    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed && error) {
            //NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code);
        }
    };

    // Check wether device is iPad/iPhone , because UIPrintInteractionControllerDelegate has different methods for both devices
    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        [printController presentFromRect:self.view.frame inView:self.view animated:YES completionHandler:completionHandler];
    }
    else {
        [printController presentAnimated:YES completionHandler:completionHandler];
    }
}

Надеюсь, это поможет. Благодаря