Objective-C AirPrint UIImageView изображение

Я пытаюсь напечатать некоторый текст из UITextView вместе с одним изображением из UIImageView. Я искал какой-то учебник в Интернете, и мне удалось распечатать текст из UITextView, но я еще не нашел способ распечатать с ним изображение. UIImageView, который я хочу распечатать, называется qrImageView, а UITextView называется qrNoteTextView. Я использую следующий код для печати TextView:

- (IBAction)qrPrint:(id)sender {
    NSLog(@"print action");
        [self.qrNoteTextView resignFirstResponder];
        NSMutableString *printBody = [NSMutableString stringWithFormat:@"%@ \n %@", self.qrNoteTextView.text, self.qrImageView.image];

        [printBody appendFormat:@"\nCreated using ..."];

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

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

        UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody];
        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;
        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);
            }
        };

        [pic presentFromBarButtonItem:self.qrNoteTextView animated:YES completionHandler:completionHandler];

}

Спасибо за ваше время!


person user3638160    schedule 12.02.2016    source источник
comment
Преобразуйте содержимое UITextView в NSData и попробуйте распечатать его после кодирования в формате UTF8. Пусть это поможет вам.   -  person Mandeep    schedule 12.02.2016


Ответы (1)


Преобразуйте содержимое UITextView в NSData и попробуйте распечатать его после кодирования в формате UTF8. Пусть это поможет вам.

Или вы можете преобразовать его в Base64 для печати. Вы можете использовать следующий код для печати текста и изображения.

NSMutableString *msgBody = [[NSMutableString alloc] initWithString:@""]; [msgBody appendString:[[NSString stringWithFormat:@"%@", @"Напечатано из MyApp"] stringByReplacingOccurrencesOfString:@"\n" withString:@""]];

                       //Embedding the image
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [NSString stringWithFormat:@"%@/Private Documents", [paths objectAtIndex:0]];

                       NSArray *arrayOfSignatureTitles = [[NSArray alloc] initWithObjects:@"image0.png", @"image1.png", @"image2.png", @"image3.png", nil];

                       for (NSString *imageName in arrayOfSignatureTitles)
{
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:appFile];

    if (imageData != nil)
    {
        [Base64 initialize];
        NSString *base64String = [Base64 encode:imageData];
        [msgBody appendString:[NSString stringWithFormat:@"  ",base64String]];
    }
}
                       [msgBody appendString:@""];

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

                       UIPrintInfo *printInfo = [UIPrintInfo printInfo];
                       printInfo.outputType = UIPrintInfoOutputGeneral;
                       printInfo.jobName = @"NarrativePro";
                       pic.printInfo = printInfo;

                       UIMarkupTextPrintFormatter *textFormatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:msgBody];
                       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;
                       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);
    }
};

                       [pic presentAnimated:YES completionHandler:completionHandler];
person Mandeep    schedule 12.02.2016
comment
Я преобразовал UITextView и UIImageView в NSData и объединил их в NSMutableData. Но как мне распечатать этот NSMutableData? - person user3638160; 12.02.2016
comment
Вы можете использовать следующий код для добавления изображения в UITextView 'UIImage* onions = [self thumbnailOfImageWithName:@onion extension:@jpg]; NSTextAttachment* onionatt = [новый NSTextAttachment]; onionatt.image = лук; onionatt.bounds = CGRectMake(0,-5,onions.size.width,onions.size.height); NSAttributedString* onionattchar = [NSAttributedString attributeStringWithAttachment:onionatt]; NSRange r = [[mas string] rangeOfString:@Onions]; [mas insertAttributedString: onionattchar atIndex: (r.location + r.length)]; self.tv.attributedText = мас; - person Mandeep; 12.02.2016
comment
Я добавил код принтера для печати текста и изображения. если это работает, пожалуйста, но ответьте. - person Mandeep; 12.02.2016
comment
Вам нужно загрузить файлы Base64, а затем добавить эти файлы в код вашего проекта. используйте этот код в методе. - person Mandeep; 12.02.2016
comment
Я получаю много ошибок, когда пытаюсь вписать код. Он не распознает «mas», «tv» и «thumbnailOfImagWithName». - person user3638160; 12.02.2016
comment
не забудьте добавить NSMutableString *msgBody = [[NSMutableString alloc] initWithString:@]; [msgBody appendString:[[NSString stringWithFormat:@%@, @Printed from MyApp] stringByReplacingOccurrencesOfString:@\n withString:@]]; - person Mandeep; 12.02.2016
comment
Он не распознает Base64, как я могу это решить? - person user3638160; 12.02.2016