使用Java中的iText将CCITT Group 3 1-dimensional TIFF转换为PDF

时间:2017-02-06 19:21:16

标签: java pdf itext tiff

尝试使用iText 5.5.10读取tiff文件时遇到如下EOF异常

ExceptionConverter: java.io.EOFException
at com.itextpdf.text.pdf.RandomAccessFileOrArray.readFully(RandomAccessFileOrArray.java:249)
at com.itextpdf.text.pdf.RandomAccessFileOrArray.readFully(RandomAccessFileOrArray.java:241)
at com.itextpdf.text.pdf.codec.TiffImage.getTiffImage(TiffImage.java:209)
at com.itextpdf.text.pdf.codec.TiffImage.getTiffImage(TiffImage.java:314)
at com.itextpdf.text.pdf.codec.TiffImage.getTiffImage(TiffImage.java:302)
at com.itextpdf.text.Image.getInstance(Image.java:428)
at com.itextpdf.text.Image.getInstance(Image.java:374)
at TiffToPdf.main(TiffToPdf.java:137)

我使用的代码是:

    byte[] data = null;
    Image img = null;
    try {
        data = Files.readAllBytes(Paths.get("tiff.tif"));
        img = Image.getInstance(data, true);
    } 
    catch (Exception e) {
       e.printStackTrace();
    }

我尝试过跳过Image步骤并明确使用TiffImage类,但我遇到了同样的错误。

    byte[] data = null;
    Image img = null;
    try {
        data = Files.readAllBytes(Paths.get("tiff.tif"));
        RandomAccessSourceFactory factory = new RandomAccessSourceFactory();
        RandomAccessSource fileBytes = factory.createSource(data);
        RandomAccessFileOrArray s = new RandomAccessFileOrArray(fileBytes);
        img = TiffImage.getTiffImage(s, true, 1, true);
    } 
    catch (Exception e) {
       e.printStackTrace();
    }

我注意到iText中有两个类叫做TIFFFaxDecompressor和TIFFFaxDecoder,但是我还没能在网上找到任何关于如何使用它们的资源。

1 个答案:

答案 0 :(得分:1)

使用您给定的tiff图像,以下代码对我有用,即成功转换为pdf。

    byte[] data = null;
    com.itextpdf.text.Image img = null;
    try {
        //System.out.println(Paths.get("src/main/resources/tiff.tif"));
        data = Files.readAllBytes(Paths.get("src/main/resources/file.tif"));
        RandomAccessSourceFactory factory = new RandomAccessSourceFactory();
        RandomAccessSource fileBytes = factory.createSource(data);
        RandomAccessFileOrArray s = new RandomAccessFileOrArray(fileBytes);

        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("src/main/resources/destination.pdf"));
        document.open();
        int pages = TiffImage.getNumberOfPages(s);
        Image image;
        for (int i = 1; i <= pages; i++) {
            image = TiffImage.getTiffImage(s, i);
            Rectangle pageSize = new Rectangle(image.getWidth(),
                    image.getHeight());
            document.setPageSize(pageSize);
            document.newPage();
            document.add(image);
        }
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }