/* * 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; int exitcode = 0; 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); 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) { /* ページサイズは fit_pdi_page()で調整される */ p.begin_page_ext(0, 0, "width=a4.width height=a4.height"); 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.println("PDFlib exception occurred:"); System.err.println("[" + e.get_errnum() + "] " + e.get_apiname() + ": " + e.get_errmsg()); exitcode = 1; } catch (Exception e) { System.err.println(e); exitcode = 1; } finally { if (p != null) { p.delete(); } System.exit(exitcode); } } }