home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 November / CPNL0711.ISO / beeld / teken / scribus-1.3.3.9-win32-install.exe / share / samples / htmlimport.py < prev    next >
Text File  |  2004-12-14  |  2KB  |  80 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import sys
  5.  
  6. try:
  7.     from scribus import *
  8. except ImportError:
  9.     print "This script only runs from within Scribus."
  10.     sys.exit(1)
  11. from sgmllib import SGMLParser
  12. from htmlentitydefs import entitydefs
  13.  
  14. """ You can import some HTML files using this script.
  15.  
  16. ENCODING has to be edited for each file you're trying to parse
  17. utf8 - is the 'universal' solution but you can get error:
  18. 'UnicodeDecodeError: 'utf8' codec can't decode byte 0xbe in position 0: unexpected code byte'
  19. then you shall edit right encoding of the file e.g. ISO-8859-2
  20. """
  21. ENCODING = "utf8"
  22. TITLE = "Import HTML"
  23. BUTTON_OK = 1
  24. ICON_WARNING = 2
  25. NEWLINE = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  26.            'br', 'p', 'li', 'div', 'tr']
  27.  
  28. class HTMLParser(SGMLParser):
  29.  
  30.     def __init__(self, textbox):
  31.         self.encoding = valueDialog(TITLE, 'Set encoding of the imported file', ENCODING)
  32.         SGMLParser.__init__(self)
  33.         self.in_body = 0
  34.         self.textbox = textbox
  35.  
  36.     def append(self, text):
  37.         insertText(unicode(text, self.encoding), getTextLength(self.textbox), self.textbox)
  38.  
  39.     def start_body(self, attrs):
  40.         self.in_body = 1
  41.  
  42.     def end_body(self):
  43.         self.in_body = 0
  44.  
  45.     def unknown_starttag(self, name, attrs):
  46.         if name in NEWLINE:
  47.             self.append('\n')
  48.  
  49.     def unknown_endtag(self, name):
  50.         if name in NEWLINE:
  51.             self.append('\n')
  52.  
  53.     def handle_data(self, raw_data):
  54.         if self.in_body:
  55.             data = ' '.join(
  56.                 raw_data.replace('\n', ' ').split())
  57.             if raw_data.startswith(' '):
  58.                 data = ' ' + data
  59.             if raw_data.endswith(' ') and len(raw_data) > 1:
  60.                 data = data + ' '
  61.             self.append(data)
  62.  
  63.     def unknown_entityref(self, entity):
  64.         self.handle_data(entitydefs.get(entity, ''))
  65.  
  66.  
  67. if haveDoc():
  68.     filename = fileDialog(TITLE, "*.htm*", "", 0, 1)
  69.     if filename:
  70.         unit = getUnit()
  71.         setUnit(UNIT_MILLIMETERS)
  72.         textbox = createText(20, 20, 70, 250)
  73.         parser = HTMLParser(textbox)
  74.         parser.feed(open(filename).read())
  75.         setUnit(unit)
  76. else:
  77.     messageBox(TITLE, "No document open", ICON_WARNING, BUTTON_OK)
  78.  
  79.  
  80.