问题描述
问题
我正在使用PDFBox 1.8.8来处理现有的PDF文件。保存文档后,输出文件将比原始文件大几倍。这是不可取的。
I am using PDFBox 1.8.8 to manipulate existing PDF files. After saving a document, the output file becomes several times larger than the original. This is undesirable.
如何减少输出文件的文件大小?
How can I reduce the file size of output files?
如何复制我的情况
在下面的代码中,PDFBox只是加载现有的PDF然后保存。没有别的办法。然而,文件大小仍然会变大几倍。
In the following code, PDFBox simply loads an existing PDF and then save it. Nothing else is done. Yet the file size still becomes several times larger.
以下是两个示例输入文件的链接。对于input1.pdf,文件大小从6MB增加到50MB。对于input2.pdf,文件大小从0.4MB增加到1.3MB。
Below are links to two sample input files. For input1.pdf, file size increases from 6MB to 50MB. For input2.pdf, file size increases from 0.4MB to 1.3MB.
import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.exceptions.*;
class Test {
public static void main(String[] args) throws IOException, COSVisitorException {
PDDocument document = PDDocument.load("input1.pdf");
document.save("output.pdf");
document.close();
}
}
我尝试了什么
我尝试使用 addCompression()
PDStream的方法
class,如下面的代码所示。它没有改变任何东西。输出文件大小仍然相同。
I have tried using addCompression()
method of PDStream
class, as in the following code. It does not change anything. Output file size is still the same.
class Test2 {
public static void main(String[] args) throws IOException, COSVisitorException {
PDDocument document = PDDocument.load("input1.pdf");
for (int i = 0; i < document.getNumberOfPages(); i++) {
PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(i);
page.getContents().addCompression();
}
document.save("output.pdf");
document.close();
}
}
推荐答案
我写了这个奇怪的代码,它适用于我():
I wrote this strange code and it works for me (Apache PDFBox v.2.0.8):
private void saveCompressedPDF(PDDocument srcDoc, OutputStream os) throws IOException {
PDDocument outDoc = new PDDocument();
outDoc.setDocumentInformation(srcDoc.getDocumentInformation());
for (PDPage srcPage : srcDoc.getPages()) {
new PDPageContentStream(outDoc, srcPage,
PDPageContentStream.AppendMode.APPEND, true).close();
outDoc.addPage(srcPage);
}
outDoc.save(os);
outDoc.close();
}
这篇关于在PDFBox中,为什么保存后文件大小会变得非常大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!