Katie
Katie

Reputation: 253

Adding custom metadata in PDFDocument

I'm sending a document between the desktop and a handheld device, and I want to add a metadata header to a PDF like the following.

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

I've been using the PDFKit and PDFDocument which supplies the documentAttributes and setDocumentAttributes methods, but because it is a custom header, it doesn't seem to persist when I set the attributes and save the file:

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

I've been looking all over and I've found a couple of similar questions (like here on cocoadev for example) but no answers. Does anyone know of a way to store custom (i.e. not the 8 predefined constants provided under Document Attribute Keys) headers to PDF Files?

Upvotes: 0

Views: 1374

Answers (1)

Katie
Katie

Reputation: 253

I didn't actually edit the pre-existing headers, I simply created a NSMutableData object, added the text data first followed by the PDF data, then saved this data to the path I wanted.

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

This results in a PDF file that opens in Adobe for me, and the header is invisible when viewing.

Upvotes: 1

Related Questions