JODConverterからフォークされたdocuments4jでExcelファイルからpdfファイルを生成する例。
|
documents4jはMS-Excelを使ってPDFを生成する。
したがって、実行環境にMS-Excel(ファイルをPDFとして保存できるバージョン)がインストールされている必要がある。
documents4jには、MS-Excelへのアクセス方法としてLocalConverterとRemoteConverterの2種類がある。
LocalConverterはWindows上で実行し、同じマシン上のMS-Excelを使用する。
RemoteConverterは、Windowsマシンを別に用意し、そのマシン上のMS-Excelを使用する。
documents4jはMavenリポジトリーから取得できる。
Gradleの場合は以下のような感じ。
apply plugin: 'java' apply plugin: 'eclipse' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('com.documents4j:documents4j-local:1.0.3') // LocalConverter compile('com.documents4j:documents4j-client:1.0.3') // RemoteConverter compile('com.documents4j:documents4j-transformer-msoffice-excel:1.0.3') compile('ch.qos.logback:logback-classic:1.1.11') } task wrapper(type: Wrapper) { gradleVersion '4.1' jarFile file('.buildtools/gradlew.jar') }
使用するConverterに応じて、LocalConverterかRemoteConverter(あるいは両方)のライブラリーを指定する。
また、MS-Excelを使うためにtransformer-msoffice-excelも指定する必要がある。
slf4jが入っていないと、実行時に以下のようなログが出力される。
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
logbackを入れておけば(一緒にslf4jも入るので)このログは出なくなる。
logbackの設定ファイルも一緒に作っておけば完璧。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE logback> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <target>System.out</target> <encoder> <pattern>%d{HH:mm:ss} %-5level %msg%n</pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="STDOUT" /> </root> </configuration>
package com.example.d4j; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import com.documents4j.api.DocumentType; import com.documents4j.api.IConverter; import com.documents4j.job.LocalConverter;
public class LocalExample { public static void main(String... args) throws IOException { Path temp = Paths.get("D:/temp/documents4j/temp"); Files.createDirectories(temp); IConverter converter = LocalConverter.builder().baseFolder(temp.toFile()) .workerPool(20, 25, 2, TimeUnit.SECONDS).processTimeout(5, TimeUnit.SECONDS).build(); try { System.out.println("start"); Future<Boolean> conversion = converter .convert(new File("D:/data/dq10/DQ10.xls")).as(DocumentType.MS_EXCEL) .to(new File("D:/temp/documents4j/dq10.pdf")).as(DocumentType.PDF) .schedule(); System.out.println("end: " + conversion.get()); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } finally { converter.shutDown(); } } }
最初にLocalConverterを生成する。
convertメソッドで変換元Excelファイル、toメソッドで出力先ファイルを指定し、scheduleメソッドで実行する。
scheduleメソッドの戻り値はFutureなので、getメソッドで終了まで待つことが出来る。
↓実行例
21:25:24 INFO From-Microsoft-Excel-Converter was started successfully 21:25:24 INFO The documents4j local converter has started successfully start 21:25:24 INFO Requested conversion from D:\data\dq10\DQ10.xls (application/vnd.com.documents4j.any-msexcel) to D:\temp\documents4j\dq10.pdf (application/pdf) end: true 21:25:26 INFO From-Microsoft-Excel-Converter was shut down successfully 21:25:26 INFO The documents4j local converter has shut down successfully
RemoteConverterを使う場合、Converterの生成方法が違うだけで、後はLocalConverterと同じ。
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import com.documents4j.api.IConverter; import com.documents4j.job.RemoteConverter;
Path temp = Paths.get("D:/temp/documents4j/temp");
Files.createDirectories(temp);
IConverter converter = RemoteConverter.builder().baseFolder(temp.toFile())
.workerPool(20, 25, 2, TimeUnit.SECONDS).requestTimeout(10, TimeUnit.SECONDS)
.baseUri("http://localhost:9998").build();
baseUriメソッドでWindowsマシン上のdocuments4jサーバーのURIを指定する。
RemoteConverterを実行するには、Windowsマシン上でdocuments4jサーバーを起動しておく必要がある。
documents4jサーバーを起動するには「documents4j-server-standalone-バージョン-shaded.jar」が必要。
shaded.jarはMavenのサイトからダウンロードできる。
javaコマンドの-jarオプションでshaded.jarファイルを実行するとdocuments4jサーバーが起動する。
引数として、受け付けるURIを指定する。
>java -jar documents4j-server-standalone-1.0.3-shaded.jar http://localhost:9998
Logging: The log is printed to the console
Logging: The log level is set to WARN
Welcome to the documents4j server!
火 9 12 21:55:36 JST 2017: Started server on 'http://localhost:9998'
The documents4j server is up and running. Hit the enter key to shut it down...
コンソール上でEnterキーを押すとdocuments4jサーバーは終了する。
火 9 12 22:04:55 JST 2017: Shutting down server on 'http://localhost:9998' Shut down successful. Goodbye!