繁体   English   中英

如何使用java itext为仅包含图像的现有pdf设置属性?

[英]how to set attributes for existing pdf that contains only images using java itext?

在将其上传到服务器之前,我想将属性设置为pdf。

Document document = new Document();
try
{
    OutputStream file = new FileOutputStream({Localpath});
    PdfWriter.getInstance(document, file);
    document.open();

    //Set attributes here
    document.addTitle("TITLE");


    document.close();
    file.close();           
} catch (Exception e)
{
    e.printStackTrace();
} 

但是它不起作用。 该文件已损坏

在对另一个答案的评论中,OP澄清了:

我想将属性设置为现有的pdf(而不是创建新的pdf)

但是,显然,他的代码从头创建了一个新文档(从仅使用FileOutputStream来访问文件,不读,只写的事实中就可以看出)。

要操作现有的PDF,必须使用PdfReader / PdfWriter对。 Bruno Lowagie对堆栈溢出问题“ iText在sandbox.stamper.SuperImpose.java中设置创建日期和修改日期”的 回答中提供了一个示例:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    Map info = reader.getInfo();
    info.put("Title", "New title");
    info.put("CreationDate", new PdfDate().toString());
    stamper.setMoreInfo(info);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XmpWriter xmp = new XmpWriter(baos, info);
    xmp.close();
    stamper.setXmpMetadata(baos.toByteArray());
    stamper.close();
    reader.close();
}

ChangeMetadata.java

如您所见,代码同时在老式的PDF信息字典( stamper.setMoreInfo )和XMP元数据( stamper.setXmpMetadata )中设置了元数据。

显然, srcdest在此处不应相同。

没有第二个文件

在另一条评论中,OP澄清说他已经尝试过类似的解决方案,但是他想防止

临时存在第二个文件

通过首先将原始PDF读取为byte[] ,然后将其标记为目标文件,可以很容易地避免这种情况。 例如,如果File singleFile引用了原始文件(也将其作为目标文件),则可以实现:

byte[] original = Files.readAllBytes(singleFile.toPath());

PdfReader reader = new PdfReader(original);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(singleFile));
Map<String, String> info = reader.getInfo();
info.put("Title", "New title");
info.put("CreationDate", new PdfDate().toString());
stamper.setMoreInfo(info);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XmpWriter xmp = new XmpWriter(baos, info);
xmp.close();
stamper.setXmpMetadata(baos.toByteArray());
stamper.close();
reader.close();

UpdateMetaData测试testChangeTitleWithoutTempFile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM