Skip to content

Instantly share code, notes, and snippets.

@max747
Created May 20, 2011 04:08
Show Gist options
  • Select an option

  • Save max747/982334 to your computer and use it in GitHub Desktop.

Select an option

Save max747/982334 to your computer and use it in GitHub Desktop.
concatenate pdfs (using iText)
import java.io.FileOutputStream;
import java.io.IOException;
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;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
public class PdfJoiner {
public void join(String outputPath, String... inputPaths) {
Document document = null;
PdfCopy copy = null;
try {
for (String inputPath : inputPaths) {
PdfReader reader = new PdfReader(new RandomAccessFileOrArray(inputPath), null); // ここがポイント
reader.consolidateNamedDestinations();
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
copy = new PdfCopy(document, new FileOutputStream(outputPath));
document.open();
}
PdfImportedPage page;
int numberOfPages = reader.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
page = copy.getImportedPage(reader, i);
copy.addPage(page);
}
reader.close();
}
copy.close();
document.close();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (DocumentException e) {
throw new RuntimeException(e);
} finally {
if (document != null) {
document.close();
}
if (copy != null) {
copy.close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment