简体   繁体   English

将NSImage输出为PDF文件

[英]Output NSImage to PDF file

How would you save an NSImage to a PDF file with Foundation? 如何使用Foundation将NSImage保存为PDF文件? This is not a GUI app so AppKit (and therefore NSView) is not in use. 这不是GUI应用程序,因此未使用AppKit(因此未使用NSView)。

EDIT: Well, I feel silly now. 编辑:嗯,我现在觉得很傻。 NSImage is part of AppKit, so it is in use. NSImage是AppKit的一部分,因此它正在使用中。 However, my question still stands: how do you save the NSImage to a PDF? 但是,我的问题仍然存在:如何将NSImage保存为PDF?

By making a connection to the window server you can use NSImage and NSView . 通过建立与窗口服务器的连接,您可以使用NSImageNSView You can make that connection to the window server by using the AppKit function NSApplicationLoad . 您可以使用AppKit函数NSApplicationLoad建立与窗口服务器的连接。

main.m 的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;
}

Compile this with the frameworks Foundation and AppKit linked: 使用链接有Foundation和AppKit的框架进行编译:

gcc -framework Foundation -framework AppKit main.m

When you compiled it you can use it like this: 编译它时,您可以像这样使用它:

./a.out myImage.png outFile.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM