qasefuzikoのブログ

文章の練習

asciidocで表紙をカスタマイズする

背景

WordやExcel方眼紙(笑)に代わるドキュメントツールとしてAsciidocを試している。Wordで書いていたフォーマットをなるべく踏襲できないかと試行錯誤していたが、PDF変換においてスタイルファイルだけでは表紙のカスタマイズに限度があることがわかった。デフォルトではタイトル、著者名、Revisionなど基本的な要素は触ることができるが、承認欄や付帯事項、Copyrightなど独自の要素を追加することができなかった。

調べてみると表紙は別途WordなりPowerPointなりで作成して後から合成する方法が多くを占めるが、記載する内容はadocで完結したいなぁと。

waku-take-a.github.io

もっと調べてみたら同じことを考えている人はやはりいらっしゃって、pdfのコンバータを拡張することで、かなり自由にカスタマイズできるとのこと。

omnirev.net

上記の記事内でもリンクがあるが、公式のリファレンスにも拡張する方法が記載されていた。

docs.asciidoctor.org

方法

カスタマイズの作り方

公式リファレンスにも同じことが書いてあるけど、適当なrbファイルを作成して、以下の雛形を作成する。

docs.asciidoctor.org

class ExtendedPDFConverter < (Asciidoctor::Converter.for 'pdf')
  register_for 'pdf'
  # ここに色々書いていく
end

adocファイル内に定義した要素:doctitle:は、

title = doc.doctitle

のように参照することができる。 また、独自の要素も参照することができ、例えば製品名としてproduct-nameという要素をadoc内に作った場合、

productName = doc.attr 'product-name'

とすれば、表紙に独自の要素を使用することができる。

表紙に描画する場合、ink_proseメソッドとtextメソッドのいずれかを使用する。ソースを追いかけきれていないけど、前者はasciidocの記法を解釈でき、後者は汎用的に使えるものらしい。公式ドキュメントではink_proseで記載している。

text title, align: :center
ink_prose ProductName , align: :center, margin: 0

表示位置の調整は、相対位置はmove_cursor_tomove_downが使える。位置指定にpage_heightを使用すれば、ページの絶対位置を指定することができる。

move_cursor_to page_height * 0.8
move_down 50

pdfへの変換

作成したrbファイルをasciidoctor-pdfで使用する場合は、コマンドライン-rオプションでrbファイルのパスを指定する。

asciidoctor-pdf ^
    -r ./Style/ext-pdf-convert2.rb ^
    -r ./Style/config.rb ^
    -a scripts=cjk ^
    CustomTitlepage.adoc -o output.pdf

adocファイル

// 表紙
:doctitle: 表紙タイトル
:subtitle: サブタイトル
:author: ◯◯◯◯株式会社▲▲▲▲部
:revnumber: 1
:revdate: 2025/10/12
:product-name: 〇〇システム

:pdf-themesdir: ./Style
:pdf-theme: StyleforPDF.yml
:pdf-fontsdir: ./Font;c:/Windows/Fonts;/usr/share/fonts/custom;GEM_FONTS_DIR
:doctype: book
:encoding: utf-8
:lang: ja

= {doctitle}

Rubyファイル

class PDFConverterCustomTitlePage < (Asciidoctor::Converter.for 'pdf')
    register_for 'pdf'
    def ink_title_page(doc)
        title = doc.doctitle
        subtitle = doc.attr 'subtitle'
        productName = doc.attr 'product-name'
        revdate = doc.attr 'revdate'
        author = doc.author

        move_cursor_to page_height * 0.8
        text title, align: :center, size: 40, leading: 8
        text subtitle, align: :center, size: 32, leading: 8
        ink_prose productName, align: :center,size: 32, margin: 0

        move_cursor_to page_height * 0.4

        ink_prose revdate, align: :center, size: 20, leading: 8
        ink_prose author, align: :center, size: 20, leading: 8 

        move_cursor_to page_height * 0.2
        approval_data = [["承認", "起草"], ["", ""]]
        table(approval_data, width: 100, column_widths: [50] * 3, position: :center) do
            cells.style do |c|
            c.inline_format = true
            c.align = :center
            c.borders = [:top, :bottom, :left, :right] # セルのすべてに罫線を引く
            c.border_width = 1
            end
            row(1).height = 50 # 2行目の高さを高めに設定
        end

    end
end

結果