简体   繁体   中英

Output NSImage to PDF file

How would you save an NSImage to a PDF file with Foundation? This is not a GUI app so AppKit (and therefore NSView) is not in use.

EDIT: Well, I feel silly now. NSImage is part of AppKit, so it is in use. However, my question still stands: how do you save the NSImage to a PDF?

By making a connection to the window server you can use NSImage and NSView . You can make that connection to the window server by using the AppKit function 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;
}

Compile this with the frameworks Foundation and AppKit linked:

gcc -framework Foundation -framework AppKit main.m

When you compiled it you can use it like this:

./a.out myImage.png outFile.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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