Ant for EPUB

Inasmuch as I like to automate processes as much as possible, here’s two Ant targets/macros for automating zipping an EPUB file and checking it with epubcheck:

  • Zipping an EPUB file so that it retains an uncompressed mimetypefile
    <target name="epub.zip"
            description="Package up an EPUB" >
      <delete file="${build.dir}/${epub}.epub" />
      <!-- The 'mimetype' file is supposed to be uncompressed and the
           first thing in the .epub file so the file conforms to the
           (rather long) signature for EPUB files. -->
      <zip destfile="${build.dir}/${epub}.mimetype"
           compress="false"
           encoding="UTF-8">
        <fileset dir="${build.dir}/${epub}" includes="mimetype" />
      </zip>
      <!-- We'd really rather have the rest compressed, thank you. -->
      <zip destfile="${build.dir}/${epub}.zip"
           compress="true"
           encoding="UTF-8"
           level="9">
        <zipfileset dir="${build.dir}/${epub}/META-INF" prefix="META-INF"/>
        <zipfileset dir="${build.dir}/${epub}/OPS" prefix="OPS"/>
      </zip>
      <!-- Putting them together this way is the best way so far found
           for getting only 'mimetype' uncompressed in the .epub. -->
      <zip destfile="${build.dir}/${epub}.epub"
           update="true"
           keepcompression="true"
           encoding="UTF-8">
        <zipfileset src="${build.dir}/${epub}.mimetype" />
        <zipfileset src="${build.dir}/${epub}.zip" />
      </zip>
      <!-- Delete the temporary Zip files. -->
      <delete file="${build.dir}/${epub}.mimetype" />
      <delete file="${build.dir}/${epub}.zip" />
    </target>
  • Checking an EPUB with epubcheck
    <macrodef name="epub.check"
              description="Check an epub">
      <attribute name="epub" description="Name of the EPUB" />
      <sequential>
        <java jar="${epubcheck.jar}"
              fork="true">
          <arg value="${build.dir}/@{epub}.epub" />
        </java>
      </sequential>
    </macrodef>
    
    <target name="epub.check.YourEPUB"
            description="Check YourEPUB EPUB">
      <epub.check epub="YourEPUB"/>
    </target>

    (In practice, the epub.check.YourEPUB target is generated by XSLT, but that’s another story.)