我正在尝试从PDF文件中提取图像。我在网上找到了一个很好的例子:
PdfReader reader;
File file = new File("example.pdf");
reader = new PdfReader(file.getAbsolutePath());
for (int i = 0; i < reader.getXrefSize(); i++) {
PdfObject pdfobj = reader.getPdfObject(i);
if (pdfobj == null || !pdfobj.isStream()) {
continue;
}
PdfStream stream = (PdfStream) pdfobj;
PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
byte[] img = PdfReader.getStreamBytesRaw((PRStream) stream);
FileOutputStream out = new FileOutputStream(new File(file.getParentFile(), String.format("%1$05d", i) + ".jpg"));
out.write(img);
out.flush();
out.close();
}
}
这给了我所有的图像,但图像的顺序错误。我的下一次尝试看起来像这样:
for (int i = 0; i <= reader.getNumberOfPages(); i++) {
PdfDictionary d = reader.getPageN(i);
PdfIndirectReference ir = d.getAsIndirectObject(PdfName.CONTENTS);
PdfObject o = reader.getPdfObject(ir.getNumber());
PdfStream stream = (PdfStream) o;
// rest from example above
}
虽然o.isStream()== true,但我只得到/ Length和/ Filter,并且流只有大约100个字节长。根本找不到图像。
我的问题是以正确的顺序从PDF文件中获取所有图像的正确方法。
答案 0 :(得分:3)
我在其他地方找到了答案,即iText邮件列表。
以下代码适合我 - 请注意我切换到 PdfBox :
PDDocument document = null;
document = PDDocument.load(inFile);
List pages = document.getDocumentCatalog().getAllPages();
Iterator iter = pages.iterator();
while (iter.hasNext()) {
PDPage page = (PDPage) iter.next();
PDResources resources = page.getResources();
Map pageImages = resources.getImages();
if (pageImages != null) {
Iterator imageIter = pageImages.keySet().iterator();
while (imageIter.hasNext()) {
String key = (String) imageIter.next();
PDXObjectImage image = (PDXObjectImage) pageImages.get(key);
image.write2OutputStream(/* some output stream */);
}
}
}