Mac OS X: Print directly from file/URL?

╄→гoц情女王★ 提交于 2019-12-21 02:54:15

问题


I want to code a litte utility that can print a page from a an URL, the URL would deliver a standard file (like a pdf or a jpg picture) and I just want to print this from within my cocoa app without showing any dialog, is that possible? I can't find anything about this in the docs except for a thing telling me to build a view with the file and then print this view but is this really necessary?

Any help appreciated.

Thanks, Philip


回答1:


You don't need to show the NSView in order to print.
Just create the NSView programmatically and pass it to the NSPrintOperation.

Example code:

// Get Print Info
NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];

// Printing Text
NSRect textRect = NSMakeRect(0,0,100,50);
NSTextView *theTextView = [[NSTextView alloc] initWithFrame:textRect];
[theTextView setString: @"Hello World"];
NSPrintOperation *textPrint = [NSPrintOperation printOperationWithView:theTextView printInfo:printInfo];
[textPrint setCanSpawnSeparateThread:YES];
[textPrint runOperation];

// Printing Picture
NSImage *pic =  [[NSImage alloc] initWithContentsOfFile: @"/Users/Anne/Desktop/Sample.png"];
NSRect picRect = NSRectFromCGRect(CGRectMake(0, 0, pic.size.width, pic.size.height));
NSImageView *imageView = [[NSImageView alloc] initWithFrame:picRect];
[imageView setImage:pic];
NSPrintOperation * picPrint = [NSPrintOperation printOperationWithView:imageView printInfo:printInfo];
[picPrint setCanSpawnSeparateThread:YES];
[picPrint runOperation];

For PDF documents use PDFView (add the Quartz framework).

You might also consider using WebView (add the WebKit framework).
WebView supports many formats and makes formatting a breeze (HTML).



来源:https://stackoverflow.com/questions/11139386/mac-os-x-print-directly-from-file-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!