元のPDF文書に含まれる文書情報や、しおり、注釈等のインタラクティブ要素(コンテンツ以外の要素)は、インポートされませんが、pCOS 機能を使用すればインタラクティブ要素を取得し、出力 PDF に生成することが可能です。詳しくはテクニカルトピックの
PDF の結合方法でも解説していますので、ご参考ください。
/*
* $Id: split_document.java,v 1.1 2013/01/17 12:58:38 stm Exp $
*
* PDF の分割:
* 複数のページからなる PDF 文書を分割します。
*
* インタラクティブ要素(例:しおり)は失われます。
*
* 必要な製品: PDFlib+PDI/PPS 9
* 必要なデータ: PDF 文書
*/
package com.pdflib.cookbook.pdflib.pdf_import;
import com.pdflib.pdflib;
import com.pdflib.PDFlibException;
public class split_document {
public static void main(String argv[]) {
/* 必要に応じてデータファイルがあるフォルダのパスを指定する */
String searchpath = "../input";
String outfile_basename = "split_document";
String title = "Split PDF Document";
String infile = "PDFlib-datasheet.pdf";
/*
* PDF文書は、いくつかのページを持つそれぞれのPDF出力文書に分割される
*/
final int SUBDOC_PAGES = 2;
pdflib p = null;
try {
p = new pdflib();
p.set_option("searchpath={" + searchpath + "}");
/* load_font() 等でエラーが起きた場合、-1を返す */
p.set_option("errorpolicy=return");
int indoc = p.open_pdi_document(infile, "");
if (indoc == -1)
throw new Exception("Error: " + p.get_errmsg());
/*
* 入力文書のページ数を決定し、出力文書数を計算する
*/
int page_count = (int) p.pcos_get_number(indoc, "length:pages");
int outdoc_count = page_count / SUBDOC_PAGES
+ (page_count % SUBDOC_PAGES > 0 ? 1 : 0);
for (int outdoc_counter = 0, page = 0;
outdoc_counter < outdoc_count; outdoc_counter += 1) {
String outfile = outfile_basename + "_" + (outdoc_counter + 1)
+ ".pdf";
/*
* 出力文書を開く
*/
if (p.begin_document(outfile, "") == -1)
throw new Exception("Error: " + p.get_errmsg());
p.set_info("Creator", "PDFlib Cookbook");
p.set_info("Title", title + " $Revision: 1.1 $");
p.set_info("Subject", "Sub-document " + (outdoc_counter + 1)
+ " of " + outdoc_count + " of input document '" + infile
+ "'");
for (int i = 0; page < page_count && i < SUBDOC_PAGES;
page += 1, i += 1) {
/* ダミーサイズのページ:後で調整する */
p.begin_page_ext(10, 10, "");
int pagehdl = p.open_pdi_page(indoc, page + 1, "");
if (pagehdl == -1)
throw new Exception("Error: " + p.get_errmsg());
/*
* 出力ページ上にインポートしたページを配置し、ページサイズを
* 調整する
*/
p.fit_pdi_page(pagehdl, 0, 0, "adjustpage");
p.close_pdi_page(pagehdl);
p.end_page_ext("");
}
/* 出力文書を閉じる */
p.end_document("");
}
/* 入力文書を閉じる */
p.close_pdi_document(indoc);
}
catch (PDFlibException e) {
System.err.print("PDFlib exception occurred:\n");
System.err.print("[" + e.get_errnum() + "] " + e.get_apiname()
+ ": " + e.get_errmsg() + "\n");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
if (p != null) {
p.delete();
}
}
}
}