1. 简介

本文将演示如何 从AsciiDoc文档生成书籍,并通过多种样式选项自定义书籍外观。如果你还不熟悉Java中的AsciiDoc,可以先阅读我们的 AsciiDoctor入门指南

2. 后端书籍类型

使用AsciiDoctorj生成书籍最简单的方式是通过Maven(与之前文章类似),**唯一区别是需要指定 doctype 标签并设置为 *"book"***:

<backend>pdf</backend>
<doctype>book</doctype>

设置doctype后,AsciiDoctorj会识别你要构建书籍,自动创建:

  • 标题页
  • 目录
  • 正文起始页
  • 分部与章节

要实现这些结构,AsciiDoc文档需定义书籍应有的标题、章节等元素。

3. 定义自定义样式

编写书籍时通常需要自定义样式,这可以通过YAML格式的主题文件实现。例如,以下代码定义了书籍页面的基本样式:

page:
    layout: portrait
    margin: [0.75in, 1in, 0.75in, 1in]
    size: A4

✅ 设置为纵向模式
✅ 上下边距0.75英寸,左右边距1英寸
✅ 使用A4纸张格式

还可以自定义页眉页脚:

header:
  height: 0.5in
  line_height: 1
  recto_content:
    center: '{document-title}'
  verso_content:
    center: '{document-title}'

footer:
  height: 0.5in
  line_height: 1
  recto_content:
    right: '{chapter-title} | *{page-number}*'
  verso_content:
    left: '*{page-number}* | {chapter-title}'

⚠️ 奇偶页页眉居中显示文档标题
⚠️ 页脚显示章节标题和页码(奇偶页位置不同)

更多样式选项可参考 AsciiDoctorj GitHub文档

要在生成过程中应用自定义主题,需在pom.xml的attributes部分指定样式文件路径:

<pdf-stylesdir>${project.basedir}/src/themes</pdf-stylesdir>
<pdf-style>custom</pdf-style>

第一行定义样式文件目录,第二行指定文件名(不含扩展名)。

完整配置示例:

<configuration>
    <sourceDirectory>src/docs/asciidoc</sourceDirectory>
    <outputDirectory>target/docs/asciidoc</outputDirectory>
    <attributes>
        <pdf-stylesdir>${project.basedir}/src/themes</pdf-stylesdir>
        <pdf-style>custom</pdf-style>
    </attributes>
    <backend>pdf</backend>
    <doctype>book</doctype>
</configuration>

4. 生成书籍

生成书籍非常简单粗暴,只需在项目目录运行Maven命令。生成的书籍文件位于 target/docs/asciidoctor/ 目录下。

5. 总结

本文展示了如何使用Maven生成带自定义样式的书籍。完整代码示例可在 GitHub仓库 获取,遇到问题可联系作者 book@example.com


原始标题:Generating a Book with Asciidoctor

» 下一篇: Kryo 介绍