在itext7中,如何通过增加时间来更改附加文件的显示顺序

时间:2018-05-14 06:05:01

标签: java itext itext7

我想在创建的pdf中更改附件文件顺序,附件默认按名称显示, 如何通过添加时间来更改它们?

这是我的工具方法:

@Override
public boolean attachFile(String src, String dest, List<SysItemfile> attachmentpaths) {
    try {
        PdfName name = new PdfName(src);
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
        List<String> descs = new ArrayList<String>();
        int i = 0;
        int j = 1;
        for (SysItemfile attachmentpath : attachmentpaths) {
            String filename = attachmentpath.getFilename();
            //test for the file name
            System.out.println("filename:"+filename);

            if (descs.contains(attachmentpath.getFilename())) {
                //get the file suffix 
                String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                String realname = filename.substring(0,filename.lastIndexOf("."));
                filename = realname+i+"."+suffix;
                i++;
            } else {
                descs.add(attachmentpath.getFilename());
            }
            PdfFileSpec spec = PdfFileSpec.createEmbeddedFileSpec(pdfDoc, attachmentpath.getFileurl(),
                    filename, filename, name, name);
            // the first parameter is discription
            pdfDoc.addFileAttachment(filename, spec);

        }
        pdfDoc.close();
    } catch (IOException e) {
        logger.error("attachFile unsuccess!");
        logger.error(e.getLocalizedMessage());
        return false;
    }
    return true;
}

之后,当我向我的pdf添加附件时,无法更改附件显示的顺序 我该怎么办?

1 个答案:

答案 0 :(得分:1)

只要您添加附件,PDF标准就不允许规定PDF查看器在显示附件时使用的排序顺序。

另一方面,如果您将PDF设为便携式集合(也称为投资组合),则可以规定架构(即详细列表中的字段)和排序顺序(通过这些领域中的一个或组合。)

您可以非常轻松地将带附件的PDF作为便携式集合,其名称和修改日期按后者排序,如下所示:

try (   PdfReader reader = new PdfReader(...);
        PdfWriter writer = new PdfWriter(...);
        PdfDocument document = new PdfDocument(reader, writer)) {
    PdfCollection collection = new PdfCollection();
    document.getCatalog().setCollection(collection);
    PdfCollectionSchema schema = new PdfCollectionSchema();
    PdfCollectionField field = new PdfCollectionField("File Name", PdfCollectionField.FILENAME);
    field.setOrder(0);
    schema.addField("Name", field);
    field = new PdfCollectionField("Modification Date", PdfCollectionField.MODDATE);
    field.setOrder(1);
    schema.addField("Modified", field);
    collection.setSchema(schema);
    PdfCollectionSort sort = new PdfCollectionSort("Modified");
    collection.setSort(sort);
}

SortAttachments test testAttachLikeGeologistedWithCollection

您甚至可以使用要排序的PdfCollectionField.TEXTPdfCollectionField.DATEPdfCollectionField.NUMBER类型定义自定义字段。您可以通过PdfFileSpec方法在setCollectionItem上设置此类自定义字段的值。