2012-06-15 16 views
0

我在桌面和手持設備之間發送文檔,並且想要將元數據標題添加到PDF,如下所示。在PDFDocument中添加自定義元數據

<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文件?

回答

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]; 

這導致在Adobe爲我打開一個PDF文件,並查看當標題是看不見的。

+0

在這種情況下,對象偏移將不正確,並且文件已損壞。 Adobe Reader可以打開文件(修復交叉引用),但其他PDF處理器可能會抱怨這一點。如果你的目標只是Adobe Reader,那麼你很好。 – iPDFdev

+0

你是對的。在我的具體情況中,我們將文件發送到需要此標頭的移動應用程序,並將文檔推送到Adobe Reader應用程序,但感謝您的支持。 – Katie

相關問題