我正在使用 PDFBox v2.0.26 修改使用 PrinceXML 生成的現有 PDF,然后與 PDFBox 的 CLI 合并。
之后我想使用 Java 腳本更新 PDF 的元資料,其中包括作者和標題。這不太奏效。當我在后處理后打開 PDF 時,我看不到新的作者和標題資訊,但它在那里(某處),因為當我讀回它時,我得到了新的值。
重現步驟:
- 打開 Adob??e Acrobat Pro DC(我使用的是 2022.002 版本)
- 檔案 > 創建 > 空白頁
- Ctrl D > 輸入作者和標題的單詞(例如“作者在這里”和“標題在這里”)
- 關閉對話并保存檔案
- 運行下面的代碼
- 第一次運行的輸出:
Existing author: author here
Existing title: title here
第二次運行的輸出:
Existing author: My new author
Existing title: My new title
當我在 Acrobat 中打開 PDF 并執行 Ctrl-d 時,我看到:
Title: title here
Author: author here
我錯過了什么?如果我從頭開始創建一個新的 PDF,它會很好地作業,而不是使用現有的 PDF。
我的代碼:
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
public class setTitle {
public static void main(String args[]) throws IOException {
String filepath = "C:\\Temp\\temp.pdf";
//Loading an existing document
File file = new File(filepath);
PDDocument document = PDDocument.load(file);
//Creating the PDDocumentInformation object
PDDocumentInformation pdd = document.getDocumentInformation();
System.out.println("Existing author: " pdd.getAuthor());
System.out.println("Existing title: " pdd.getTitle());
//Setting the author of the document
pdd.setAuthor("My new author");
// Setting the title of the document
pdd.setTitle("My new title");
//Saving the document
document.save("C:/Temp/temp.pdf");
//Closing the document
document.close();
}
}
uj5u.com熱心網友回復:
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDMetadata meta = catalog.getMetadata();
XMPMetadata metadata;
if (meta != null)
{
DomXmpParser xmpParser = new DomXmpParser();
metadata = xmpParser.parse(meta.toByteArray());
}
else
{
meta = new PDMetadata(doc);
catalog.setMetadata(meta);
metadata = XMPMetadata.createXMPMetadata();
}
DublinCoreSchema dcSchema = metadata.getDublinCoreSchema();
if (dcSchema == null)
{
dcSchema = metadata.createAndAddDublinCoreSchema();
}
dcSchema.setTitle(pdd.getTitle());
dcSchema.addCreator(pdd.getAuthor()); // you may want to check whether the author is already there
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(metadata, baos, false);
meta.importXMPMetadata(baos.toByteArray());
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504733.html
