Class: Softcover::Builders::Epub
- Inherits:
-
Softcover::Builder
- Object
- Softcover::Builder
- Softcover::Builders::Epub
- Includes:
- Output
- Defined in:
- lib/softcover/builders/epub.rb
Constant Summary
Constants included from Utils
Instance Attribute Summary
Attributes inherited from Softcover::Builder
Instance Method Summary collapse
- #build!(options = {}) ⇒ Object
- #chapter_name(n) ⇒ Object
-
#chapter_template(title, content) ⇒ Object
Returns the HTML template for a chapter.
-
#chapters ⇒ Object
Returns the chapters to write (accounting for previews).
- #container_xml ⇒ Object
-
#content_opf ⇒ Object
Returns the content configuration file.
-
#copy_image_files ⇒ Object
Copies the image files from the HTML version of the document.
- #cover_page ⇒ Object
- #create_directories ⇒ Object
- #create_style_files ⇒ Object
-
#html_with_math(chapter, images_dir, texmath_dir, pngs, options = {}) ⇒ Object
Returns HTML for HTML source that includes math.
-
#inkscape ⇒ Object
Returns the Inkscape executable (if available).
-
#make_epub(options = {}) ⇒ Object
Make the EPUB, which is basically just a zipped HTML file.
-
#math?(string) ⇒ Boolean
Returns true if a string appears to have LaTeX math.
-
#move_epub ⇒ Object
Move the completed EPUB book to the ‘ebooks` directory.
-
#nav_html ⇒ Object
Returns the nav HTML content.
-
#phantomjs ⇒ Object
Returns the PhantomJS executable (if available).
-
#preview? ⇒ Boolean
Returns true if generating a book preview.
-
#remove_html ⇒ Object
Removes HTML.
-
#strip_attributes(doc) ⇒ Object
Strip attributes that are invalid in EPUB documents.
-
#toc_ncx ⇒ Object
Returns the Table of Contents for the spine.
-
#write_container_xml ⇒ Object
Writes the container XML file.
-
#write_contents ⇒ Object
Writes the content.opf file.
-
#write_html(options = {}) ⇒ Object
Writes the HTML for the EPUB.
-
#write_mimetype ⇒ Object
Writes the mimetype file.
-
#write_nav ⇒ Object
Writes the navigation file.
-
#write_toc ⇒ Object
Writes the Table of Contents.
Methods included from Output
should_output?, silence!, silent?, #system, unsilence!
Methods inherited from Softcover::Builder
Methods included from Utils
#add_highlight_class!, #as_size, #current_book, #digest, #executable, #execute, #in_book_directory?, #logged_in?, #mkdir, #path, #reset_current_book!, #rm, #silence, #source, #tmpify, #write_pygments_file
Constructor Details
This class inherits a constructor from Softcover::Builder
Instance Method Details
#build!(options = {}) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/softcover/builders/epub.rb', line 6 def build!(={}) @preview = [:preview] Softcover::Builders::Html.new.build!(preserve_tex: true) if manifest.markdown? self.manifest = Softcover::BookManifest.new(source: :polytex, origin: :markdown) end remove_html create_directories write_mimetype write_container_xml write_toc write_nav copy_image_files write_html() write_contents create_style_files make_epub() move_epub end |
#chapter_name(n) ⇒ Object
391 392 393 |
# File 'lib/softcover/builders/epub.rb', line 391 def chapter_name(n) n == 0 ? "Frontmatter" : "Chapter #{n}" end |
#chapter_template(title, content) ⇒ Object
Returns the HTML template for a chapter.
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/softcover/builders/epub.rb', line 420 def chapter_template(title, content) %(<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>#{title}</title> <link rel="stylesheet" href="styles/pygments.css" type="text/css" /> <link rel="stylesheet" href="styles/softcover.css" type="text/css" /> <link rel="stylesheet" href="styles/epub.css" type="text/css" /> <link rel="stylesheet" type="application/vnd.adobe-page-template+xml" href="styles/page-template.xpgt" /> </head> <body> #{content} </body> </html>) end |
#chapters ⇒ Object
Returns the chapters to write (accounting for previews).
65 66 67 |
# File 'lib/softcover/builders/epub.rb', line 65 def chapters preview? ? manifest.preview_chapters : manifest.chapters end |
#container_xml ⇒ Object
279 280 281 282 283 284 285 286 |
# File 'lib/softcover/builders/epub.rb', line 279 def container_xml %(<?xml version="1.0"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles> <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/> </rootfiles> </container>) end |
#content_opf ⇒ Object
Returns the content configuration file.
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/softcover/builders/epub.rb', line 289 def content_opf title = manifest.title = manifest. copyright = manifest.copyright uuid = manifest.uuid man_ch = chapters.map do |chapter| %(<item id="#{chapter.slug}" href="#{chapter.fragment_name}" media-type="application/xhtml+xml"/>) end toc_ch = chapters.map do |chapter| %(<itemref idref="#{chapter.slug}"/>) end image_files = Dir['epub/OEBPS/images/**/*'].select { |f| File.file?(f) } images = image_files.map do |image| ext = File.extname(image).sub('.', '') # e.g., 'png' # Strip off the leading 'epub/OEBPS'. sep = File::SEPARATOR href = image.split(sep)[2..-1].join(sep) # Define an id based on the filename. # Prefix with 'img-' in case the filname starts with an # invalid character such as a number. label = File.basename(image).gsub('.', '-') id = "img-#{label}" %(<item id="#{id}" href="#{href}" media-type="image/#{ext}"/>) end %(<?xml version="1.0" encoding="UTF-8"?> <package unique-identifier="BookID" version="3.0" xmlns="http://www.idpf.org/2007/opf"> <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:opf="http://www.idpf.org/2007/opf"> <dc:title>#{title}</dc:title> <dc:language>en</dc:language> <dc:rights>Copyright (c) #{copyright} #{author}</dc:rights> <dc:creator>#{author}</dc:creator> <dc:publisher>Softcover</dc:publisher> <dc:identifier id="BookID">urn:uuid:#{uuid}</dc:identifier> <meta property="dcterms:modified">#{Time.now.strftime('%Y-%m-%dT%H:%M:%S')}Z</meta> <meta name="cover" content="img-cover-png"/> </metadata> <manifest> <item href="nav.html" id="nav" media-type="application/xhtml+xml" properties="nav"/> <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/> <item id="page-template.xpgt" href="styles/page-template.xpgt" media-type="application/vnd.adobe-page-template+xml"/> <item id="pygments.css" href="styles/pygments.css" media-type="text/css"/> <item id="softcover.css" href="styles/softcover.css" media-type="text/css"/> <item id="epub.css" href="styles/epub.css" media-type="text/css"/> <item id="cover" href="cover.html" media-type="application/xhtml+xml"/> #{man_ch.join("\n")} #{images.join("\n")} </manifest> <spine toc="ncx"> <itemref idref="cover" linear="no" /> #{toc_ch.join("\n")} </spine> </package> ) end |
#copy_image_files ⇒ Object
Copies the image files from the HTML version of the document. We remove PDF images, which are valid in PDF documents but not in EPUB.
232 233 234 235 236 |
# File 'lib/softcover/builders/epub.rb', line 232 def copy_image_files FileUtils.cp_r(File.join('html', 'images'), File.join('epub', 'OEBPS')) File.delete(*Dir['epub/OEBPS/images/**/*.pdf']) end |
#cover_page ⇒ Object
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/softcover/builders/epub.rb', line 345 def cover_page %(<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cover</title> </head> <body> <div id="cover"> <img width="573" height="800" src="images/cover.png" alt="cover image" /> </div> </body> </html> ) end |
#create_directories ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/softcover/builders/epub.rb', line 38 def create_directories mkdir('epub') mkdir(path('epub/OEBPS')) mkdir(path('epub/OEBPS/styles')) mkdir(path('epub/META-INF')) mkdir('ebooks') end |
#create_style_files ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/softcover/builders/epub.rb', line 212 def create_style_files html_styles = File.join('html', 'stylesheets') epub_styles = File.join('epub', 'OEBPS', 'styles') FileUtils.cp(File.join(html_styles, 'pygments.css'), epub_styles) # Copy over the EPUB-specific CSS. template_dir = File.join(File.dirname(__FILE__), '..', 'template') epub_css = File.join(template_dir, epub_styles, 'epub.css') FileUtils.cp(epub_css, epub_styles) # For some reason, EPUB books hate the #book ids in the stylesheet # (i.e., such books fail to validate), so remove them. polytexnic_css = File.read(File.join(html_styles, 'softcover.css')) polytexnic_css.gsub!(/\s*#book\s+/, '') File.write(File.join(epub_styles, 'softcover.css'), polytexnic_css) end |
#html_with_math(chapter, images_dir, texmath_dir, pngs, options = {}) ⇒ Object
Returns HTML for HTML source that includes math. As a side-effect, html_with_math creates PNGs corresponding to any math in the given source. The technique involves using PhantomJS to hit the HTML source for each page containing math to create SVGs for every math element. Since ereader support for SVGs is spotty, they are then converted to PNGs using Inkscape. The filenames are SHAs of their contents, which arranges both for unique filenames and for automatic disk caching.
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/softcover/builders/epub.rb', line 115 def html_with_math(chapter, images_dir, texmath_dir, pngs, ={}) content = File.read(File.join("html", "#{chapter.slug}.html")) pagejs = "#{File.dirname(__FILE__)}/utils/page.js" url = "file://#{Dir.pwd}/html/#{chapter.slug}.html" cmd = "#{phantomjs} #{pagejs} #{url}" silence { silence_stream(STDERR) { system cmd } } # Sometimes in tests the phantomjs_source.html file is missing. # It shouldn't ever happen, but it does no harm to skip it. return nil unless File.exist?('phantomjs_source.html') raw_source = File.read('phantomjs_source.html') source = strip_attributes(Nokogiri::HTML(raw_source)) rm 'phantomjs_source.html' # Remove the first body div, which is the hidden MathJax SVGs. if (mathjax_svgs = source.at_css('body div')) mathjax_svgs.remove else # There's not actually any math, so return nil. return nil end # Remove all the unneeded raw TeX displays. source.css('script').each(&:remove) # Remove all the MathJax preview spans. source.css('MathJax_Preview').each(&:remove) # Suck out all the SVGs svgs = source.css('div#book svg') frames = source.css('span.MathJax_SVG') svgs.zip(frames).each do |svg, frame| # Save the SVG file. svg['viewBox'] = svg['viewbox'] svg.remove_attribute('viewbox') first_child = frame.children.first first_child.replace(svg) unless svg == first_child output = svg.to_xhtml svg_filename = File.join(texmath_dir, "#{digest(output)}.svg") File.write(svg_filename, output) # Convert to PNG. png_filename = svg_filename.sub('.svg', '.png') pngs << png_filename unless File.exist?(png_filename) unless [:silent] || [:quiet] puts "Creating #{png_filename}" end svg_height = svg['style'].scan(/height: (.*?);/).flatten.first scale_factor = 8 # This scale factor turns out to look good. h = scale_factor * svg_height.to_f cmd = "#{inkscape} -f #{svg_filename} -e #{png_filename} -h #{h}pt" if [:silent] silence { silence_stream(STDERR) { system cmd } } else silence_stream(STDERR) { system cmd } end end rm svg_filename png = Nokogiri::XML::Node.new('img', source) png['src'] = File.join('images', 'texmath', File.basename(png_filename)) png['alt'] = png_filename.sub('.png', '') svg.replace(png) end source.at_css('div#book').children.to_xhtml end |
#inkscape ⇒ Object
Returns the Inkscape executable (if available).
186 187 188 189 190 |
# File 'lib/softcover/builders/epub.rb', line 186 def inkscape filename = '/Applications/Inkscape.app/Contents/Resources/bin/inkscape' = "Install Inkscape (http://inkscape.org/)" @inkscape ||= executable(filename, ) end |
#make_epub(options = {}) ⇒ Object
Make the EPUB, which is basically just a zipped HTML file.
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/softcover/builders/epub.rb', line 239 def make_epub(={}) filename = manifest.filename zip_filename = filename + '.zip' base_file = "zip -X0 #{zip_filename} mimetype" zip = "zip -rDXg9" = "#{zip} #{zip_filename} META-INF -x \*.DS_Store -x mimetype" main_info = "#{zip} #{zip_filename} OEBPS -x \*.DS_Store \*.gitkeep" rename = "mv #{zip_filename} #{filename}.epub" commands = [base_file, , main_info, rename] command = commands.join(' && ') Dir.chdir('epub') do if Softcover.test? || [:quiet] || [:silent] silence { system(command) } else system(command) end end end |
#math?(string) ⇒ Boolean
Returns true if a string appears to have LaTeX math. We detect math via opening math commands: (, [, and beginequation This gives a false positive when math is included in verbatim environments and nowhere else, but it does little harm (requiring only an unnecessary call to page.js).
208 209 210 |
# File 'lib/softcover/builders/epub.rb', line 208 def math?(string) !!string.match(/(?:\\\(|\\\[|\\begin{equation})/) end |
#move_epub ⇒ Object
Move the completed EPUB book to the ‘ebooks` directory. Note that we handle the case of a preview book as well.
260 261 262 263 264 265 |
# File 'lib/softcover/builders/epub.rb', line 260 def move_epub origin = manifest.filename target = preview? ? origin + '-preview' : origin FileUtils.mv(File.join('epub', "#{origin}.epub"), File.join('ebooks', "#{target}.epub")) end |
#nav_html ⇒ Object
Returns the nav HTML content.
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/softcover/builders/epub.rb', line 396 def nav_html title = manifest.title nav_list = manifest.chapters.map do |chapter| %(<li><a href="#{chapter.fragment_name}">#{chapter.title}</a></li>) end %(<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"> <head> <meta charset="UTF-8" /> <title>#{title}</title> </head> <body> <nav epub:type="toc"> <h1>#{title}</h1> <ol> #{nav_list.join("\n")} </ol> </nav> </body> </html> ) end |
#phantomjs ⇒ Object
Returns the PhantomJS executable (if available).
179 180 181 182 183 |
# File 'lib/softcover/builders/epub.rb', line 179 def phantomjs filename = `which phantomjs`.chomp = "Install PhantomJS (http://phantomjs.org/)" @phantomjs ||= executable(filename, ) end |
#preview? ⇒ Boolean
Returns true if generating a book preview.
28 29 30 |
# File 'lib/softcover/builders/epub.rb', line 28 def preview? !!@preview end |
#remove_html ⇒ Object
Removes HTML. All the HTML is generated, so this clears out any unused files.
34 35 36 |
# File 'lib/softcover/builders/epub.rb', line 34 def remove_html FileUtils.rm(Dir.glob(path('epub/OEBPS/html/*.html'))) end |
#strip_attributes(doc) ⇒ Object
Strip attributes that are invalid in EPUB documents.
193 194 195 196 197 198 199 200 201 |
# File 'lib/softcover/builders/epub.rb', line 193 def strip_attributes(doc) attrs = %w[data-tralics-id data-label data-number data-chapter role aria-readonly] doc.tap do attrs.each do |attr| doc.xpath("//@#{attr}").remove end end end |
#toc_ncx ⇒ Object
Returns the Table of Contents for the spine.
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
# File 'lib/softcover/builders/epub.rb', line 362 def toc_ncx title = manifest.title chapter_nav = [] offset = preview? ? manifest.preview_chapter_range.first : 0 chapters.each_with_index do |chapter, i| n = i + offset chapter_nav << %(<navPoint id="#{chapter.slug}" playOrder="#{n+1}">) chapter_nav << %( <navLabel><text>#{chapter_name(n)}</text></navLabel>) chapter_nav << %( <content src="#{chapter.fragment_name}"/>) chapter_nav << %(</navPoint>) end %(<?xml version="1.0" encoding="UTF-8"?> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"> <head> <meta name="dtb:uid" content="d430b920-e684-11e1-aff1-0800200c9a66"/> <meta name="dtb:depth" content="2"/> <meta name="dtb:totalPageCount" content="0"/> <meta name="dtb:maxPageNumber" content="0"/> </head> <docTitle> <text>#{title}</text> </docTitle> <navMap> #{chapter_nav.join("\n")} </navMap> </ncx> ) end |
#write_container_xml ⇒ Object
Writes the container XML file. This is required by the EPUB standard.
54 55 56 |
# File 'lib/softcover/builders/epub.rb', line 54 def write_container_xml File.write(path('epub/META-INF/container.xml'), container_xml) end |
#write_contents ⇒ Object
Writes the content.opf file. This is required by the EPUB standard.
60 61 62 |
# File 'lib/softcover/builders/epub.rb', line 60 def write_contents File.write(path('epub/OEBPS/content.opf'), content_opf) end |
#write_html(options = {}) ⇒ Object
Writes the HTML for the EPUB. Included is a math detector that processes the page with MathJax (via page.js) so that math can be included in EPUB (and thence MOBI).
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/softcover/builders/epub.rb', line 72 def write_html(={}) images_dir = File.join('epub', 'OEBPS', 'images') texmath_dir = File.join(images_dir, 'texmath') mkdir images_dir mkdir texmath_dir File.write(path('epub/OEBPS/cover.html'), cover_page) pngs = [] chapters.each_with_index do |chapter, i| target_filename = path("epub/OEBPS/#{chapter.fragment_name}") File.open(target_filename, 'w') do |f| content = File.read(path("html/#{chapter.fragment_name}")) doc = strip_attributes(Nokogiri::HTML(content)) inner_html = doc.at_css('body').children.to_xhtml if math?(inner_html) html = html_with_math(chapter, images_dir, texmath_dir, pngs, ) html ||= inner_html # handle case of spurious math detection else html = inner_html end f.write(chapter_template("Chapter #{i}", html)) end end # Clean up unused PNGs. png_files = Dir[path("#{texmath_dir}/*.png")] (png_files - pngs).each do |f| if File.exist?(f) puts "Removing unused PNG #{f}" unless [:silent] FileUtils.rm(f) end end end |
#write_mimetype ⇒ Object
Writes the mimetype file. This is required by the EPUB standard.
48 49 50 |
# File 'lib/softcover/builders/epub.rb', line 48 def write_mimetype File.write(path('epub/mimetype'), 'application/epub+zip') end |
#write_nav ⇒ Object
Writes the navigation file. This is required by the EPUB standard.
275 276 277 |
# File 'lib/softcover/builders/epub.rb', line 275 def write_nav File.write('epub/OEBPS/nav.html', nav_html) end |
#write_toc ⇒ Object
Writes the Table of Contents. This is required by the EPUB standard.
269 270 271 |
# File 'lib/softcover/builders/epub.rb', line 269 def write_toc File.write('epub/OEBPS/toc.ncx', toc_ncx) end |