org.gmdev.pdftrick.engine.MergeFiles.java Source code

Java tutorial

Introduction

Here is the source code for org.gmdev.pdftrick.engine.MergeFiles.java

Source

/*
 * This file is part of the PdfTrick project.
 * Copyright: (C) 2014
 * Author: Gian Luca Mori
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information, please contact Gian Luca Mori at this
 * address: giansluca@gmail.com
 */
package org.gmdev.pdftrick.engine;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.gmdev.pdftrick.factory.PdfTrickFactory;
import org.gmdev.pdftrick.utils.Consts;
import org.gmdev.pdftrick.utils.PdfTrickMessages;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * @author Gian Luca Mori
 */
public class MergeFiles {

    private static final Logger logger = Logger.getLogger(MergeFiles.class);
    private static final PdfTrickFactory factory = PdfTrickFactory.getFactory();

    /**
     * Merge multiple pdf files
     * @param filesVett
     * @param resultFilePath
     * @return The merged file
     */
    public File mergePdf(ArrayList<File> filesVett, String resultFilePath) {
        final HashMap<String, String> namePwd = factory.getNamePwd();

        File mergedFile = new File(resultFilePath);
        List<StreamPwdContainer> list = new ArrayList<StreamPwdContainer>();
        try {
            // Source pdfs
            Iterator<File> ite = filesVett.iterator();
            while (ite.hasNext()) {
                File element = ite.next();
                StreamPwdContainer boom = new StreamPwdContainer();
                boom.setIn(new FileInputStream(element));
                if (namePwd.containsKey(element.getName())) {
                    boom.setPwd(namePwd.get(element.getName()));
                } else {
                    boom.setPwd("");
                }
                list.add(boom);
            }
            // Resulting pdf
            OutputStream out = new FileOutputStream(mergedFile);
            doMerge(list, out);
        } catch (FileNotFoundException e) {
            logger.error("Exception", e);
            PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
        } catch (DocumentException e) {
            logger.error("Exception", e);
            PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
        } catch (IOException e) {
            logger.error("Exception", e);
            PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
        }
        return mergedFile;
    }

    /**
     * Materially multiple pdf files are written merged file on a disk 
     * @param list
     * @param outputStream
     * @throws DocumentException
     * @throws IOException
     */
    private void doMerge(List<StreamPwdContainer> list, OutputStream outputStream)
            throws DocumentException, IOException {
        HashMap<Integer, String> rotationFromPages = factory.getRotationFromPages();
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfContentByte cb = writer.getDirectContent();

        int z = 0;
        for (StreamPwdContainer boom : list) {

            InputStream in = boom.getIn();
            PdfReader reader = null;
            if (!boom.getPwd().equalsIgnoreCase("")) {
                reader = new PdfReader(in, boom.getPwd().getBytes());
            } else {
                reader = new PdfReader(in);
            }

            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                z++;
                int rotation = reader.getPageRotation(i);

                //set size
                Rectangle pageSize_ = reader.getPageSize(i);
                Rectangle pageSize = null;
                if (rotation == 270 || rotation == 90) {
                    pageSize = new Rectangle(pageSize_.getHeight(), pageSize_.getWidth());
                } else {
                    pageSize = pageSize_;
                }

                document.setPageSize(pageSize);
                writer.setCropBoxSize(pageSize);

                document.newPage();

                // import the page from source pdf
                PdfImportedPage page = writer.getImportedPage(reader, i);

                // add the page to the destination pdf
                if (rotation == 270) {
                    cb.addTemplate(page, 0, 1.0f, -1.0f, 0, reader.getPageSizeWithRotation(i).getWidth(), 0);
                    rotationFromPages.put(z, "" + rotation);
                } else if (rotation == 180) {
                    cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0);
                    rotationFromPages.put(z, "" + rotation);
                } else if (rotation == 90) {
                    cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                    rotationFromPages.put(z, "" + rotation);
                } else {
                    cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
            }
            in.close();
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    }

    /**
     * @author Gian Luca Mori
     */
    public class StreamPwdContainer {

        public InputStream in;
        public String pwd;

        /**
         * @return The InputStream of the file
         */
        public InputStream getIn() {
            return in;
        }

        /**
         * @param in
         */
        public void setIn(InputStream in) {
            this.in = in;
        }

        /**
         * @return The password of the file
         */
        public String getPwd() {
            return pwd;
        }

        /**
         * @param pwd
         */
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    }

}