Tôi đang cố gắng chèn hình ảnh jpg vào PDF. Một số hình ảnh jpg hoạt động đúng nhưng trong một số trường hợp, tôi nhận được ngoại lệ sau.EOF sớm khi đọc ngoại lệ JPG trong khi viết hình ảnh jpg sang pdf bằng cách sử dụng itext
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)
Dưới đây là mã tôi đang sử dụng.
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;
}
}
Tôi gặp lỗi trên dòng sau trong mã ở trên.
Image img = Image.getInstance(path);
path
là đường dẫn đầy đủ của hình ảnh.
tôi thấy câu hỏi tương tự trên SO
Premature EOF while reading JPG using itext
Failure to read JPEG file from byte[]
Nhưng điều này đã không giải quyết vấn đề của tôi.
Dưới đây là một liên kết đến một trong những hình ảnh như vậy
https://dl.dropboxusercontent.com/u/46349359/image.jpg
Tải lên một trong các tệp JPG của bạn gây ra ngoại lệ. Tôi hy vọng nó sẽ bị phá vỡ theo một cách rất tinh tế. –
@AmedeeVanGasse đã cập nhật các câu hỏi với hình ảnh mẫu. – ashishjmeshram