Печать с устройства iOS (AirPrint) - PullRequest
1 голос
/ 03 июля 2011

Я думаю, что подхожу к этому не с того угла. Это мой первый набег в PDF с Quartz. Я хотел бы иметь возможность печатать текст, который вводится в мое приложение, но мне, возможно, придется удалить его в этом выпуске.

Я прочитал все, что смог получить, как в Apple, так и в Интернете, но я не могу заставить свои вещи работать. Я могу получить документ на принтер, но он всегда печатается пустым. Процесс, который я использую:

  1. Получить текст как NSString.
  2. Преобразование строки в PDF в объекте NSData.
  3. Распечатать.

У меня есть два метода в моем текстовом проекте. Это всего лишь тест, поэтому никаких наворотов и, возможно, утечек памяти нет, я просто пытаюсь заставить его работать.

Заранее спасибо за любую помощь.

Первый создает документ PDF как NSData.

- (NSData *)createPdfAsDataWithAttributedString:(NSAttributedString *)text {
    // Save the text just in case…
    _pdfText = [text copy];

    // Allocate the pdf Context.
    CGContextRef pdfContext;

    // Create the PDF Attribute Dictionary.
    CFMutableDictionaryRef pdfAttributeDictionary = NULL;
    pdfAttributeDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(pdfAttributeDictionary, kCGPDFContextTitle, CFSTR("My Note"));
    CFDictionarySetValue(pdfAttributeDictionary, kCGPDFContextCreator, CFSTR("Me"));

    // Create the data referece as a mutable data type.
    NSData *pdfData = [[NSMutableData alloc] init];

    // User the data consumer using the data reference.
    CGDataConsumerRef pdfDataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);

    // Finally the pdfContext can be created.
    pdfContext = CGPDFContextCreate(pdfDataConsumer, NULL, pdfAttributeDictionary);

    // Start the first page.
    CGContextBeginPage(pdfContext, NULL);

    // Set the font
    CGContextSelectFont(pdfContext, "Helvetica", 16.0f, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(pdfContext, kCGTextFill);
    CGContextSetRGBFillColor(pdfContext, 0, 0, 0, 1);

    // Print the text
    NSString *regText = [text string];
    const char *pdfText = [regText cStringUsingEncoding:NSUTF8StringEncoding];
    CGContextShowText(pdfContext, pdfText, strlen(pdfText));

    // End the page.
    CGContextEndPage(pdfContext);

    // Save the current state
    CGContextSaveGState(pdfContext);    

    // Release the PDF context
    CGContextRelease(pdfContext);

    return [pdfData autorelease];
}

Второй отпечаток.

- (IBAction)printPdfTouchUpInside:(id)sender {
    PDFCreator *pdfCreator = [[PDFCreator alloc] init];
    NSData *pdfData = [pdfCreator createPdfAsDataWithAttributedString:_printableText];
    UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    [printInfo setPrinterID:@"Canon MP620 series"];
    [printInfo setOrientation:UIPrintInfoOrientationPortrait];
    [printInfo setOutputType:UIPrintInfoOutputGeneral];
    [printInfo setJobName:@"Test Print"];

    [printController setPrintInfo:printInfo];
    [printController setPrintingItem:pdfData];

    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);
        }
    };

    [printController presentFromRect:[sender bounds] inView:sender animated:YES completionHandler:completionHandler];
}
...