convertToDocx

Johannes Thorn Jody Winter Jody Winter Jeremie Bresson Ralf D. Müller Heiko Stehli ghp-dev Lars Francke

1 minute to read

Before You Begin

Before using this task:

  • Install pandoc.

  • Ensure that 'docbook' and 'docx' are added to the inputFiles formats in Config.groovy.

  • As an optional step, specify a reference doc file with custom stylesheets (see task createReferenceDoc).

Further Reading and Resources

Read the Render AsciiDoc to docx (MS Word) blog post.

Source

Show source code of scripts/pandoc.gradle or go directly to GitHub · docToolchain/scripts/pandoc.gradle.
scripts/pandoc.gradle
task convertToDocx (
        group: 'docToolchain',
        description: 'converts file to .docx via pandoc. Needs pandoc installed.',
        type: Exec
) {
    // All files with option `docx` in config.groovy is converted to docbook and then to docx.
    def sourceFilesDocx = sourceFiles.findAll { 'docx' in it.formats }
    def explicitSourceFilesCount = sourceFilesDocx.size()
    if(explicitSourceFilesCount==0){
        sourceFilesDocx = sourceFiles.findAll { 'docbook' in it.formats }
    }
    sourceFilesDocx.each {
        def sourceFile = it.file.replace('.adoc', '.xml')
        def targetFile = sourceFile.replace('.xml', '.docx')

        new File("$targetDir/docx/$targetFile")
            .getParentFile()
            .getAbsoluteFile().mkdirs()

        workingDir "$targetDir/docbook"
        executable = "pandoc"

        if(referenceDocFile?.trim()) {
            args = ["-r","docbook",
                    "-t","docx",
                    "-o","../docx/$targetFile",
                    "--reference-doc=${docDir}/${referenceDocFile}",
                    sourceFile]
        } else {
            args = ["-r","docbook",
                    "-t","docx",
                    "-o","./../docx/$targetFile",
                    sourceFile]
        }
    }
    doFirst {
        if(sourceFilesDocx.size()==0){
            throw new Exception ("""
            >> No source files defined for type 'docx'.
            >> Please specify at least one inputFile in your docToolchainConfig.groovy
            """)
        }
        if(explicitSourceFilesCount==0) {
            logger.warn('WARNING: No source files defined for type "docx". Converting with best effort')
        }
    }
}