将pdf文件转换为tiff

Converting pdf file to tiff

我正在尝试将彩色图像或非图像 PDF 文件转换为多页 tiff 文件。为此,我编写了一些代码,但此代码将 PDF 文件转换为黑白 tiff 文件。我需要 tiff 文件应该是彩色的。那么我应该进行哪些更改才能获得彩色的 tiff 文件。

public void btnConvertToTiffActionPerformed(ActionEvent e) throws InterruptedException {
        final double FAX_RESOLUTION = 200.0;
        final double PRINTER_RESOLUTION = 300.0;
        // This compression type may be wpecific to JAI ImageIO Tools
        final String COMPRESSION_TYPE_GROUP4FAX = "CCITT T.6";
        Iterator<ImageWriter> iterator = ImageIO.getImageWritersByFormatName("tiff");
        if (!iterator.hasNext()) {
            System.out.println(
                "ImageIO missing required plug-in to write TIFF files. " +
                "You can download the JAI ImageIO Tools from: " +
                "https://jai-imageio.dev.java.net/");
            return;
        }
        boolean foundCompressionType = false;
        for(String type : iterator.next().getDefaultWriteParam().getCompressionTypes()) {
            if (COMPRESSION_TYPE_GROUP4FAX.equals(type)) {
                foundCompressionType = true;
                break;
            }
        }
        if (!foundCompressionType) {
            System.out.println(
                "TIFF ImageIO plug-in does not support Group 4 Fax " +
                "compression type ("+COMPRESSION_TYPE_GROUP4FAX+")");
            return;
        }

        Document document = new Document();
        try {
            document.setFile(file.getAbsolutePath());
        } catch (PDFException ex) {
            System.out.println("Error parsing PDF document " + ex);
        } catch (PDFSecurityException ex) {
            System.out.println("Error encryption not supported " + ex);
        } catch (FileNotFoundException ex) {
            System.out.println("Error file not found " + ex);
        } catch (IOException ex) {
            System.out.println("Error handling PDF document " + ex);
        }
        try {
            // save page caputres to file.
            File file = new File("D:\pdfbox\imageCapture.tif");
            ImageOutputStream ios = ImageIO.createImageOutputStream(file);
            ImageWriter writer = ImageIO.getImageWritersByFormatName("tiff").next();
            writer.setOutput(ios);
            // Paint each pages content to an image and write the image to file
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                final double targetDPI = PRINTER_RESOLUTION;
                float scale = 1.0f;
                float rotation = 0f;
                // Given no initial zooming, calculate our natural DPI when
                // printed to standard US Letter paper
                PDimension size = document.getPageDimension(i, rotation, scale);
                double dpi = Math.sqrt((size.getWidth()*size.getWidth()) +
                                       (size.getHeight()*size.getHeight()) ) /
                             Math.sqrt((8.5*8.5)+(11*11));
                // Calculate scale required to achieve at least our target DPI
                if (dpi < (targetDPI-0.1)) {
                    scale = (float) (targetDPI / dpi);
                    size = document.getPageDimension(i, rotation, scale);
                }
                int pageWidth = (int) size.getWidth();
                int pageHeight = (int) size.getHeight();
                int[] cmap = new int[] { 0xFF000000, 0xFFFFFFFF };
                IndexColorModel cm = new IndexColorModel(8, cmap.length, cmap, 0, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
                BufferedImage image = new BufferedImage(
                    pageWidth, pageHeight, BufferedImage.TYPE_BYTE_BINARY, cm);
                Graphics g = image.createGraphics();
                document.paintPage(
                    i, g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX,
                    rotation, scale);
                g.dispose();              
                // capture the page image to file
                IIOImage img = new IIOImage(image, null, null);
                ImageWriteParam param = writer.getDefaultWriteParam();
                param.setCompressionMode(param.MODE_EXPLICIT);
                param.setCompressionType(COMPRESSION_TYPE_GROUP4FAX);
                if (i == 0) {
                    writer.write(null, img, param);
                }
                else {
                    writer.writeInsert(-1, img, param);
                }
                image.flush();
            }            
            ios.flush();
            ios.close();
            writer.dispose();
        }
        catch(IOException ex) {
            System.out.println("Error saving file " + ex);
            ex.printStackTrace();
        }        
        // clean up resources
        document.dispose();
        System.out.println("Done");
    }
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
public void convertToTiff() {
    try {    
        PDDocument document = PDDocument.load(pdf-file path);
        // save page caputres to file.
        File file = new File(D:\pdf);
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        ImageWriter writer = ImageIO.getImageWritersByFormatName("tiff").next();
        writer.setOutput(ios);
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        ImageType imageType = ImageType.RGB;//This can we Gray,ARGB,Binary
        int pageCount = document.getNumberOfPages();

        BufferedImage[] images = new BufferedImage[pageCount];
        writer.setOutput(ios);
        ImageWriteParam params = writer.getDefaultWriteParam();
        params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

        // Compression: None, PackBits, ZLib, Deflate, LZW, JPEG and CCITT
        // variants allowed
        params.setCompressionType(LZW);
        writer.prepareWriteSequence(null);
        // System.out.println(document.getNumberOfPages());

        for (int page = 0; page < document.getNumberOfPages(); page++) {
            BufferedImage image = pdfRenderer.renderImageWithDPI(page,
                    Integer.parseInt("300", imageType);
            images[page] = image;
            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), params);
            writer.writeToSequence(new IIOImage(image, null, metadata), params);

        }
        // clean up resources
        ios.flush();
        ios.close();
        writer.dispose();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(contentPane, ex.getMessage()+"\n"+ ex.getCause());
    }
}

我遇到了类似的情况,可以使用以下库解决

<dependency>
        <groupId>org.icepdf.os</groupId>
        <artifactId>icepdf-core</artifactId>
        <version>6.2.2</version>
    </dependency>

    <dependency>
        <groupId>javax.media</groupId>
        <artifactId>jai_codec</artifactId>
        <version>1.1.3</version>
    </dependency>

Java代码:

  File file = new File("YourTiffFile.tiff");

    Document document = new Document();
    try {
        document.setFile("Path to PDF");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    try {

        Vector<BufferedImage> vector = new Vector<BufferedImage>();
        BufferedImage image = null;
        for (int i = 0; i < document.getNumberOfPages(); i++) {

            image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX,
                    0f, 1.0f);
            vector.add(image);
        }

        TIFFEncodeParam params = new TIFFEncodeParam();
        OutputStream out = new FileOutputStream(file);
        ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);

        params.setExtraImages(vector.listIterator(1));
        params.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
        encoder.encode(vector.get(0));
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    document.dispose();