将NSImage输出为PDF文件

时间:2012-01-04 23:14:26

标签: cocoa pdf

如何使用Foundation将NSImage保存为PDF文件?这不是GUI应用程序,因此AppKit(以及NSView)未被使用。

编辑:好吧,我现在觉得很傻。 NSImage是AppKit的一部分,因此它正在使用中。但是,我的问题仍然存在:如何将NSImage保存为PDF?

1 个答案:

答案 0 :(得分:3)

通过建立与窗口服务器的连接,您可以使用NSImageNSView。您可以使用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