使用itext将jpg图像写入pdf时读取JPG异常时的过早EOF

时间:2017-06-22 03:49:14

标签: java itext jpeg

我正在尝试将jpg图像插入PDF。一些jpg图像正常工作但在某些情况下我得到以下异常。

java.io.IOException: Premature EOF while reading JPG.
    at com.itextpdf.text.Jpeg.processParameters(Jpeg.java:218)
    at com.itextpdf.text.Jpeg.<init>(Jpeg.java:117)
    at com.itextpdf.text.Image.getInstance(Image.java:279)
    at com.itextpdf.text.Image.getInstance(Image.java:241)
    at com.itextpdf.text.Image.getInstance(Image.java:364)

以下是我正在使用的代码。

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImagesNextToEachOther {

    public static final String DEST = "/home/Documents/pdftest/hello.pdf";

    public static final String IMG1 = "/home/Documents/pdftest/2.jpg";

    public static void main(String[] args) throws IOException,
            DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new ImagesNextToEachOther().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);
        table.addCell(createImageCell(IMG1));
        document.add(table);
        document.close();
    }

    public static PdfPCell createImageCell(String path) throws DocumentException, IOException {
        Image img = Image.getInstance(path);
        PdfPCell cell = new PdfPCell(img, true);
        return cell;
    }
}

我在上面的代码中的以下行收到错误。

Image img = Image.getInstance(path);

path是图片的完整路径。

我在SO上发现了类似的问题

Premature EOF while reading JPG using itext

Failure to read JPEG file from byte[]

但这并没有解决我的问题。

这是指向此类图片之一的链接

https://dl.dropboxusercontent.com/u/46349359/image.jpg

1 个答案:

答案 0 :(得分:7)

正如Amedee在他的评论中已经解释过的那样,JPG已被打破。您可以通过打开GIMP中的图片然后选择File > Overwrite image.jpg来自行检查,GIMP将修复图像,EOF错误将消失。

我已经为你完成了这个,结果是:

enter image description here

如果您下载此图像,并将其与代码一起使用,则不会发生错误。

这对我有什么帮助?你可能会问。 我可以在浏览器中看到图像。我可以在图像查看器中看到图像。为什么不在iText中解决这个问题?

答案很简单:PDF本身支持JPG,这意味着我们可以在PDF中放置所有JPG图像字节的精确副本。但是,在我们这样做之前,iText会对图像进行健全性检查。当这种健全性检查失败时,iText将(并且应该)拒绝该图像,因为包含这样一个&#34;破坏&#34;的PDF的可能性很高。如果我们使用它,图片会显示错误消息。

图像查看器或图像编辑工具(例如GIMP)更宽容。他们忽略了图像形成不良的事实。对于GIMP,该工具可以修复错误,并让您有机会覆盖&#34;覆盖&#34;用于存储修复的图像。

目前还没有计划让iText执行此类修复。我们已经为破坏的TIFF文件提供了这样的修复,但即使这样,默认情况下也是拒绝损坏的图像。如果您希望iText修复损坏的TIFF文件,您必须设置一个标记,因为我们的大多数客户更愿意获得异常,而不是冒着添加自动修复的图像的风险。如果您是iText客户,请随时发布支持请求,以便进行类似的#34;破解图像修复&#34; iText的功能;如果您是iText客户,请随意添加此修复程序,并在AGPL下发布该项修补程序以及项目的其余代码(如您所知,iText&#39; s在大多数情况下,AGPL强制要求您发布项目的完整源代码。)