当前位置: 首页 > 知识库问答 >
问题:

如何使用pdfbox或其他java库减小合并PDF/A-1b文件的大小

斜烈
2023-03-14

输入:带有嵌入式字体的(如14)PDF/A-1b文件列表
处理:与ApachePDFBox进行简单合并
结果:1个PDF/A-1b文件,文件大小较大(太大)。(它几乎是所有源文件大小的总和)。

问题:有没有办法减少生成的PDF文件的大小
想法:删除多余的嵌入式字体。但是怎么做呢?这是正确的方法吗?

不幸的是,下面的代码没有完成这项工作,而是突出了明显的问题。

try (PDDocument document = PDDocument.load(new File("E:/tmp/16189_ZU_20181121195111_5544_2008-12-31_Standardauswertung.pdf"))) {
    List<COSName> collectedFonts = new ArrayList<>();
    PDPageTree pages = document.getDocumentCatalog().getPages();
    int pageNr = 0;
    for (PDPage page : pages) {
        pageNr++;
        Iterable<COSName> names = page.getResources().getFontNames();
        System.out.println("Page " + pageNr);
        for (COSName name : names) {
            collectedFonts.add(name);
            System.out.print("\t" + name + " - ");
            PDFont font = page.getResources().getFont(name);
            System.out.println(font + ", embedded: " + font.isEmbedded());
            page.getCOSObject().removeItem(COSName.F);
            page.getResources().getCOSObject().removeItem(name);
        }
    }
    document.save("E:/tmp/output.pdf");
}

代码会产生这样的输出:

Page 1
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 2
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 3
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 4
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 5
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 6
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 7
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 8
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 9
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 10
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 11
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F33} - PDTrueTypeFont ArialMT-BoldItalic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 12
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 13
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true
Page 14
    COSName{F23} - PDTrueTypeFont ArialMT-Bold, embedded: true
    COSName{F25} - PDTrueTypeFont ArialMT-Italic, embedded: true
    COSName{F27} - PDTrueTypeFont ArialMT-Regular, embedded: true

任何感激的帮助...

共有3个答案

阴高寒
2023-03-14

我发现的另一种方法是以这种方式使用ITEXT 7(pdfWriter.setSmartMode):

    try (PdfWriter pdfWriter = new PdfWriter(out)) {
        pdfWriter.setSmartMode(true); // Here happens the optimation, e.g. reducing redundantly embedded fonts
        pdfWriter.setCompressionLevel(Deflater.BEST_COMPRESSION);
        try (PdfDocument pdfDoc = new PdfADocument(pdfWriter, PdfAConformanceLevel.PDF_A_1B,
                new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", colorProfile))) {
            PdfMerger merger = new PdfMerger(pdfDoc);
            merger.setCloseSourceDocuments(true);
            try {
                for (InputStream pdf : pdfs) {
                    try (PdfDocument doc = new PdfDocument(new PdfReader(pdf))) {
                        merger.merge(doc, createPageList(doc.getNumberOfPages()));
                    }
                }
                merger.close();
            }
            catch (com.itextpdf.kernel.crypto.BadPasswordException e) {
                throw new BieneException("Konkatenierung eines passwortgeschützten PDF-Dokumentes nicht möglich: " + e.getMessage(),
                        e);
            }
            catch (com.itextpdf.io.IOException | PdfException e) {
                throw new BieneException(e.getMessage(), e);
            }
        }
    }
龚弘业
2023-03-14

在文件中调试时,我发现相同字体的字体文件被多次引用。因此,用已经查看过的字体文件项替换字典中的实际字体文件项,删除引用并可以进行压缩。这样,我就可以把一个30 MB的文件缩小到大约6 MB。

    File file = new File("test.pdf");

    PDDocument doc = PDDocument.load(file);
    Map<String, COSBase> fontFileCache = new HashMap<>();
    for (int pageNumber = 0; pageNumber < doc.getNumberOfPages(); pageNumber++) {
        final PDPage page = doc.getPage(pageNumber);
        COSDictionary pageDictionary = (COSDictionary) page.getResources().getCOSObject().getDictionaryObject(COSName.FONT);
        for (COSName currentFont : pageDictionary.keySet()) {
            COSDictionary fontDictionary = (COSDictionary) pageDictionary.getDictionaryObject(currentFont);
            for (COSName actualFont : fontDictionary.keySet()) {
                COSBase actualFontDictionaryObject = fontDictionary.getDictionaryObject(actualFont);
                if (actualFontDictionaryObject instanceof COSDictionary) {
                    COSDictionary fontFile = (COSDictionary) actualFontDictionaryObject;
                    if (fontFile.getItem(COSName.FONT_NAME) instanceof COSName) {
                        COSName fontName = (COSName) fontFile.getItem(COSName.FONT_NAME);
                        fontFileCache.computeIfAbsent(fontName.getName(), key -> fontFile.getItem(COSName.FONT_FILE2));
                        fontFile.setItem(COSName.FONT_FILE2, fontFileCache.get(fontName.getName()));
                    }
                }
            }
        }
    }

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    doc.save(baos);
    final File compressed = new File("test_compressed.pdf");
    baos.writeTo(new FileOutputStream(compressed));

也许这不是最优雅的方法,但它的工作原理和保持PDF/1b兼容性。

伏子辰
2023-03-14

这个答案中的代码试图优化像OP的示例文档这样的文档,即包含完全相同的对象副本的文档,在手头的情况下是完全相同的、完全嵌入的字体。它不会仅仅合并几乎相同的对象,例如将相同字体的多个子集合并到一个单一的联合子集中。

在对问题的评论过程中,很明显,OP的PDF中的重复字体确实是源字体文件的完全相同的副本。要合并这些重复的对象,必须收集文档的复杂对象(数组、字典、流),将它们相互比较,然后合并重复的对象。

对于大型文档,文档中所有复杂对象的实际成对比较可能会花费太多时间,因此下面的代码计算这些对象的散列,并仅比较具有相同散列的对象。

要合并重复项,代码将选择其中一个重复项,并将对任何其他重复项的所有引用替换为对所选重复项的引用,从而从文档对象池中删除其他重复项。为了更有效地执行此操作,代码最初不仅收集所有复杂对象,还收集对每个对象的所有引用。

这是用来优化PDDocument的方法:

public void optimize(PDDocument pdDocument) throws IOException {
    Map<COSBase, Collection<Reference>> complexObjects = findComplexObjects(pdDocument);
    for (int pass = 0; ; pass++) {
        int merges = mergeDuplicates(complexObjects);
        if (merges <= 0) {
            System.out.printf("Pass %d - No merged objects\n\n", pass);
            break;
        }
        System.out.printf("Pass %d - Merged objects: %d\n\n", pass, merges);
    }
}

(测试中的OptimizeAfterMerge方法)

优化采用多个过程,因为只有在合并它们引用的重复项后才能识别某些对象的相等性。

以下帮助器方法和类收集PDF的复杂对象以及对每个对象的引用:

Map<COSBase, Collection<Reference>> findComplexObjects(PDDocument pdDocument) {
    COSDictionary catalogDictionary = pdDocument.getDocumentCatalog().getCOSObject();
    Map<COSBase, Collection<Reference>> incomingReferences = new HashMap<>();
    incomingReferences.put(catalogDictionary, new ArrayList<>());

    Set<COSBase> lastPass = Collections.<COSBase>singleton(catalogDictionary);
    Set<COSBase> thisPass = new HashSet<>();
    while(!lastPass.isEmpty()) {
        for (COSBase object : lastPass) {
            if (object instanceof COSArray) {
                COSArray array = (COSArray) object;
                for (int i = 0; i < array.size(); i++) {
                    addTarget(new ArrayReference(array, i), incomingReferences, thisPass);
                }
            } else if (object instanceof COSDictionary) {
                COSDictionary dictionary = (COSDictionary) object;
                for (COSName key : dictionary.keySet()) {
                    addTarget(new DictionaryReference(dictionary, key), incomingReferences, thisPass);
                }
            }
        }
        lastPass = thisPass;
        thisPass = new HashSet<>();
    }
    return incomingReferences;
}

void addTarget(Reference reference, Map<COSBase, Collection<Reference>> incomingReferences, Set<COSBase> thisPass) {
    COSBase object = reference.getTo();
    if (object instanceof COSArray || object instanceof COSDictionary) {
        Collection<Reference> incoming = incomingReferences.get(object);
        if (incoming == null) {
            incoming = new ArrayList<>();
            incomingReferences.put(object, incoming);
            thisPass.add(object);
        }
        incoming.add(reference);
    }
}

说明:OptimizeAfterMerge辅助方法findComplexObjectaddTarget

interface Reference {
    public COSBase getFrom();

    public COSBase getTo();
    public void setTo(COSBase to);
}

static class ArrayReference implements Reference {
    public ArrayReference(COSArray array, int index) {
        this.from = array;
        this.index = index;
    }

    @Override
    public COSBase getFrom() {
        return from;
    }

    @Override
    public COSBase getTo() {
        return resolve(from.get(index));
    }

    @Override
    public void setTo(COSBase to) {
        from.set(index, to);
    }

    final COSArray from;
    final int index;
}

static class DictionaryReference implements Reference {
    public DictionaryReference(COSDictionary dictionary, COSName key) {
        this.from = dictionary;
        this.key = key;
    }

    @Override
    public COSBase getFrom() {
        return from;
    }

    @Override
    public COSBase getTo() {
        return resolve(from.getDictionaryObject(key));
    }

    @Override
    public void setTo(COSBase to) {
        from.setItem(key, to);
    }

    final COSDictionary from;
    final COSName key;
}

(OptimizeAfterMerge帮助接口参考与实现Array参考Dictionary参考

以下帮助器方法和类最终会识别和合并重复项:

int mergeDuplicates(Map<COSBase, Collection<Reference>> complexObjects) throws IOException {
    List<HashOfCOSBase> hashes = new ArrayList<>(complexObjects.size());
    for (COSBase object : complexObjects.keySet()) {
        hashes.add(new HashOfCOSBase(object));
    }
    Collections.sort(hashes);

    int removedDuplicates = 0;
    if (!hashes.isEmpty()) {
        int runStart = 0;
        int runHash = hashes.get(0).hash;
        for (int i = 1; i < hashes.size(); i++) {
            int hash = hashes.get(i).hash;
            if (hash != runHash) {
                int runSize = i - runStart;
                if (runSize != 1) {
                    System.out.printf("Equal hash %d for %d elements.\n", runHash, runSize);
                    removedDuplicates += mergeRun(complexObjects, hashes.subList(runStart, i));
                }
                runHash = hash;
                runStart = i;
            }
        }
        int runSize = hashes.size() - runStart;
        if (runSize != 1) {
            System.out.printf("Equal hash %d for %d elements.\n", runHash, runSize);
            removedDuplicates += mergeRun(complexObjects, hashes.subList(runStart, hashes.size()));
        }
    }
    return removedDuplicates;
}

int mergeRun(Map<COSBase, Collection<Reference>> complexObjects, List<HashOfCOSBase> run) {
    int removedDuplicates = 0;

    List<List<COSBase>> duplicateSets = new ArrayList<>();
    for (HashOfCOSBase entry : run) {
        COSBase element = entry.object;
        for (List<COSBase> duplicateSet : duplicateSets) {
            if (equals(element, duplicateSet.get(0))) {
                duplicateSet.add(element);
                element = null;
                break;
            }
        }
        if (element != null) {
            List<COSBase> duplicateSet = new ArrayList<>();
            duplicateSet.add(element);
            duplicateSets.add(duplicateSet);
        }
    }

    System.out.printf("Identified %d set(s) of identical objects in run.\n", duplicateSets.size());

    for (List<COSBase> duplicateSet : duplicateSets) {
        if (duplicateSet.size() > 1) {
            COSBase surviver = duplicateSet.remove(0);
            Collection<Reference> surviverReferences = complexObjects.get(surviver);
            for (COSBase object : duplicateSet) {
                Collection<Reference> references = complexObjects.get(object);
                for (Reference reference : references) {
                    reference.setTo(surviver);
                    surviverReferences.add(reference);
                }
                complexObjects.remove(object);
                removedDuplicates++;
            }
            surviver.setDirect(false);
        }
    }

    return removedDuplicates;
}

boolean equals(COSBase a, COSBase b) {
    if (a instanceof COSArray) {
        if (b instanceof COSArray) {
            COSArray aArray = (COSArray) a;
            COSArray bArray = (COSArray) b;
            if (aArray.size() == bArray.size()) {
                for (int i=0; i < aArray.size(); i++) {
                    if (!resolve(aArray.get(i)).equals(resolve(bArray.get(i))))
                        return false;
                }
                return true;
            }
        }
    } else if (a instanceof COSDictionary) {
        if (b instanceof COSDictionary) {
            COSDictionary aDict = (COSDictionary) a;
            COSDictionary bDict = (COSDictionary) b;
            Set<COSName> keys = aDict.keySet();
            if (keys.equals(bDict.keySet())) {
                for (COSName key : keys) {
                    if (!resolve(aDict.getItem(key)).equals(bDict.getItem(key)))
                        return false;
                }
                // In case of COSStreams we strictly speaking should
                // also compare the stream contents here. But apparently
                // their hashes coincide well enough for the original
                // hashing equality, so let's just assume...
                return true;
            }
        }
    }
    return false;
}

static COSBase resolve(COSBase object) {
    while (object instanceof COSObject)
        object = ((COSObject)object).getObject();
    return object;
}

(OptimizeAfterMerge帮助器方法mergeDuplicatesmergeRun等于,和解决

static class HashOfCOSBase implements Comparable<HashOfCOSBase> {
    public HashOfCOSBase(COSBase object) throws IOException {
        this.object = object;
        this.hash = calculateHash(object);
    }

    int calculateHash(COSBase object) throws IOException {
        if (object instanceof COSArray) {
            int result = 1;
            for (COSBase member : (COSArray)object)
                result = 31 * result + member.hashCode();
            return result;
        } else if (object instanceof COSDictionary) {
            int result = 3;
            for (Map.Entry<COSName, COSBase> entry : ((COSDictionary)object).entrySet())
                result += entry.hashCode();
            if (object instanceof COSStream) {
                try (   InputStream data = ((COSStream)object).createRawInputStream()   ) {
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    byte[] buffer = new byte[8192];
                    int bytesRead = 0;
                    while((bytesRead = data.read(buffer)) >= 0)
                        md.update(buffer, 0, bytesRead);
                    result = 31 * result + Arrays.hashCode(md.digest());
                } catch (NoSuchAlgorithmException e) {
                    throw new IOException(e);
                }
            }
            return result;
        } else {
            throw new IllegalArgumentException(String.format("Unknown complex COSBase type %s", object.getClass().getName()));
        }
    }

    final COSBase object;
    final int hash;

    @Override
    public int compareTo(HashOfCOSBase o) {
        int result = Integer.compare(hash,  o.hash);
        if (result == 0)
            result = Integer.compare(hashCode(), o.hashCode());
        return result;
    }
}

(优化合并帮助器类hashofcbase

OP的示例文档大小约为6.5MB。像这样应用上面的代码

PDDocument pdDocument = PDDocument.load(SOURCE);

optimize(pdDocument);

pdDocument.save(RESULT);

导致PDF小于700 KB的大小,它似乎是完整的。

(如果丢失了什么,请告诉我,我会设法修复的。)

一方面,此优化器不会识别所有相同的重复项。特别是在循环引用的情况下,不会识别对象的重复圆,因为代码仅在重复对象圆的内容相同时才识别重复对象,而重复对象圆中通常不会出现这种情况。

另一方面,在某些情况下,这个优化器可能已经过于急切了,因为PDF查看器可能需要一些重复的对象作为单独的对象来接受每个实例作为单独的实体。

此外,该程序还涉及文件中的各种对象,甚至是定义PDF内部结构的对象,但它不会尝试更新管理此结构的任何PDFBox类(PDDocumentPDDocumentCatalogPDAcroForm,…)。为了不让任何挂起的更改破坏整个文档,因此,请仅将此程序应用于新加载的、未修改PDDocument实例,然后立即保存,无需进一步ado。

 类似资料:
  • 问题内容: 输入 :包含嵌入式字体的(例如14个)PDF / A-1b文件列表。 处理 :与Apache PDFBOX进行简单合并。 结果 :1个PDF / A-1b文件,文件大小太大(太大)。(这几乎是所有源文件大小的总和)。 问题 :是否可以减小生成的PDF的文件大小? 想法 :删除多余的嵌入式字体。但是如何?这是正确的做法吗? 不幸的是,以下代码无法完成任务,但突出了明显的问题。 该代码产生

  • 使用PDFBox可以读取livecycle创建的动态PDF。下面的代码读取然后写回用于创建动态PDF的xml文件。我有点担心,因为生成的文件很大,从647kb pdf开始。新的pdf 14000kb。任何人都知道如何减少生成的新文件的大小。写回pdf文件时可以设置某种类型的压缩吗?

  • 我有一个大的pdf打印文件,它包含5544页,大约36MB大小。该文件由MS Word 2010创建,仅包含文本和每个信件/文档上的徽标。 我将它拆分为5544个文件,然后根据关键字合并成2770个字母。每个字母约为。140-145kb。 当我将所有的字母合并到一个新的pdf打印文件(仍然包含5544页)时,文件的大小增长到396MB。 所有文本提取、拆分和合并都是通过从PHP调用Apache P

  • 在jasper-report中生成PDF/A包含许多缺陷,并且在某些版本的jasper-report中不受支持。这就是为什么我决定传递这篇问答文章的原因,它指出了将一个带有图形的简单报表导出到PDF/a所必需的步骤和库版本 示例数据(usersrep.csv) 如果将报告导出为pdf,我需要做什么来生成pdf/A-1A?

  • 问题内容: SO和Web上的大多数问题/答案都讨论了如何使用Hive将一堆小的ORC文件组合成一个更大的文件,但是,我的ORC文件是日志文件,每天都分开,因此我需要将它们分开。我只想每天“汇总” ORC文件(它们是HDFS中的目录)。 我最有可能需要用Java编写解决方案,并且遇到过OrcFileMergeOperator,这可能是我需要使用的内容,但还为时过早。 解决此问题的最佳方法是什么? 问

  • 问题内容: 如果要优化PDF文件并减小文件大小,Ghostscript是最好的选择吗? 我需要存储大量PDF文件,因此我需要尽可能地优化和减小文件大小 是否有人对Ghostscript和/或其他有任何经验? 问题答案: 如果您正在寻找免费(如“自由”)软件,那么Ghostscript无疑是您的最佳选择。但是,它并不总是易于使用-它的某些(非常强大的)处理选项不容易找到文档。 看看这个答案,它解释了