package com.pkm.concat.two.pdf;
import java.io.*;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
/**
* Created by pritom on 17/05/2015.
*/
public class ConcatTwoPdfBytes {
public static void main(String[] args) throws Exception {
File file = new File("from-1.pdf");
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Document document = new Document();
Rectangle rectangle = PageSize.A4;
document.setPageSize(rectangle);
PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
PdfContentByte cb = pdfWriter.getDirectContent();
PdfReader pdfReader = new PdfReader(fileInputStream);
for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
document.newPage();
PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
cb.addTemplate(page, 0, 0);
}
File file2 = new File("from-2.pdf");
fileInputStream = new FileInputStream(file2);
pdfReader = new PdfReader(fileInputStream);
for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
document.newPage();
PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
cb.addTemplate(page, 0, 0);
}
document.close();
byte[] bytesRead = byteArrayOutputStream.toByteArray();
File outputFile = new File(file.getName() + " And " + file2.getName());
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
fileOutputStream.write(bytesRead);
fileOutputStream.flush();
fileOutputStream.close();
}
}
Its really helpful
ReplyDelete