/*
* This file is part of rockframework.
*
* rockframework 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.
*
* rockframework 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/>;.
*/
package br.net.woodstock.rockframework.document.pdf.itextpdf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import br.net.woodstock.rockframework.core.RockFrameworkVersion;
import br.net.woodstock.rockframework.core.util.Assert;
import br.net.woodstock.rockframework.core.utils.Arrays;
import br.net.woodstock.rockframework.document.DocumentInput;
import br.net.woodstock.rockframework.document.DocumentOutput;
import br.net.woodstock.rockframework.document.DocumentProcessor;
import br.net.woodstock.rockframework.document.pdf.PDFException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
public class MergeProcessor implements DocumentProcessor {
private static final long serialVersionUID = RockFrameworkVersion.VERSION;
public static final String SOURCES_PARAMETER = "sources";
public MergeProcessor() {
super();
}
@Override
@SuppressWarnings("unchecked")
public DocumentOutput process(final DocumentInput input) {
Assert.notNull(input, "input");
try {
Object sources = input.getParameter(MergeProcessor.SOURCES_PARAMETER);
Collection<Object> collection = null;
if (sources == null) {
throw new DocumentException("Parameter 'sources' + must be set");
}
if (Arrays.isArray(sources)) {
collection = Arrays.toList(sources);
} else if (sources instanceof Collection) {
collection = (Collection<Object>) sources;
}
Document document = new Document();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfCopy writer = new PdfCopy(document, outputStream);
document.open();
for (Object source : collection) {
PdfReader reader = IText.read(source);
int pageCount = reader.getNumberOfPages();
for (int i = 1; i <= pageCount; i++) {
PdfImportedPage page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
reader.close();
}
document.close();
writer.close();
return new DocumentOutput(new ByteArrayInputStream(outputStream.toByteArray()));
} catch (IOException e) {
throw new PDFException(e);
} catch (DocumentException e) {
throw new PDFException(e);
}
}
}