インポートした PDF と同じバージョンの PDF を作成
Q.PDF をインポートし、同じ PDF バージョンの PDF を出力したいです。どうすればいいですか?
A.pCOS 関数を使ってインポートする PDF のバージョンを取得し、同じバージョンの PDF ファイルを作成します。
PDFlib では、PDF_begin_document() の compatibility オプションで作成する PDF の PDF バージョンを指定することができます。また、pCOS 関数でインポートする PDF のバージョンを取得することができるので、取得したバージョンを compatibility で指定することでインポートした PDF と同じバージョンの PDF を作成することができます。手順は以下の通りです:
- インポートする PDF を PDF_open_pdi_document() で開く
- pCOS パス pdfversionstring で、PDFlib 関数で使用できる PDF バージョン表記を取得する
- PDF_begin_document() の compatibility オプションで、先ほど取得した PDF バージョン表記を設定する
- 必要なページをインポートし、出力 PDF にコピーする
- テキスト等を重ね、PDF を出力する
PDFlib 9 はデフォルトで PDF 1.7 (ISO-32000-1:2008, Adobe Acrobat 8 相当) の PDF を作成しますが、この手順によりインポートした PDF と同じバージョンの PDF が作成されます。ソースコードは下記の通りです。
/*
* 2018 Copyright (c) infoTek K.K. all rights reserved.
*
* 1番目の引数を PDF ファイルとして読み込み、その1ページ目を
* sample.pdf というファイル名で出力するサンプルプログラムです。
* compatibility を読み込む PDF のバージョンを揃えます。
*/
import com.pdflib.pdflib;
import com.pdflib.PDFlibException;
public class Version {
public static void main(String argv[]) {
pdflib p = null;
int infile_doc, page;
String infile;
String optlist = null;
String version;
String outfile = "sample.pdf";
if(argv.length == 0) {
System.err.println("引数に PDF ファイルを指定してください。");
System.exit(1);
}
try {
infile = argv[0];
p = new pdflib();
p.set_option("errorpolicy=return");
infile_doc = p.open_pdi_document(infile, "");
if (infile_doc == -1) {
throw new Exception("Error: " + p.get_errmsg());
}
version = p.pcos_get_string(infile_doc, "pdfversionstring");
if(version == null) {
System.err.println("PDF バージョンが不正です");
System.exit(1);
}
optlist = "compatibility=" + version;
if (p.begin_document(outfile, optlist) == -1) {
// 通常のエラーに加え、version が PDFlib のサポートしていない
// compatibility 文字列の場合にも失敗します
throw new Exception("Error: " + p.get_errmsg());
}
// 以下は通常の PDF 作成と同様です
int pages = (int)p.pcos_get_number(infile_doc, "length:pages");
for(int i=0; i<pages; i++) {
page = p.open_pdi_page(infile_doc, i+1, "");
if (page == -1) {
throw new Exception("Error: " + p.get_errmsg());
}
p.begin_page_ext(0, 0, "");
p.fit_pdi_page(page, 0, 0, "adjustpage");
/*
* テキスト等を重ねる処理
*/
p.end_page_ext("");
p.close_pdi_page(page);
}
p.end_document("");
p.close_pdi_document(infile_doc);
}
catch (PDFlibException e) {
System.err.print("PDFlib exception occurred in sample:\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();
}
}
}
}
Java 1.7 / PDFlib 9