Concatenate PDF files (using iText)Tag(s): IO Open Source
This HowTo is based on the iText package. You need a recent version (ex. 2.*)
This a command line utility. You specify the pdf files to be merge into one.
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PRAcroForm;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.SimpleBookmark;
public class ConcatPDFFiles {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
if (args.length < 2) {
System.out.println
("Usage: ConcatPDFFiles file1.pdf [file2.pdf... fileN.pdf] out.pdf");
System.exit(1);
}
int pageOffset = 0;
ArrayList master = new ArrayList();
int f = 0;
String outFile = args[args.length - 1];
Document document = null;
PdfCopy writer = null;
while (f < args.length - 1) {
PdfReader reader = new PdfReader(args[f]);
reader.consolidateNamedDestinations();
int n = reader.getNumberOfPages();
List bookmarks = SimpleBookmark.getBookmark(reader);
if (bookmarks != null) {
if (pageOffset != 0) {
SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset,
null);
}
master.addAll(bookmarks);
}
pageOffset += n;
if (f == 0) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document,
new FileOutputStream(outFile));
document.open();
}
PdfImportedPage page;
for (int i = 0; i < n;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
PRAcroForm form = reader.getAcroForm();
if (form != null) {
writer.copyAcroForm(reader);
}
f++;
}
if (!master.isEmpty()) {
writer.setOutlines(master);
}
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
See also this HowTo.
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com