如何使用 Foundation 将 NSImage 保存为 PDF 文件?这不是 GUI 应用程序,因此未使用 AppKit(以及 NSView)。
编辑:嗯,我现在觉得很傻。 NSImage是AppKit的一部分,因此正在使用。但是,我的问题仍然存在:如何将 NSImage 保存到 PDF?
最佳答案
通过与窗口服务器建立连接,您可以使用 NSImage
和 NSView
。您可以使用 AppKit 函数 NSApplicationLoad
建立与窗口服务器的连接。
main.m
#include <AppKit/AppKit.h>
int main(int argc, const char **argv) {
if(argc != 3) {
fprintf(stderr, "Usage: %s source_img dest_pdf\n", argv[0]);
exit(1);
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BOOL success;
NSString *imgPath, *pdfPath;
NSImage *myImage;
NSImageView *myView;
NSRect vFrame;
NSData *pdfData;
imgPath = [NSString stringWithUTF8String:argv[1]];
pdfPath = [NSString stringWithUTF8String:argv[2]];
/* Calling NSApplicationLoad will give a Carbon application a connection
to the window server and enable the use of NSImage, NSView, etc. */
success = NSApplicationLoad();
if(!success) {
fprintf(stderr, "Failed to make a connection to the window server\n");
exit(1);
}
/* Create image */
myImage = [[NSImage alloc] initWithContentsOfFile:imgPath];
if(!myImage) {
fprintf(stderr, "Failed to create image from path %s\n", argv[1]);
exit(1);
}
/* Create view with that size */
vFrame = NSZeroRect;
vFrame.size = [myImage size];
myView = [[NSImageView alloc] initWithFrame:vFrame];
[myView setImage:myImage];
[myImage release];
/* Generate data */
pdfData = [myView dataWithPDFInsideRect:vFrame];
[pdfData retain];
[myView release];
/* Write data to file */
success = [pdfData writeToFile:pdfPath options:0 error:NULL];
[pdfData release];
if(!success) {
fprintf(stderr, "Failed to write PDF data to path %s\n", argv[2]);
exit(1);
}
[pool release];
return 0;
}
使用 Foundation 和 AppKit 链接的框架进行编译:
gcc -framework Foundation -framework AppKit main.m
当你编译它时,你可以像这样使用它:
./a.out myImage.png outFile.pdf
关于cocoa - 将 NSImage 输出为 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735473/