Contents

使用Asciidoctor生成一本书

1. 简介

在这篇快速文章中,我们将演示如何从 AsciiDoc 文档生成书籍,以及如何使用各种样式选项自定义书籍。

如果您不熟悉 Java 中的 AsciiDoc,可以阅读我们的 AsciiDoctor 简介

2. 后端图书类型

使用 AsciiDoctorj 生成书籍的最简单方法是使用 Maven,就像前面提到的文章中一样。唯一的区别是您必须指定doctype标签并将其设置为“book”*。*

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

通过定义的 doctype,AsciiDoctorj 知道您想要构建一本书,因此它创建:

  • 扉页
  • 目录
  • 正文内容首页
  • 部分和章节

要获得提及的部分,Asciidoc 文档应该定义书名、章节和其他正常的部分。

3.定义自定义样式

在写一本书时,我们很自然地想要使用一些自定义样式。可以使用简单 YAML 文件中定义的 AsciiDoc 特定格式语言来执行此操作。

例如,这段代码将定义一本书中每一页的外观。我们想要在纵向模式下,上下 0.75 英寸的边距,在 A4 纸格式的两侧边距 1 英寸:

page:
    layout: portrait
    margin: [0.75in, 1in, 0.75in, 1in]
    size: 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 的属性部分中指定:

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

第一行定义了我们定义样式的路径,第二行指定了不带扩展名的文件名。

通过这些更改,我们的pom.xml看起来像这样:

<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/*目录中找到。