【问题标题】:Adding custom metadata in PDFDocument在 PDFDocument 中添加自定义元数据
【发布时间】:2012-06-15 18:07:56
【问题描述】:

我正在桌面和手持设备之间发送文档,并且我想将元数据标题添加到 PDF,如下所示。

<CUSTOM_HEADER>\n
{"fileInfoEncodedInJson\":
   {"filename":"My Print Out",
   "filesize\":"630",
   "filedesc":"",}
   }\n
</CUSTOM_HEADER>\n
… file contents …

我一直在使用提供 documentAttributessetDocumentAttributes 方法的 PDFKit 和 PDFDocument,但是因为它是自定义标题,所以当我设置属性并保存文件时它似乎不会持续存在:

NSURL *path = [NSURL fileURLWithPath:@"/Users/username/Desktop/file.pdf"];
PDFDocument *document = [[PDFDocument alloc] initWithURL:path];

NSDictionary *docAttributes = [self.document documentAttributes];
NSMutableDictionary *newAttributes = [[NSMutableDictionary alloc] initWithDictionary:docAttributes];
[newAttributes setObject: @"Custom header contents" forKey:@"Custom header"];
docAttributes = [[NSDictionary alloc] initWithDictionary: newAttributes];

[document setDocumentAttributes: docAttributes];

//Here Custom Header is an entry in the dictionary

[self.document writeToFile:@"/Users/username/Desktop/UPDATEDfile.pdf"];

//Here the UPDATEDfile.pdf does not contain the custom header

我一直在寻找,我发现了几个类似的问题(例如 cocoadev 上的here)但没有答案。有谁知道将自定义(即不是文档属性键下提供的 8 个预定义常量)标题存储到 PDF 文件的方法?

【问题讨论】:

    标签: cocoa pdf metadata


    【解决方案1】:

    我实际上并没有编辑预先存在的标题,我只是创建了一个 NSMutableData 对象,先添加文本数据,然后添加 PDF 数据,然后将此数据保存到我想要的路径。

     NSString *header = [NSString stringWithFormat:@"<CUSTOM_HEADER>\n {\"fileInfoEncodedInJson\":  {\"filename\":\"My Print Out\", \"filesize\":\"630\",\"filedesc\":\"\",}  }\n </CUSTOM_HEADER>\n"];
    
    // Append header to PDF data
    NSMutableData *data = [NSMutableData dataWithData:[header dataUsingEncoding:NSWindowsCP1252StringEncoding]];
    [data appendData:[doc dataRepresentation]];
    
    [data writeToFile:@"/Users/username/Desktop/UPDATEDfile.pdf" atomically:NO];
    

    这会在 Adob​​e 中为我打开一个 PDF 文件,并且在查看时标题是不可见的。

    【讨论】:

    • 在这种情况下,对象偏移将不正确并且文件已损坏。 Adobe Reader 可以打开文件(它会修复交叉引用),但其他 PDF 处理器可能会抱怨这一点。如果您的目标只是 Adob​​e Reader,那么您就可以了。
    • 你是对的。在我的具体情况下,我们将文件发送到需要此标头的移动应用程序并将文档推送到 Adob​​e Reader 应用程序,但感谢您的提醒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2018-06-24
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多