元数据是元数据(当然,它是由Adobe您使用XMP XML推荐)。只要你创建一个有效的CFDataRef并将它传递给参数2,你就可以随意使用任何东西。例如,下面是如何将字符串“Hello World”传递到一个PDF的元数据:
void MakeAPDF()
{
CGRect mediaRect = CGRectMake(0, 0, 400, 600);
// use your own rect instead
CFMutableDataRef result = CFDataCreateMutable(kCFAllocatorDefault, 0);
CGDataConsumerRef PDFDataConsumer = CGDataConsumerCreateWithCFData(result);
// mark the PDF as coming from your program
CFMutableDictionaryRef auxInfo = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, NULL);
CFDictionaryAddValue(auxInfo, kCGPDFContextCreator, CFSTR("Your Programs Name"));
CFDictionaryRef auxillaryInformation = CFDictionaryCreateCopy(kCFAllocatorDefault, auxInfo);
CFRelease(auxInfo);
// create a context to draw into
CGContextRef graphicContext = CGPDFContextCreate(PDFDataConsumer, &mediaRect, auxillaryInformation);
CFRelease(auxillaryInformation);
CGDataConsumerRelease(PDFDataConsumer);
// actually make the call to embed your String
NSString* str= @"Hello World";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
CFDataRef cfdata = CFDataCreate(NULL, [data bytes], [data length]);
CGPDFContextAddDocumentMetadata(graphicContext, cfdata);
CGContextBeginPage(graphicContext, &mediaRect);
// do your drawing, like this grey rectangle
CGContextSetGrayFillColor(graphicContext, 0.5, 0.5);
CGContextAddRect(graphicContext, mediaRect);
CGContextFillPath(graphicContext);
// end your drawing
CGContextEndPage(graphicContext);
CGContextFlush(graphicContext);
CGPDFContextClose(graphicContext);
}
XMP文件可能是这样的:
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c041">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:format>application/pdf</dc:format>
<dc:title>
<rdf:Alt>
<rdf:li />
</rdf:Alt>
</dc:title>
<dc:description>
<rdf:Alt>
<rdf:li />
</rdf:Alt>
</dc:description>
<dc:creator>
<rdf:Seq>
<rdf:li />
</rdf:Seq>
</dc:creator>
</rdf:Description>
<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
<pdf:Keywords />
<pdf:Producer />
</rdf:Description>
<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">
<xmp:CreatorTool />
<xmp:CreateDate>2011-02-10T11:41:05+02:00</xmp:CreateDate>
<xmp:ModifyDate>2011-02-10T11:41:06+02:00</xmp:ModifyDate>
</rdf:Description></rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
谢谢你的帮助! :) 我的PDF目前由UIGraphicsBeginPDFContextToFile创建,生成的PDF为“firstDoc.pdf”。我怎样才能让它传递这个文件并添加元数据? 您的代码创建一个新的图形上下文并用它来生成pdf。 –
当您生成上下文时,只需使用从字符串向下到元数据添加调用的所有内容并传入上下文。另外,不要忘记upvote和接受! – CodaFi
我的问题是,我在PDF文档中有多个页面。我不确定你的方法,但最后一次生成PDF时,我无法继续输入字符串。当我估计我的页面空间不足时,我必须调用一些“创建新页面功能”。 –