Skip to content

Instantly share code, notes, and snippets.

@cat-in-136
Created February 17, 2013 01:25
Show Gist options
  • Save cat-in-136/4969586 to your computer and use it in GitHub Desktop.
Save cat-in-136/4969586 to your computer and use it in GitHub Desktop.
PDF concatination with merging the bookmarks
package com.blogspot.catin136.pdfconcatwithbookmark;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BadPdfFormatException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfSmartCopy;
import com.lowagie.text.pdf.SimpleBookmark;
public class PdfConcatWithBookmark {
private Document doc = null;
private PdfCopy copy = null;
private List<HashMap<String,Object>> bookmark = null;
private int numOfPage = 0;
public PdfConcatWithBookmark(OutputStream output) throws DocumentException {
doc = new Document();
copy = new PdfSmartCopy(doc, output);
bookmark = new ArrayList<HashMap<String,Object>>();
copy.setFullCompression();
doc.open();
}
public PdfConcatWithBookmark(String output) throws FileNotFoundException, DocumentException {
this(new FileOutputStream(output));
}
public void addPdfFile(String path) throws BadPdfFormatException, IOException {
PdfReader reader = new PdfReader(path);
List<HashMap<String,Object>> fileBookmark = SimpleBookmark.getBookmark(reader);
SimpleBookmark.shiftPageNumbers(fileBookmark, numOfPage, null);
bookmark.addAll(fileBookmark);
int filePageCount = reader.getNumberOfPages();
for (int page = 1; page <= filePageCount; page++) {
copy.addPage(copy.getImportedPage(reader, page));
numOfPage++;
}
copy.freeReader(reader);
reader.close();
}
public void close() {
copy.setOutlines(bookmark);
doc.close();
}
public static void main(String[] args) throws DocumentException, IOException {
if (args.length >= 2) {
PdfConcatWithBookmark concat = null;
try {
concat = new PdfConcatWithBookmark(args[args.length - 1]);
for (int i = 0; i < args.length - 1; i++) {
concat.addPdfFile(args[i]);
}
} finally {
if (concat != null) {
concat.close();
}
}
} else {
System.out.println("Usage: java -cp ... "
+ PdfConcatWithBookmark.class.getCanonicalName()
+ " input1.pdf input2.pdf ... output.pdf");
System.exit(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment