我有一个PDF文档的输入流可供我使用。我想将subject
元数据添加到文档中,然后保存。我不知道该怎么做。
我在这里看到了一个示例食谱:https://pdfbox.apache.org/1.8/cookbook/workingwithmetadata.html
然而,它仍然是模糊的。以下是我正在尝试的地方以及我有疑问的地方
PDDocument doc = PDDocument.load(myInputStream);
PDDocumentCatalog catalog = doc.getDocumentCatalog();
InputStream newXMPData = ...; //what goes here? How can I add subject tag?
PDMetadata newMetadata = new PDMetadata(doc, newXMLData, false );
catalog.setMetadata( newMetadata );
//does anything else need to happen to save the document??
//I would like an outputstream of the document (with metadata) so that I can save it to an S3 bucket
答案 0 :(得分:4)
以下代码设置PDF文档的标题,但它也应该适用于其他属性:
public static byte[] insertTitlePdf(byte[] documentBytes, String title) {
try {
PDDocument document = PDDocument.load(documentBytes);
PDDocumentInformation info = document.getDocumentInformation();
info.setTitle(title);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos);
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
需要Apache PDFBox,因此请将其导入到Maven:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.6</version>
</dependency>
添加标题:
byte[] documentBytesWithTitle = insertTitlePdf(documentBytes, "Some fancy title");
使用(JSF示例)在浏览器中显示它:
<object class="pdf" data="data:application/pdf;base64,#{myBean.getDocumentBytesWithTitleAsBase64()}" type="application/pdf">Document could not be loaded</object>
结果(Chrome):
答案 1 :(得分:3)
另一种更简单的方法是使用内置的Document Information对象:
PDDocument inputDoc = // your doc
inputDoc.getDocumentInformation().setCreator("Some meta");
inputDoc.getDocumentInformation().setCustomMetadataValue("fieldName", "fieldValue");
这也有不需要xmpbox库的好处。
答案 2 :(得分:2)
此答案使用xmpbox,来自源代码下载中的AddMetadataFromDocInfo example:
XMPMetadata xmp = XMPMetadata.createXMPMetadata();
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.setDescription("descr");
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(xmp, baos, true);
PDMetadata metadata = new PDMetadata(doc);
metadata.importXMPMetadata(baos.toByteArray());
doc.getDocumentCatalog().setMetadata(metadata);