トップ 差分 一覧 ソース 置換 検索 ヘルプ PDF RSS ログイン

iTextを使ってPDF結合する

参考

http://d.hatena.ne.jp/ocs/20110520/1305866658

準備

iTextを準備する。
注意点はバージョンによってライセンスが異なる。
5以降はライセンスが厳しいので、4以前を使うのが無難。
itext-4.2.1.jar(674)

サンプル

参考先のソースをほぼそのまま。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.RandomAccessFileOrArray;


public class test {
  
  public static void main(String[] args) {
    String inFiles[] = new String[args.length - 1];
    System.arraycopy(args, 1, inFiles, 0, inFiles.length);
    connectPDF(args[0], inFiles);
  }
  
  public static void connectPDF(String outputPath, String... inputPaths) {
    Document document = null;
    PdfCopy copy = null;
    PdfReader reader = null;
    
    try {
      for (String inputPath : inputPaths) {
        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();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
      
    } catch (DocumentException e) {
      throw new RuntimeException(e);
      
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (document != null) {
        document.close();
      }
      if (copy != null) {
        copy.close();
      }
    }
  }
}
[カテゴリ: プログラミング言語 > Java]

[通知用URL]



  • Hatenaブックマークに追加
  • livedoorクリップに追加
  • del.icio.usに追加
  • FC2ブックマークに追加

最終更新時間:2016年12月10日 23時35分35秒