将PDF转换为多页tiff(第4组)

时间:2015-08-12 19:00:39

标签: java pdf pdfbox tiff icafe

我正在尝试将org.apache.pdfbox.pdmodel.PDDocument类和icafe库(https://github.com/dragon66/icafe/)所代表的PDF转换为具有第4组压缩和300 dpi的多页tiff。示例代码适用于我288 dpi,但奇怪的是不是300 dpi,导出的tiff仍然只是白色。有谁知道这里的问题是什么?

我在示例中使用的示例pdf位于:http://www.bergophil.ch/a.pdf

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import cafe.image.ImageColorType;
import cafe.image.ImageParam;
import cafe.image.options.TIFFOptions;
import cafe.image.tiff.TIFFTweaker;
import cafe.image.tiff.TiffFieldEnum.Compression;
import cafe.io.FileCacheRandomAccessOutputStream;
import cafe.io.RandomAccessOutputStream;

public class Pdf2TiffConverter {
    public static void main(String[] args) {
        String pdf = "a.pdf";
        PDDocument pddoc = null;
        try {
            pddoc = PDDocument.load(pdf);
        } catch (IOException e) {
        }

        try {
            savePdfAsTiff(pddoc);
        } catch (IOException e) {
        }
    }

    private static void savePdfAsTiff(PDDocument pdf) throws IOException {
        BufferedImage[] images = new BufferedImage[pdf.getNumberOfPages()];
        for (int i = 0; i < images.length; i++) {
            PDPage page = (PDPage) pdf.getDocumentCatalog().getAllPages()
                    .get(i);
            BufferedImage image;
            try {
//              image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 288); //works
                image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300); // does not work
                images[i] = image;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fos = new FileOutputStream("a.tiff");
        RandomAccessOutputStream rout = new FileCacheRandomAccessOutputStream(
                fos);
        ImageParam.ImageParamBuilder builder = ImageParam.getBuilder();
        ImageParam[] param = new ImageParam[1];
        TIFFOptions tiffOptions = new TIFFOptions();
        tiffOptions.setTiffCompression(Compression.CCITTFAX4);
        builder.imageOptions(tiffOptions);
        builder.colorType(ImageColorType.BILEVEL);
        param[0] = builder.build();
        TIFFTweaker.writeMultipageTIFF(rout, param, images);
        rout.close();
        fos.close();
    }
}

或者是否有其他库来编写多页TIFF?

编辑:

感谢dragon66,icafe中的错误现已修复。与此同时,我尝试了其他库,并且还调用了ghostscript。我认为ghostscript非常可靠,因为id是一种广泛使用的工具,另一方面,我必须依赖我的代码的用户有一个ghostscript-installation,如下所示:

   /**
 * Converts a given pdf as specified by its path to an tiff using group 4 compression
 *
 * @param pdfFilePath The absolute path of the pdf
 * @param tiffFilePath The absolute path of the tiff to be created
 * @param dpi The resolution of the tiff
 * @throws MyException If the conversion fails
 */
private static void convertPdfToTiffGhostscript(String pdfFilePath, String tiffFilePath, int dpi) throws MyException {
    // location of gswin64c.exe
    String ghostscriptLoc = context.getGhostscriptLoc();

    // enclose src and dest. with quotes to avoid problems if the paths contain whitespaces
    pdfFilePath = "\"" + pdfFilePath + "\"";
    tiffFilePath = "\"" + tiffFilePath + "\"";

    logger.debug("invoking ghostscript to convert {} to {}", pdfFilePath, tiffFilePath);
    String cmd = ghostscriptLoc + " -dQUIET -dBATCH -o " + tiffFilePath + " -r" + dpi + " -sDEVICE=tiffg4 " + pdfFilePath;
    logger.debug("The following command will be invoked: {}", cmd);

    int exitVal = 0;
    try {
        exitVal = Runtime.getRuntime().exec(cmd).waitFor();
    } catch (Exception e) {
        logger.error("error while converting to tiff using ghostscript", e);
        throw new MyException(ErrorMessages.GHOSTSTSCRIPT_ERROR, e);
    }
    if (exitVal != 0) {
        logger.error("error while converting to tiff using ghostscript, exitval is {}", exitVal);
        throw new MyException(ErrorMessages.GHOSTSTSCRIPT_ERROR);
    }
}

我发现tif中产生的ghostscripttiff icafe产生的tiff强烈不同ghostscript来自{{1}}看起来像灰度一样)

5 个答案:

答案 0 :(得分:8)

问题问题已经有一段时间了,我终于找到了时间和一个精彩的有序抖动矩阵,这让我可以提供一些关于&#34; icafe&#34;可以用来获得与调用外部ghostscript可执行文件相似或更好的结果。一些新功能被添加到&#34; icafe&#34;最近,例如更好的量化和有序抖动算法,在下面的示例代码中使用。

这里我要使用的示例pdf是princeCatalogue。以下大部分代码来自OP,由于包名称更改和更多ImageParam控件设置而发生一些更改。

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import com.icafe4j.image.ImageColorType;
import com.icafe4j.image.ImageParam;
import com.icafe4j.image.options.TIFFOptions;
import com.icafe4j.image.quant.DitherMethod;
import com.icafe4j.image.quant.DitherMatrix;
import com.icafe4j.image.tiff.TIFFTweaker;
import com.icafe4j.image.tiff.TiffFieldEnum.Compression;
import com.icafe4j.io.FileCacheRandomAccessOutputStream;
import com.icafe4j.io.RandomAccessOutputStream;

public class Pdf2TiffConverter {
    public static void main(String[] args) {
        String pdf = "princecatalogue.pdf";
        PDDocument pddoc = null;
        try {
            pddoc = PDDocument.load(pdf);
        } catch (IOException e) {
        }

        try {
            savePdfAsTiff(pddoc);
        } catch (IOException e) {
        }
    }

    private static void savePdfAsTiff(PDDocument pdf) throws IOException {
        BufferedImage[] images = new BufferedImage[pdf.getNumberOfPages()];
        for (int i = 0; i < images.length; i++) {
            PDPage page = (PDPage) pdf.getDocumentCatalog().getAllPages()
                    .get(i);
            BufferedImage image;
            try {
//              image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 288); //works
                image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300); // does not work
                images[i] = image;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fos = new FileOutputStream("a.tiff");
        RandomAccessOutputStream rout = new FileCacheRandomAccessOutputStream(
                fos);
        ImageParam.ImageParamBuilder builder = ImageParam.getBuilder();
        ImageParam[] param = new ImageParam[1];
        TIFFOptions tiffOptions = new TIFFOptions();
        tiffOptions.setTiffCompression(Compression.CCITTFAX4);
        builder.imageOptions(tiffOptions);
        builder.colorType(ImageColorType.BILEVEL).ditherMatrix(DitherMatrix.getBayer8x8Diag()).applyDither(true).ditherMethod(DitherMethod.BAYER);
        param[0] = builder.build();
        TIFFTweaker.writeMultipageTIFF(rout, param, images);
        rout.close();
        fos.close();
    }
}

对于ghostscript,我直接使用命令行和OP提供的相同参数。结果TIFF图像第一页的屏幕截图如下所示:

enter image description here

左侧显示&#34; ghostscript&#34;的输出。右边是&#34; icafe&#34;的输出。可以看出,至少在这种情况下,来自&#34; icafe&#34;优于&#34; ghostscript&#34;的输出。

使用CCITTFAX4压缩,文件大小来自&#34; ghostscript&#34;是2.22M,文件大小来自&#34; icafe&#34;是2.08M。考虑到在创建黑白输出时使用抖动的事实,两者都不是那么好。实际上,不同的压缩算法会创建更小的文件大小。例如,使用LZW,来自&#34; icafe&#34;只有634K,如果使用DEFLATE压缩,输出文件大小下降到582K。

答案 1 :(得分:2)

这里有一些代码可以保存在我使用PDFBox的多页tiff中。它需要来自PDFBox的TIFFUtil class(它不是公开的,因此您必须制作副本)。

void saveAsMultipageTIFF(ArrayList<BufferedImage> bimTab, String filename, int dpi) throws IOException
{
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
    ImageWriter imageWriter = writers.next();

    ImageOutputStream ios = ImageIO.createImageOutputStream(new File(filename));
    imageWriter.setOutput(ios);
    imageWriter.prepareWriteSequence(null);
    for (BufferedImage image : bimTab)
    {
        ImageWriteParam param = imageWriter.getDefaultWriteParam();
        IIOMetadata metadata = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        TIFFUtil.setCompressionType(param, image);
        TIFFUtil.updateMetadata(metadata, image, dpi);
        imageWriter.writeToSequence(new IIOImage(image, null, metadata), param);
    }
    imageWriter.endWriteSequence();
    imageWriter.dispose();
    ios.flush();
    ios.close();
}

我前段时间通过使用此代码对自己进行了实验: https://www.java.net/node/670205(我用解决方案2)

...然而

如果你创建一个包含大量图像的数组,那就是你的内存消耗 真的很高兴。那么渲染图像可能会更好 将它添加到tiff文件,然后渲染下一页并丢失 参考前一个,以便gc可以在需要时获得空间。

答案 2 :(得分:0)

由于解决方案用于此问题的某些依赖项似乎未得到维护。我通过使用最新版本(2.0.16)pdfbox得到了解决方案:

ByteArrayOutputStream imageBaos = new ByteArrayOutputStream();
ImageOutputStream output = ImageIO.createImageOutputStream(imageBaos);
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();

try (final PDDocument document = PDDocument.load(new File("/tmp/tmp.pdf"))) {

            PDFRenderer pdfRenderer = new PDFRenderer(document);

            int pageCount = document.getNumberOfPages();

            BufferedImage[] images = new BufferedImage[pageCount];
            // ByteArrayOutputStream[] baosArray = new ByteArrayOutputStream[pageCount];

            writer.setOutput(output);

            ImageWriteParam params = writer.getDefaultWriteParam();

            params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

            // Compression: None, PackBits, ZLib, Deflate, LZW, JPEG and CCITT
            // variants allowed
            params.setCompressionType("Deflate");

            writer.prepareWriteSequence(null);

            for (int page = 0; page < pageCount; page++) {
                BufferedImage image = pdfRenderer.renderImageWithDPI(page, DPI, ImageType.RGB);
                images[page] = image;
                IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), params);
                writer.writeToSequence(new IIOImage(image, null, metadata), params);
                // ImageIO.write(image, "tiff", baosArray[page]);
            }

            System.out.println("imageBaos size: " + imageBaos.size());
            // Finished write to output

            writer.endWriteSequence();

            document.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            // avoid memory leaks
            writer.dispose();
        }

然后,您可以使用imageBaos写入本地文件。但是,如果您要将图像传递给ByteArrayOutputStream并返回像我这样的私密方法。然后,我们需要其他步骤。

处理完成后,图像字节将在ImageOutputStream output对象中可用。我们需要将偏移量定位到output对象的开头,然后读取脚钉以写入新的ByteArrayOutputStream,这是一种简洁的方法:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
long counter = 0; 
        while (true) {
            try {
                bos.write(ios.readByte());
                counter++;
            } catch (EOFException e) {
                System.out.println("End of Image Stream");
                break;
            } catch (IOException e) {
                System.out.println("Error processing the Image Stream");
                break;
            }
        }
return bos

或者您也可以只ImageOutputStream.flush()最后获得imageBaos字节,然后返回。

答案 3 :(得分:0)

受到Yusaku答案的启发,

我制作了自己的版本,

这可以将多个pdf页面转换为字节数组。

我将pdfbox 2.0.16与imageio-tiff 3.4.2结合使用

//PDF converter to tiff toolbox method.
private byte[] bytesToTIFF(@Nonnull byte[] in) {

        int dpi = 300;
        ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();

        try(ByteArrayOutputStream imageBaos = new ByteArrayOutputStream(255)){

            writer.setOutput(ImageIO.createImageOutputStream(imageBaos));
            writer.prepareWriteSequence(null);

            PDDocument document = PDDocument.load(in);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            ImageWriteParam params = writer.getDefaultWriteParam();

            for (int page = 0; page < document.getNumberOfPages(); page++) {
                BufferedImage image = pdfRenderer.renderImageWithDPI(page, dpi, ImageType.RGB);
                IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), params);
                writer.writeToSequence(new IIOImage(image, null, metadata), params);
            }

            LOG.trace("size found: {}", imageBaos.size());

            writer.endWriteSequence();
            writer.reset();

            return imageBaos.toByteArray();

        } catch (Exception ex) {
            LOG.warn("can't instantiate the bytesToTiff method with: PDF", ex);
        } finally {
            writer.dispose();
        }
}

答案 4 :(得分:0)

有关我的PDFBox实现,请参阅我的github code