イントロダクション
電子書籍を作成するのにも普通に資料を作成するのにも使用できる。PDFを作成するプログラムを組みたいと思いAspose.PDFを見つけました。
つまるところは、作成したドキュメントをPDFにするプログラムを作ろうと思った次第です。
Aspose.PDF API
まずは使い方を学ぶとして、このチュートリアルをやってみようと思います。
下のコードはこちらにある内容です。細かいところが違いますが、シンプルにPDFファイルを出力しています。出力結果としては、下のようなものが出ました。
public static void main(String[] args) {
Document doc = new Document();
Page page = doc.getPages().add();
page.getParagraphs().add(new TextFragment(
"Hello This is a test"));
doc.save("Hello.pdf");
}
出力した後に赤い文字があるのでそれが、不要です。なので別なものを使用することにしました。
ポールジーグマン
こちらのサイトのEpublibというライブラリがあるので使ってみることにします。
そして、このページにあるコードを実行してみたら、このような出力が得られました。
まともな、物ができたのでよしとしました。実行したコードは下のようなものです。
public static void main(String[] args) {
try {
// Create new Book
Book book = new Book();
Metadata metadata = book.getMetadata();
// Set the title
metadata.addTitle("EPUB4J test book 1");
// Add an Author
metadata.addAuthor(new Author("Joe", "Tester"));
final String ROOT = "src/main/resources";
// Set cover image
book.setCoverImage(
getResource(ROOT + "/book1/test_cover.png", "cover.png"));
// Add Chapter 1
book.addSection("Introduction",
getResource(ROOT + "/book1/chapter1.html", "chapter1.html"));
// Add css file
book.getResources().add(
getResource(ROOT + "/book1/book1.css", "book1.css"));
// Add Chapter 2
TOCReference chapter2 = book.addSection( "Second Chapter",
getResource(ROOT + "/book1/chapter2.html", "chapter2.html"));
// Add image used by Chapter 2
book.getResources().add(
getResource(ROOT + "/book1/flowers_320x240.png", "img/gardening.png"));
// Add Chapter2, Section 1
book.addSection(chapter2, "Chapter 2, section 1",
getResource(ROOT + "/book1/chapter2_1.html", "chapter2_1.html"));
// Add Chapter 3
book.addSection("Conclusion",
getResource(ROOT + "/book1/chapter3.html", "chapter3.html"));
// Create EpubWriter
EpubWriter epubWriter = new EpubWriter();
// Write the Book as Epub
epubWriter.write(book, new FileOutputStream("test1_book1.epub"));
} catch (Exception e) {
e.printStackTrace();
}
}
PDFファイルを出力する
しかし、PDFファイルの出力には、文字コードの設定が必要なのかわかりませんが、ちゃんと出力されませんでした。
実行したコードは下のようなものです。
public static void main(String[] args) throws IOException {
File html = new File(ROOT + "chapter3.html");
org.jsoup.nodes.Document document = Jsoup.parse(html, "UTF-8");
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
File outputPdf = new File("testPdf.pdf");
try (OutputStream outputStream = new FileOutputStream(outputPdf)) {
ITextRenderer renderer = new ITextRenderer();
SharedContext sharedContext = renderer.getSharedContext();
sharedContext.setPrint(true);
sharedContext.setInteractive(false);
renderer.setDocumentFromString(document.html());
renderer.layout();
renderer.createPDF(outputStream);
}
}
半角の文字のみが出力されていました。これはもう少し学習する必要があります。
調査をします。
最終的には、テキストファイルから、PDFにする事ができると良いと思ってます。