I am trying to insert jpg image into the PDF. Some jpg images works properly but in some cases I get following exception.
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)
Below is the code I am using.
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;
}
}
I am getting error on the following line in the above code.
Image img = Image.getInstance(path);
path
is the full path of the image.
I found similar question on SO
Premature EOF while reading JPG using itext
Failure to read JPEG file from byte[]
But this did not solve my issue.
Here's a link to one of such image