objective-cmacosbase64nsimage

Print NSImage from base64 string


I'd like to print a base64 encoded image (passed in from canvas in a web view). How can I read/print a base64 string? Here's what I have so far:

- (void) printImage:(NSString *)printerName andData:(NSString *)base64img andW:(float)paperW andH:(float)paperH {
    
    NSImage *img = [base64img dataUsingEncoding:NSDataBase64Encoding64CharacterLineLength];
    
    NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
    [printInfo setTopMargin:0.0];
    [printInfo setBottomMargin:0.0];
    [printInfo setLeftMargin:0.0];
    [printInfo setRightMargin:0.0];
    [printInfo setHorizontalPagination:NSFitPagination];
    [printInfo setVerticalPagination:NSFitPagination];
    
    [printInfo setPaperSize:NSMakeSize(paperW, paperH)];
    [printInfo setPrinter:[NSPrinter printerWithName:printerName]];
    
    NSPrintOperation *op = [img printOperationForPrintInfo: printInfo autoRotate: YES];
    
    [op setShowsPrintPanel:NO];
    [op setShowsProgressPanel:NO];
    [op runOperation];
}

Thanks in advance!


Solution

  • This line has at least three errors:

    NSImage *img = [base64img dataUsingEncoding:NSDataBase64Encoding64CharacterLineLength];
    

    You need to decode the string to an NSData using initWithBase64EncodingString:options:, and then you need to create an NSImage from the NSData using initWithData:.

    NSData *data = [[NSData alloc] initWithBase64EncodedString:base64img
        options:NSDataBase64DecodingIgnoreUnknownCharacters];
    if (data == nil) {
        return;
    }
    
    NSImage *img = [[NSImage alloc] initWithData:data];
    if (img == nil) {
        return;
    }