複雑な PDF の作成
Contents
[
Hide
]
Hello World の例 では、最もシンプルな PDF 作成手順を説明しています。この例では、そのワークフローを基に、グラフィックス、テキスト、表形式のコンテンツを組み合わせた、より複雑なドキュメントを作成します。
Java で、より複雑な PDF ドキュメントを作成するには:
- Document を作成してください。
- Page を追加してください。
page.addImage(...)と対象領域を定義する Rectangle を使用して、Page に画像を追加してください。- 見出し用の TextFragment を作成し、フォント、サイズ、配置、および Position を設定してください。
- 説明段落用に 2 つ目の TextFragment を作成してください。
- 枠線、パディング、およびヘッダーのスタイルを設定した Table を作成してください。
- 生成したスケジュール行を Table に追加してください。
- Table を Page の段落コレクションに追加してください。
- 出力 PDF の Document を保存してください。
次の Java コードは GetStartedExamples.java に基づいています。
public static void complexExample(Path imageFile, Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
page.addImage(imageFile.toString(), new Rectangle(20, 730, 120, 830, true));
TextFragment header = new TextFragment("New ferry routes in Fall 2029");
header.getTextState().setFont(FontRepository.findFont("Arial"));
header.getTextState().setFontSize(24);
header.setHorizontalAlignment(HorizontalAlignment.Center);
header.setPosition(new Position(130, 720));
page.getParagraphs().add(header);
String descriptionText = "Visitors must buy tickets online and tickets are limited to 5,000 per day. "
+ "Ferry service is operating at half capacity and on a reduced schedule. "
+ "Expect lineups.";
TextFragment description = new TextFragment(descriptionText);
description.getTextState().setFont(FontRepository.findFont("Times New Roman"));
description.getTextState().setFontSize(14);
description.setHorizontalAlignment(HorizontalAlignment.Left);
page.getParagraphs().add(description);
page.getParagraphs().add(createScheduleTable());
document.save(outputFile.toString());
}
}
同じ例では、ヘッダーの書式設定と生成された出発時刻を使用してスケジュールテーブルを準備するヘルパーメソッドを使用します。
private static Table createScheduleTable() {
Table table = new Table();
table.setColumnWidths("200 200");
table.setBorder(new BorderInfo(BorderSide.Box, 1.0f, Color.getDarkSlateGray()));
table.setDefaultCellBorder(new BorderInfo(BorderSide.Box, 0.5f, Color.getBlack()));
table.setDefaultCellPadding(new MarginInfo(4.5, 4.5, 4.5, 4.5));
table.getMargin().setBottom(10);
table.getDefaultCellTextState().setFont(FontRepository.findFont("Helvetica"));
Row headerRow = table.getRows().add();
Cell departsCityCell = headerRow.getCells().add("Departs City");
Cell departsIslandCell = headerRow.getCells().add("Departs Island");
styleHeaderCell(departsCityCell);
styleHeaderCell(departsIslandCell);
Duration time = Duration.ofHours(6);
Duration increment = Duration.ofMinutes(30);
for (int index = 0; index < 10; index++) {
Row dataRow = table.getRows().add();
dataRow.getCells().add(formatTime(time));
time = time.plus(increment);
dataRow.getCells().add(formatTime(time));
}
return table;
}