chm2html.py: Mengubah .chm ke satu file .html

Tentang chm2html.py

Script Python ini sebenarnya script yang telah lama saya buat. Penyebabnya sederhana saja, saya sering membaca dokumentasi dalam format .chm (compressed HTML file) tapi harus bolak balik ke satu chapter ke chapter berikutnya. Sering saya menginginkan hanya membuka satu file saja, atau barangkali cukup jadi 1 file kemudian saya buka menggunakan OpenOffice.org writer kemudian di export ke PDF untuk pencetakan.

Source Code

Indentasi sangat penting dalam Python, jadi jika akan mencoba script berikut, pastikan indentasi sudah benar.

chm2html.py

 

 

 

 

 

#!/usr/bin/python
# chm2html.py
# a simple python script to convert from .CHM into one single big HTML
#
# created by Bambang Purnomosidi D. P.
#

from optparse import OptionParser
import sys, os, re

class joinedHTML:

  def __init__(self, jFileName, jMainFile):
    self.fileName = jFileName
    self.mainFile = jMainFile

  def makeTOC(self, hhcFile):

    hf = open(hhcFile, 'r')

    h = []
    self.daftarFile = []
    isi = hf.readlines()
    for a in isi:
      a = str.strip(a)
      if a.startswith('<param name="Local"'):
        h.append(a)

    for x in h:
      b = x.split('"')
      isiBeneran = b[3]
      self.daftarFile.append(isiBeneran)

    hf.close()

  def placeHTMLIntoStr(self, htmlFile):

    f = open(htmlFile,'r')
    self.htmlString = f.read()
    f.close()

  def splitInput(self):

    h = re.split('<body>|<body.+>|</body>', self.htmlString)

    self.header = h[0]
    self.body = h[1]
    self.footer = h[2]

  def getMain(self):

    self.placeHTMLIntoStr(self.daftarFile[0])
    self.splitInput()
    self.mainHeader = self.header
    self.mainFooter = self.footer
    self.mainBody = self.body

def main():

  usage = "%prog [options]"
  parser = OptionParser(usage)
  parser.add_option("-o", "--outfile", dest="fileName",
  help="Write output to FILENAME")
  parser.add_option("-c", "--hhcfile", dest="mainFile",
  help="A .hhc file which hold all contents definition")

  (options, args) = parser.parse_args()

  if options.fileName == None or options.mainFile == None:
  print 'Invalid arguments. Try -h or --help'
  sys.exit(2)

  # .hhc should be in current directory
  # and there's a directory named as the prefix
  # of .hhc (without extention)
  #

  if not os.path.isfile('./' + os.path.basename(options.mainFile)):
    print 'Error:'
    print os.path.basename(options.mainFile) + ' should be in current directory'
    sys.exit(2)
    directory = re.split('\.', os.path.basename(options.mainFile))

  if not os.path.isdir(directory[0]):
    print 'Error:'
    print 'No directory named ' + directory[0] + ' in current dir'
    sys.exit(2)

  htmlProcessed = joinedHTML(options.fileName, options.mainFile)
  htmlProcessed.makeTOC(options.mainFile)

  print 'Processing main file (' + options.mainFile + ') ... '
  htmlProcessed.getMain()
  print ''
  print 'Processing new contents ... '
  print ''

  newContents = htmlProcessed.mainHeader + '\r\n<body>' + htmlProcessed.mainBody

  print ''
  print 'Writing to ' + directory[0] + '/' + options.fileName
  print 'Using header and footer from ' + htmlProcessed.daftarFile[0]
  print ''

  iterasiKe = 0

  for fHTML in htmlProcessed.daftarFile:
    iterasiKe = iterasiKe + 1
    print 'Processing ' + str(iterasiKe) + ' of ' + str(len(htmlProcessed.daftarFile)) + '(' + fHTML + ') ...'

    try:
      htmlProcessed.placeHTMLIntoStr(fHTML)
      htmlProcessed.splitInput()
    except:
      print ''
      print 'Error while processing ' + fHTML
      print ''
      #sys.exit(2)

  newContents = newContents + htmlProcessed.body
  newContents = newContents + '\r\n</body>' + htmlProcessed.mainFooter
  print ''
  print 'Writing new contents to file ... '
  print ''
  outFile = open(directory[0] + '/' + options.fileName, 'w')
  outFile.write(newContents)
  print ''
  print 'Finished. Have a look at ' + directory[0] + '/' + options.fileName
  print ''

if __name__ == "__main__":
  main()

Menggunakan Script chm2html.py

Untuk menggunakan script ini, silahkan meng-extract file .CHM dengan extract_chmLib dari proyek chmlib (http://www.jedrea.com/chmlib/).  Setelah itu masuk ke direktori hasil extract dan jalankan sesuai dengan parameter yang diminta oleh script ini.

Script ini masih mempunyai sedikit kekurangan, yaitu direktori tempat file-file HTML yang telah diekstrak harus sama dengan nama file .HHC, misalnya jika hasil ekstrak menunjukkan ada file toc.hhc, maka direktori tempat hasil ekstrak harus bernama toc.

 

  1. No trackbacks yet.