Вывести NSImage в файл PDF - PullRequest
       0

Вывести NSImage в файл PDF

1 голос
/ 05 января 2012

Как бы вы сохранили NSImage в PDF-файл с помощью Foundation?Это не приложение с графическим интерфейсом, поэтому AppKit (и, следовательно, NSView) не используется.

РЕДАКТИРОВАТЬ: Ну, я чувствую себя глупо сейчас.NSImage является частью AppKit, поэтому он используется.Тем не менее, мой вопрос остается в силе: как сохранить NSImage в PDF?

1 Ответ

3 голосов
/ 05 января 2012

Установив соединение с оконным сервером, вы можете использовать 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;
}

Скомпилируйте это с использованием Frameworks и AppKit:

gcc -framework Foundation -framework AppKit main.m

Когда вы скомпилировали его, вы можете использовать его так:

./a.out myImage.png outFile.pdf
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...