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!
This line has at least three errors:
First, the
dataUsingEncoding:message asks the string to encode itself as data, but you want a decode operation, not an encode operation.Second, the
dataUsingEncoding:method requires anNSStringEncodingargument, andNSDataBase64Encoding64CharacterLineLengthis not anNSStringEncoding. (It is anNSDataBase64EncodingOptions.)Unfortunately, because you are using Objective-C instead of Swift, the compiler doesn't reject this code. (Maybe it gives a warning though? I didn't try it.)
Third,
dataUsingEncoding:returns anNSData, not anNSImage. I'm pretty sure the compiler emits at least a warning for this.You need to decode the string to an
NSDatausinginitWithBase64EncodingString:options:, and then you need to create anNSImagefrom theNSDatausinginitWithData:.