May 28, 2012

CSS package in python, cssutils

cssutils
documentation

documentation 很详细,好用
层次
sheet  -> rule -> property

例子,处理 epub 电子书的css 文件,添加font-face 的 url,修改段落的 line-height
import cssutils
def css_proc(css):
    #of = open(css,'a')
    #of.write('last line')
    #of.close()
    
    sheet = cssutils.parseFile(css)
    #print sheet.cssText
    for rule in sheet:
        if rule.type == rule.FONT_FACE_RULE:
            for property in rule.style:            
                if property.name == 'src':
                    property.value = 'url(res:///system/fonts/zw.ttf), url(res:///system/media/sdcard/fonts/zw.ttf), url(res:///sdcard/fonts/zw.ttf), url(res:///opt/sony/ebook/FONT/zw.ttf), url(res:///Data/FONT/zw.ttf), url(res:///opt/sony/ebook/FONT/tt0011m_.ttf), url(res:///fonts/ttf/zw.ttf), url(res:///../../media/mmcblk0p1/fonts/zw.ttf), url(res:///DK_System/system/font/zw.ttf), url(res:///abook/fonts/zw.ttf), url(res:///system/fonts/DroidSansFallback.ttf)'
        if rule.type == rule.STYLE_RULE and rule.selectorText == 'p':
            rule.style.setProperty('line-height','200%')
                        
            #for property in rule.style:
            #    if property.name == 'line-height':
            #        property.value = '140%'
            #        lineHeightSet = True
            #        break
            
                  
    
    of = open(css, 'w')
    of.write(sheet.cssText)
    of.close()

0 comments: