以下の内容はhttps://kazuhira-r.hatenablog.com/entry/2026/02/14/161812より取得しました。


JavadocをPandocでMarkdownに変換してみる

これは、なにをしたくて書いたもの?

JavadocをMarkdownに変換したら、どういう感じになるのかな?と思って、変換方法を調べてみました。

こういう時にはPandocがよく使われるようなので、試してみたいと思います。

Pandoc

PandocのWebサイトはこちら。

Pandoc - index

Pandocはあるマークアップ形式から別のマークアップ形式に変換するツールです。

のように挙げればキリがなく、どのようなマークアップが連ねられているかはPandocのトップページを確認してください。

またオプションのフォーマット指定も見るとよいでしょう。

Pandoc User’s Guide / Options / General options

使い方はデモページを見るのがよいでしょう。

Pandoc - Demos

今回はJavadocをMarkdownに変換してみたいというのが目的なので、あまりPandoc自体には踏み込みません。

環境

今回の環境はこちら。

$ java --version
openjdk 25.0.2 2026-01-20
OpenJDK Runtime Environment (build 25.0.2+10-Ubuntu-124.04)
OpenJDK 64-Bit Server VM (build 25.0.2+10-Ubuntu-124.04, mixed mode, sharing)


$ mvn --version
Apache Maven 3.9.12 (848fbb4bf2d427b72bdb2471c22fced7ebd9a7a1)
Maven home: $HOME/.sdkman/candidates/maven/current
Java version: 25.0.2, vendor: Ubuntu, runtime: /usr/lib/jvm/java-25-openjdk-amd64
Default locale: ja_JP, platform encoding: UTF-8
OS name: "linux", version: "6.8.0-100-generic", arch: "amd64", family: "unix"

OSはUbuntu Linux 24.04 LTSです。

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 24.04.4 LTS
Release:        24.04
Codename:       noble


$ uname -srvmpio
Linux 6.8.0-100-generic #100-Ubuntu SMP PREEMPT_DYNAMIC Tue Jan 13 16:40:06 UTC 2026 x86_64 x86_64 x86_64 GNU/Linux

Pandocをインストールする

まずはPandocをインストールしましょう。

Ubuntu Linux 24.04 LTSであればaptでインストールできます。

$ apt show pandoc
Package: pandoc
Version: 3.1.3+ds-2
Priority: optional
Section: universe/text
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Debian Haskell Group <debian-haskell@lists.debian.org>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 199 MB
Provides: pandoc-abi (= 1.23.1-1)
Depends: pandoc-data (<< 3.1.3.~), pandoc-data (>= 3.1.3), libc6 (>= 2.38), libffi8 (>= 3.4), libgmp10 (>= 2:6.3.0+dfsg), liblua5.4-0 (>= 5.4.6), libyaml-0-2, zlib1g (>= 1:1.1.4)
Suggests: texlive-latex-recommended, texlive-xetex, texlive-luatex, pandoc-citeproc, texlive-latex-extra, context, wkhtmltopdf, librsvg2-bin, groff, ghc, nodejs, php, perl, python, ruby, r-base-core, libjs-mathjax, libjs-katex, citation-style-language-styles
Homepage: https://pandoc.org/
Download-Size: 26.9 MB
APT-Sources: http://archive.ubuntu.com/ubuntu noble/universe amd64 Packages
Description: general markup converter
 Pandoc is a Haskell library for converting
 from one markup format to another,
 and a command-line tool that uses this library.
 The formats it can handle include
  * light markup formats
    (many variants of Markdown, reStructuredText, AsciiDoc,
     Org-mode, Muse, Textile, txt2tags)
  * HTML formats (HTML 4 and 5)
  * Ebook formats (EPUB v2 and v3, FB2)
  * Documentation formats (GNU TexInfo, Haddock)
  * Roff formats (man, ms)
  * TeX formats (LaTeX, ConTeXt)
  * Typst
  * XML formats
    (DocBook 4 and 5, JATS, TEI Simple, OpenDocument)
  * Outline formats (OPML)
  * Bibliography formats (BibTeX, BibLaTeX, CSL JSON, CSL YAML, RIS)
  * Word processor formats (Docx, RTF, ODT)
  * Interactive notebook formats (Jupyter notebook ipynb)
  * Page layout formats (InDesign ICML)
  * Wiki markup formats
    (MediaWiki, DokuWiki, TikiWiki, TWiki,
     Vimwiki, XWiki, ZimWiki, Jira wiki, Creole)
  * Slide show formats
    (LaTeX Beamer, PowerPoint, Slidy,
     reveal.js, Slideous, S5, DZSlides)
  * Data formats (CSV and TSV tables)
  * PDF (via external programs such as pdflatex or wkhtmltopdf)
 .
 Pandoc can convert mathematical content in documents
 between TeX, MathML, Word equations, roff eqn, typst,
 and plain text.
 It includes a powerful system
 for automatic citations and bibliographies,
 and it can be customized extensively using templates, filters,
 and custom readers and writers written in Lua.
 .
 This package contains the pandoc tool.
 .
 Some uses of Pandoc require additional packages:
  * SVG content in PDF output requires librsvg2-bin.
  * YAML metadata in TeX-related output requires texlive-latex-extra.
  * *.hs filters not set executable requires ghc.
  * *.js filters not set executable requires nodejs.
  * *.php filters not set executable requires php.
  * *.pl filters not set executable requires perl.
  * *.py filters not set executable requires python.
  * *.rb filters not set executable requires ruby.
  * *.r filters not set executable requires r-base-core.
  * LaTeX output, and PDF output via PDFLaTeX,
    require texlive-latex-recommended.
  * XeLaTeX output, and PDF output via XeLaTeX, require texlive-xetex.
  * LuaTeX output, and PDF output via LuaTeX, require texlive-luatex.
  * ConTeXt output, and PDF output via ConTeXt, require context.
  * PDF output via wkhtmltopdf requires wkhtmltopdf.
  * Roff man and roff ms output, and PDF output via roff ms,
    require groff.
  * MathJax-rendered equations require libjs-mathjax.
  * KaTeX-rendered equations require node-katex.
  * option --csl may use styles in citation-style-language-styles.

最新バージョンではないのですが、まあよいでしょう。

インストール。

$ sudo apt install pandoc

バージョン。

$ pandoc --version
pandoc 3.1.3
Features: -server +lua
Scripting engine: Lua 5.4
User data directory: /home/vagrant/.local/share/pandoc
Copyright (C) 2006-2023 John MacFarlane. Web: https://pandoc.org
This is free software; see the source for copying conditions. There is no
warranty, not even for merchantability or fitness for a particular purpose.

ヘルプ。

$ pandoc --help
pandoc [OPTIONS] [FILES]
  -f FORMAT, -r FORMAT  --from=FORMAT, --read=FORMAT
  -t FORMAT, -w FORMAT  --to=FORMAT, --write=FORMAT
  -o FILE               --output=FILE
                        --data-dir=DIRECTORY
  -M KEY[:VALUE]        --metadata=KEY[:VALUE]
                        --metadata-file=FILE
  -d FILE               --defaults=FILE
                        --file-scope
                        --sandbox
  -s                    --standalone
                        --template=FILE
  -V KEY[:VALUE]        --variable=KEY[:VALUE]
                        --wrap=auto|none|preserve
                        --ascii
                        --toc, --table-of-contents
                        --toc-depth=NUMBER
  -N                    --number-sections
                        --number-offset=NUMBERS
                        --top-level-division=section|chapter|part
                        --extract-media=PATH
                        --resource-path=SEARCHPATH
  -H FILE               --include-in-header=FILE
  -B FILE               --include-before-body=FILE
  -A FILE               --include-after-body=FILE
                        --no-highlight
                        --highlight-style=STYLE|FILE
                        --syntax-definition=FILE
                        --dpi=NUMBER
                        --eol=crlf|lf|native
                        --columns=NUMBER
  -p                    --preserve-tabs
                        --tab-stop=NUMBER
                        --pdf-engine=PROGRAM
                        --pdf-engine-opt=STRING
                        --reference-doc=FILE
                        --self-contained
                        --embed-resources
                        --request-header=NAME:VALUE
                        --no-check-certificate
                        --abbreviations=FILE
                        --indented-code-classes=STRING
                        --default-image-extension=extension
  -F PROGRAM            --filter=PROGRAM
  -L SCRIPTPATH         --lua-filter=SCRIPTPATH
                        --shift-heading-level-by=NUMBER
                        --base-header-level=NUMBER
                        --track-changes=accept|reject|all
                        --strip-comments
                        --reference-links
                        --reference-location=block|section|document
                        --markdown-headings=setext|atx
                        --list-tables
                        --listings
  -i                    --incremental
                        --slide-level=NUMBER
                        --section-divs
                        --html-q-tags
                        --email-obfuscation=none|javascript|references
                        --id-prefix=STRING
  -T STRING             --title-prefix=STRING
  -c URL                --css=URL
                        --epub-subdirectory=DIRNAME
                        --epub-cover-image=FILE
                        --epub-title-page=true|false
                        --epub-metadata=FILE
                        --epub-embed-font=FILE
                        --split-level=NUMBER
                        --chunk-template=PATHTEMPLATE
                        --epub-chapter-level=NUMBER
                        --ipynb-output=all|none|best
  -C                    --citeproc
                        --bibliography=FILE
                        --csl=FILE
                        --citation-abbreviations=FILE
                        --natbib
                        --biblatex
                        --mathml
                        --webtex[=URL]
                        --mathjax[=URL]
                        --katex[=URL]
                        --gladtex
                        --trace
                        --dump-args
                        --ignore-args
                        --verbose
                        --quiet
                        --fail-if-warnings
                        --log=FILE
                        --bash-completion
                        --list-input-formats
                        --list-output-formats
                        --list-extensions[=FORMAT]
                        --list-highlight-languages
                        --list-highlight-styles
  -D FORMAT             --print-default-template=FORMAT
                        --print-default-data-file=FILE
                        --print-highlight-style=STYLE|FILE
  -v                    --version
  -h                    --help

サンプル

まずはJavadocがないと始まりません。適当なpom.xmlを作成。

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>jakarta.ws.rs</groupId>
          <artifactId>jakarta.ws.rs-api</artifactId>
          <version>3.1.0</version>
          <scope>provided</scope>
        </dependency>
    </dependencies>

依存ライブラリーのJavadocをダウンロード。ローカルリポジトリは専用に割り当てました。

$ mvn dependency:resolve -Dclassifier=javadoc -Dmaven.repo.local=local-repo

Javadoc用のディレクトリーを作成。

$ mkdir javadoc

こちらにJavadocを展開。今回はJakarta RESTful Web Servicesを対象にしました。

$ unzip -d javadoc local-repo/jakarta/ws/rs/jakarta.ws.rs-api/3.1.0/jakarta.ws.rs-api-3.1.0-javadoc.jar

このあたりを対象にしてみましょうか。

ファイルとしてはjakarta.ws.rs/jakarta/ws/rs/core/Response.htmlですね。

JavadocをMarkdownに変換する

このあたりを見ながら、JavadocをMarkdownに変換してみます。

Pandoc - Demos

Pandoc - Getting started with pandoc

こうでしょうか。

$ pandoc -f html -t markdown javadoc/jakarta.ws.rs/jakarta/ws/rs/core/Response.html

デフォルトでは結果標準出力に書き出されます。

<div>

JavaScript is disabled on your browser.

</div>

::: {role="banner"}
::: fixedNav
::: topNav
[]{#navbar.top}

::: skipNav
[Skip navigation links](#skip.navbar.top "Skip navigation links")
:::

[]{#navbar.top.firstrow}

-   [Overview](../../../../../index.html)
-   [Module](../../../../module-summary.html)
-   [Package](package-summary.html)

なるほど、HTMLがそのまま変換されているのですごいことになりますね。というか、そりゃあそうだ…と思いました。

ファイルに保存してみます。

$ pandoc -f html -t markdown javadoc/jakarta.ws.rs/jakarta/ws/rs/core/Response.html -o Response.md

表示するとこんな感じです。

ちょっと厳しい…。

中身を見ていると、このあたりを抜き出せればよいのでは?という気になりますね。

$ grep '##' Response.md
## Class Response {#class-response .title title="Class Response"}
        ### Nested Class Summary
        ### Constructor Summary
        ### Method Summary
            ### Methods inherited from class java.lang.[Object](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html?is-external=true "class or interface in java.lang"){.externalLink}
        ### Constructor Detail
        -   #### Response
        ### Method Detail
        -   #### getStatus
        -   #### getStatusInfo
        -   #### getEntity
        -   #### readEntity
        -   #### readEntity
        -   #### readEntity
        -   #### readEntity
        -   #### hasEntity
        -   #### bufferEntity
        -   #### close
        -   #### getMediaType
        -   #### getLanguage
        -   #### getLength
        -   #### getAllowedMethods
        -   #### getCookies
        -   #### getEntityTag
        -   #### getDate
        -   #### getLastModified
        -   #### getLocation
        -   #### getLinks
        -   #### hasLink
        -   #### getLink
        -   #### getLinkBuilder
        -   #### getMetadata
        -   #### getHeaders
        -   #### getStringHeaders
        -   #### getHeaderString
        -   #### isClosed
        -   #### fromResponse
        -   #### status
        -   #### status
        -   #### status
        -   #### status
        -   #### ok
        -   #### ok
        -   #### ok
        -   #### ok
        -   #### ok
        -   #### serverError
        -   #### created
        -   #### accepted
        -   #### accepted
        -   #### noContent
        -   #### notModified
        -   #### notModified
        -   #### notModified
        -   #### seeOther
        -   #### temporaryRedirect
        -   #### notAcceptable

HTMLから少し切り出してみましょうか。この用途だとhtmlqが良さそうです。

GitHub - mgdm/htmlq: Like jq, but for HTML.

ダウンロード。

$ curl -LO https://github.com/mgdm/htmlq/releases/download/v0.4.0/htmlq-x86_64-linux.tar.gz

展開。

$ tar xf htmlq-x86_64-linux.tar.gz

バージョン。

$ ./htmlq --version
htmlq 0.4.0

こんな感じでしょうか?

$ cat javadoc/jakarta.ws.rs/jakarta/ws/rs/core/Response.html | ./htmlq '.contentContainer .description, .contentContainer .details' | pandoc -f html -t markdown -o Response.md

こうなりました。

これくらいならよいのではないでしょうか?

まとめて変換する

では、ダウンロードしたJavadocをまとめて変換するスクリプトを書いておきましょう。

javadoc-to-markdown.sh

#!/bin/bash

rm -rf javadoc markdown tmp
mkdir -p javadoc markdown tmp

for javadoc_jar in $(find local-repo -name '*-javadoc.jar' | sort); do
    unzip -d tmp -o $javadoc_jar '*.html'

    if [ -f tmp/*/module-summary.html ]; then
        for e in $(find tmp/*/* -name '*.html' | grep -vE 'tmp/(doc-files|resources)' | perl -wp -e 's!(tmp/[^/]+)/.+!$1!' | sort -u); do
            cp -R $e/* javadoc
        done
    else
        for e in $(find tmp/*/* -name '*.html' | grep -vE 'tmp/(doc-files|resources)' | perl -wp -e 's!(tmp/[^/]+)/.+!$1!' | sort -u); do
            cp -R $e javadoc
        done
    fi

    rm -rf tmp/*
done

rmdir tmp

for html_file in $(find javadoc -type f | grep -vE 'class-use|(module-summary|package-[^/]+|([^/]*)?index([^/]*)?).html'); do
    markdown_file=$(echo $html_file | perl -wp -e 's!javadoc/(.+).html!$1.md!')
    target_dir=$(echo $html_file | perl -wp -e 's!javadoc/(.+)/[^/]+.html!$1!')

    mkdir -p markdown/$target_dir

    cat $html_file | ./htmlq '.contentContainer .description, .contentContainer .details' | pandoc -f html -t markdown -o markdown/$markdown_file
done

こんな感じでしょうか。




以上の内容はhttps://kazuhira-r.hatenablog.com/entry/2026/02/14/161812より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14