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

ash*_*ram 6 java jpeg itext

我试图将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)
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Image img = Image.getInstance(path);
Run Code Online (Sandbox Code Playgroud)

path 是图像的完整路径.

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

使用itext读取JPG时过早的EOF

无法从byte []读取JPEG文件

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

这是一个这样的图像的链接

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

Bru*_*gie 7

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

我为你做了这个,结果是:

在此输入图像描述

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

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

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

图像查看器或图像编辑工具(例如GIMP)更加宽容.他们忽略了图像形成不良的事实.对于GIMP,该工具可修复错误,并使您有机会"覆盖"图像以存储修复程序.

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