cocoa - 将 NSImage 输出为 PDF 文件

标签 cocoa pdf

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

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

最佳答案

通过与窗口服务器建立连接,您可以使用 NSImageNSView。您可以使用 AppKit 函数 NSApplicationLoad 建立与窗口服务器的连接。

ma​​in.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/

相关文章:

macos - NSDocument 的 NSSavePanel 的自定义附件 View

objective-c - 调用 [NSScreen mainScreen] 时的额外线程

cocoa - 使用绑定(bind)设置 NSBrowserCell 图像?

android - 可靠地检测 Android 设备上的 PDF 支持

python - 使用 Django 和 Reportlab 从 HTML 生成 PDF

objective-c - NSFileManager 或 NSTask 移动文件类型

c# - 使用 iTextSharp 和 C# 自动调整表格列宽

javascript - 执行使用jquery ajax生成PDF的php文件

java - 读取 PDF、接收文本以及写入新 PDF 的简单方法。 ( java )

objective-c - 如何为框架配置 OCUnit 测试包?