如何将多页PDF转换为多页TIFF

时间:2014-09-23 15:11:53

标签: java pdf ghost4j

我正在使用Ghost4j将多页PDF转换为多页TIFF图像。我还没有找到这样做的例子。

使用下面的代码我可以将多页PDF转换成图像但是如何从中创建单个多页TIFF图像?

    PDFDocument lDocument = new PDFDocument();
    lDocument.load(filePath);
    // create renderer
    SimpleRenderer lRenderer = new SimpleRenderer();

    // set resolution (in DPI)
    lRenderer.setResolution(300);

    // render as images
    List<Image> lImages = lRenderer.render(lDocument);
    Iterator<Image> lImageIterator = lImages.iterator();

    //how to convert the images to a single TIFF image?

1 个答案:

答案 0 :(得分:0)

虽然这不是你正在做的事情,但我做了类似的事情。我将一个目录中的多个图像合并到一个带有单独页面的tiff文件中。看看这段代码,看看你是否能找到你需要的东西。此外,您需要外部罐子/库才能使用它们,只需谷歌即可下载。我希望这会对你有所帮助。

public class CombineImages {
    private static String directory = null;
    private static String combinedImageLocation = null;
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private static int folderCount = 0;
    private static int totalFolderCount = 0;

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the directory path that contains the images: ");
        directory = scanner.nextLine(); //initialize directory
        System.out.println("Please enter a location for the new combined images to be placed: ");
        combinedImageLocation = scanner.nextLine(); //initialize directory
        if(!(combinedImageLocation.charAt((combinedImageLocation.length() - 1)) == '\\'))
        {
            combinedImageLocation += "\\";
        }
        if(!(directory.charAt((directory.length() - 1)) == '\\'))
        {
            directory += "\\";
        }
        scanner.close();
        //directory = "C:\\Users\\sorensenb\\Desktop\\CombinePhotos\\";
        //combinedImageLocation = "C:\\Users\\sorensenb\\Desktop\\NewImages\\";
        File filesDirectory;
        filesDirectory = new File(directory);
        File[] files; //holds files in given directory
        if(filesDirectory.exists())
        {
            files = filesDirectory.listFiles();
            totalFolderCount = files.length;
            folderCount = 0;
            if(files != null && (files.length > 0))
            {
                System.out.println("Start Combining Files...");
                System.out.println("Start Time: " + dateFormat.format(new Date()));
                combineImages(files);
                System.out.println("Finished Combining Files.");
                System.out.println("Finish Time: " + dateFormat.format(new Date()));
            }
        }
        else
        {       
            System.out.println("Directory does not exist!");
            System.exit(1);
        }
    }

    public static void combineImages(File[] files)
    {
        int fileCounter = 1;
        ArrayList<String> allFiles = new ArrayList<String>();
        String folderBase = "";
        String parentFolder = "";
        String currentFileName = "";
        String previousFileName = "";
        File previousFile = null;
        int counter = 0;
        for(File file:files)
        {
            if(file.isDirectory())
            {
                folderCount++;
                System.out.println("Folder " + folderCount + " out of " + totalFolderCount + " folders.");
                combineImages(file.listFiles());
            }
            else
            {
                try {
                    folderBase = file.getParentFile().getCanonicalPath();
                    parentFolder = file.getParentFile().getName();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(counter == 0)
                {
                    allFiles.add(file.getName().substring(0, file.getName().indexOf('.')));
                }
                else
                {
                    currentFileName = file.getName();
                    previousFileName = previousFile.getName();
                    currentFileName = currentFileName.substring(0, currentFileName.indexOf('.'));
                    previousFileName = previousFileName.substring(0, previousFileName.indexOf('.'));
                    if(!currentFileName.equalsIgnoreCase(previousFileName))
                    {
                        allFiles.add(currentFileName);
                    }
                }
            }
            previousFile = file;
            counter++;
        }
        System.out.println("Total Files to be Combined: " + allFiles.size());
        for(String currentFile:allFiles)
        {
            System.out.println("File " + fileCounter + " out of " + allFiles.size() + "  CurrentFile: " + currentFile);
            try {
                createNewImage(currentFile, files, folderBase, parentFolder);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            fileCounter++;
        }
    }

    ***public static void createNewImage(String currentFile, File[] files, String folderBase, String parentFolder) throws IOException
    {
        //BufferedImage image;
        int totalHeight = 0;
        int maxWidth = 0;
        int currentHeight = 0;
        ArrayList<String> allFiles = new ArrayList<String>();
        for(File file:files)
        {
            if((file.getName().substring(0, file.getName().indexOf('.'))).equalsIgnoreCase(currentFile))
            {
                allFiles.add(file.getName());
            }
        }
        allFiles = sortFiles(allFiles);
        BufferedImage image[] = new BufferedImage[allFiles.size()];
        SeekableStream ss = null;
        PlanarImage op = null;
        for (int i = 0; i < allFiles.size(); i++) {
            ss = new FileSeekableStream(folderBase + "\\" + allFiles.get(i));
            ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
            op = new NullOpImage(decoder.decodeAsRenderedImage(0), 
                    null, null, OpImage.OP_IO_BOUND);
            image[i] = op.getAsBufferedImage();
        }
        op.dispose();
        ss.close();
        /*BufferedImage convertImage;
        for(int i = 0; i < image.length; i++)
        {
            convertImage = new BufferedImage(image[i].getWidth(),image[i].getHeight(), BufferedImage.TYPE_BYTE_GRAY);
            Graphics g = convertImage.getGraphics();
            g.drawImage(convertImage, 0, 0, null);
            g.dispose();
            image[i] = convertImage;
        }*/
        File folderExists = new File(combinedImageLocation);
        if(!folderExists.exists())
        {
            folderExists.mkdirs();
        }
        TIFFEncodeParam params = new TIFFEncodeParam();
        params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
        int changeName = 1;
        String tempCurrentFile = currentFile;
        while((new File(combinedImageLocation + tempCurrentFile + "Combined.tif").exists()))
        {
            tempCurrentFile = currentFile;
            tempCurrentFile += ("(" + changeName + ")");
            changeName++;
        }
        currentFile = tempCurrentFile;
        OutputStream out = new FileOutputStream(combinedImageLocation + currentFile + "Combined" + ".tif"); 
        ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
        Vector vector = new Vector();   
        for (int i = 1; i < allFiles.size(); i++) {
            vector.add(image[i]); 
        }
        params.setExtraImages(vector.iterator()); 
        encoder.encode(image[0]); 
        for(int i = 0; i < image.length; i++)
        {
            image[i].flush();
        }
        out.close();
        System.gc();
        /*for(String file:allFiles)
        {
            image = ImageIO.read(new File(folderBase, file));
            int w = image.getWidth();
            int h = image.getHeight();
            totalHeight += h;
            if(w > maxWidth)
            {
                maxWidth = w;
            }
            image.flush();
        }
        BufferedImage combined = new BufferedImage((maxWidth), (totalHeight), BufferedImage.TYPE_BYTE_GRAY);
        for(String file:allFiles)
        {
            Graphics g = combined.getGraphics();
            image = ImageIO.read(new File(folderBase, file));
            int h = image.getHeight();
            g.drawImage(image, 0, currentHeight, null);
            currentHeight += h;
            image.flush();
            g.dispose();
        }
        File folderExists = new File(combinedImageLocation + parentFolder + "\\");
        if(!folderExists.exists())
        {
            folderExists.mkdirs();
        }
        ImageIO.write(combined, "TIFF", new File(combinedImageLocation, (parentFolder + "\\" + currentFile + "Combined.tif")));
        combined.flush();
        System.gc();*/
    }***

    public static ArrayList<String> sortFiles(ArrayList<String> allFiles)
    {
        ArrayList<String> sortedFiles = new ArrayList<String>();
        ArrayList<String> numbers = new ArrayList<String>();
        ArrayList<String> letters = new ArrayList<String>();
        for(String currentFile:allFiles)
        {
            try
            {
                Integer.parseInt(currentFile.substring((currentFile.indexOf('.') + 1)));
                numbers.add(currentFile);
            }catch(Exception e)
            {
                letters.add(currentFile);
            }
        }
        //String[] numbersArray = new String[numbers.size()];
        //String[] lettersArray = new String[letters.size()];
        for(int i = 0; i < numbers.size(); i++)
        {
            sortedFiles.add(numbers.get(i));
        }
        for(int i = 0; i < letters.size(); i++)
        {
            sortedFiles.add(letters.get(i));
        }
        return sortedFiles;
    }
}