"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "xhtml2pdf/util.py" between
xhtml2pdf-0.2.4.tar.gz and xhtml2pdf-0.2.5.tar.gz

About: xhtml2pdf is a HTML/CSS to PDF converter written in Python.

util.py  (xhtml2pdf-0.2.4):util.py  (xhtml2pdf-0.2.5)
skipping to change at line 12 skipping to change at line 12
import base64 import base64
from copy import copy from copy import copy
import logging import logging
import mimetypes import mimetypes
import os.path import os.path
import re import re
import shutil import shutil
import string import string
import sys import sys
import tempfile import tempfile
import xhtml2pdf.default
import reportlab import reportlab
from bidi.algorithm import get_display
from reportlab.lib.colors import Color, toColor from reportlab.lib.colors import Color, toColor
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.units import inch, cm from reportlab.lib.units import inch, cm
import six import six
import reportlab.pdfbase._cidfontdata
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
import arabic_reshaper
try: try:
import httplib import httplib
except ImportError: except ImportError:
import http.client as httplib import http.client as httplib
try: try:
import urllib.request as urllib2 import urllib.request as urllib2
except ImportError: except ImportError:
import urllib2 import urllib2
skipping to change at line 277 skipping to change at line 282
return float(value) return float(value)
elif type(value) in (tuple, list): elif type(value) in (tuple, list):
value = "".join(value) value = "".join(value)
value = str(value).strip().lower().replace(",", ".") value = str(value).strip().lower().replace(",", ".")
if value[-2:] == 'cm': if value[-2:] == 'cm':
return float(value[:-2].strip()) * cm return float(value[:-2].strip()) * cm
elif value[-2:] == 'mm': elif value[-2:] == 'mm':
return float(value[:-2].strip()) * mm # 1mm = 0.1cm return float(value[:-2].strip()) * mm # 1mm = 0.1cm
elif value[-2:] == 'in': elif value[-2:] == 'in':
return float(value[:-2].strip()) * inch # 1pt == 1/72inch return float(value[:-2].strip()) * inch # 1pt == 1/72inch
elif value[-2:] == 'inch':
return float(value[:-4].strip()) * inch # 1pt == 1/72inch
elif value[-2:] == 'pt': elif value[-2:] == 'pt':
return float(value[:-2].strip()) return float(value[:-2].strip())
elif value[-2:] == 'pc': elif value[-2:] == 'pc':
return float(value[:-2].strip()) * 12.0 # 1pc == 12pt return float(value[:-2].strip()) * 12.0 # 1pc == 12pt
elif value[-2:] == 'px': elif value[-2:] == 'px':
# XXX W3C says, use 96pdi # XXX W3C says, use 96pdi
# http://www.w3.org/TR/CSS21/syndata.html#length-units # http://www.w3.org/TR/CSS21/syndata.html#length-units
return float(value[:-2].strip()) * dpi96 return float(value[:-2].strip()) * dpi96
elif value[-1:] == 'i': # 1pt == 1/72inch elif value in ("none", "0", '0.0', "auto"):
return float(value[:-1].strip()) * inch
elif value in ("none", "0", "auto"):
return 0.0 return 0.0
elif relative: elif relative:
if value[-3:] == 'rem': # XXX if value[-3:] == 'rem': # XXX
# 1rem = 1 * fontSize # 1rem = 1 * fontSize
return float(value[:-3].strip()) * relative return float(value[:-3].strip()) * relative
elif value[-2:] == 'em': # XXX elif value[-2:] == 'em': # XXX
# 1em = 1 * fontSize # 1em = 1 * fontSize
return float(value[:-2].strip()) * relative return float(value[:-2].strip()) * relative
elif value[-2:] == 'ex': # XXX elif value[-2:] == 'ex': # XXX
# 1ex = 1/2 fontSize # 1ex = 1/2 fontSize
skipping to change at line 319 skipping to change at line 320
return max(MIN_FONT_SIZE, relative * _relativeSizeTable[value]) return max(MIN_FONT_SIZE, relative * _relativeSizeTable[value])
elif value in _absoluteSizeTable: elif value in _absoluteSizeTable:
if base: if base:
return max(MIN_FONT_SIZE, base * _absoluteSizeTable[value]) return max(MIN_FONT_SIZE, base * _absoluteSizeTable[value])
return max(MIN_FONT_SIZE, relative * _absoluteSizeTable[value]) return max(MIN_FONT_SIZE, relative * _absoluteSizeTable[value])
else: else:
return max(MIN_FONT_SIZE, relative * float(value)) return max(MIN_FONT_SIZE, relative * float(value))
try: try:
value = float(value) value = float(value)
except ValueError: except ValueError:
log.warn("getSize: Not a float %r", value) log.warning("getSize: Not a float %r", value)
return default # value = 0 return default # value = 0
return max(0, value) return max(0, value)
except Exception: except Exception:
log.warn("getSize %r %r", original, relative, exc_info=1) log.warning("getSize %r %r", original, relative, exc_info=1)
return default return default
@memoized @memoized
def getCoords(x, y, w, h, pagesize): def getCoords(x, y, w, h, pagesize):
""" """
As a stupid programmer I like to use the upper left As a stupid programmer I like to use the upper left
corner of the document as the 0,0 coords therefore corner of the document as the 0,0 coords therefore
we need to do some fancy calculations we need to do some fancy calculations
""" """
#~ print pagesize #~ print pagesize
skipping to change at line 491 skipping to change at line 492
Switch to next startegy. If an error occured, Switch to next startegy. If an error occured,
stay with the first strategy stay with the first strategy
""" """
if self.strategy == 0: if self.strategy == 0:
try: try:
new_delegate = self.STRATEGIES[1]() new_delegate = self.STRATEGIES[1]()
new_delegate.write(self.getvalue()) new_delegate.write(self.getvalue())
self._delegate = new_delegate self._delegate = new_delegate
self.strategy = 1 self.strategy = 1
log.warn("Created temporary file %s", self.name) log.warning("Created temporary file %s", self.name)
except: except:
self.capacity = - 1 self.capacity = - 1
def getFileName(self): def getFileName(self):
""" """
Get a named temporary file Get a named temporary file
""" """
self.makeTempFile() self.makeTempFile()
return self.name return self.name
skipping to change at line 666 skipping to change at line 667
"Received non-200 status: {}".format((r1.status, r1.reas on))) "Received non-200 status: {}".format((r1.status, r1.reas on)))
try: try:
urlResponse = urllib2.urlopen(uri) urlResponse = urllib2.urlopen(uri)
except urllib2.HTTPError as e: except urllib2.HTTPError as e:
log.error("Could not process uri: {}".format(e)) log.error("Could not process uri: {}".format(e))
return return
self.mimetype = urlResponse.info().get( self.mimetype = urlResponse.info().get(
"Content-Type", '').split(";")[0] "Content-Type", '').split(";")[0]
self.uri = urlResponse.geturl() self.uri = urlResponse.geturl()
self.file = urlResponse self.file = urlResponse
conn.close()
else: else:
log.debug("Unrecognized scheme, assuming local file path") log.debug("Unrecognized scheme, assuming local file path")
# Local data # Local data
if basepath: if basepath:
if sys.platform == 'win32' and os.path.isfile(basepath): if sys.platform == 'win32' and os.path.isfile(basepath):
basepath = os.path.dirname(basepath) basepath = os.path.dirname(basepath)
uri = os.path.normpath(os.path.join(basepath, uri)) uri = os.path.normpath(os.path.join(basepath, uri))
skipping to change at line 916 skipping to change at line 918
'violet': Color(.933333, .509804, .933333), 'violet': Color(.933333, .509804, .933333),
'wheat': Color(.960784, .870588, .701961), 'wheat': Color(.960784, .870588, .701961),
'white': Color(1, 1, 1), 'white': Color(1, 1, 1),
'whitesmoke': Color(.960784, .960784, .960784), 'whitesmoke': Color(.960784, .960784, .960784),
'window': Color(255, 255, 255), 'window': Color(255, 255, 255),
'windowframe': Color(0, 0, 0), 'windowframe': Color(0, 0, 0),
'windowtext': Color(0, 0, 0), 'windowtext': Color(0, 0, 0),
'yellow': Color(1, 1, 0), 'yellow': Color(1, 1, 0),
'yellowgreen': Color(.603922, .803922, .196078) 'yellowgreen': Color(.603922, .803922, .196078)
} }
def get_default_asian_font():
lower_font_list = []
upper_font_list = []
font_dict = copy(reportlab.pdfbase._cidfontdata.defaultUnicodeEncodings)
fonts = font_dict.keys()
for font in fonts:
upper_font_list.append(font)
lower_font_list.append(font.lower())
default_asian_font = {lower_font_list[i]: upper_font_list[i] for i in range(
len(lower_font_list))}
return default_asian_font
def set_asian_fonts(fontname):
font_dict = copy(reportlab.pdfbase._cidfontdata.defaultUnicodeEncodings)
fonts = font_dict.keys()
if fontname in fonts:
pdfmetrics.registerFont(UnicodeCIDFont(fontname))
def detect_language(name):
asian_language_list = xhtml2pdf.default.DEFAULT_LANGUAGE_LIST
if name in asian_language_list:
return name
def arabic_format(text, language):
# Note: right now all of the languages are treated the same way.
# But maybe in the future we have to for example implement something
# for "hebrew" that isn't used in "arabic"
if detect_language(language) in ('arabic', 'hebrew', 'persian', 'urdu', 'pas
hto', 'sindhi'):
ar = arabic_reshaper.reshape(text)
return get_display(ar)
else:
return None
def frag_text_language_check(context, frag_text):
if hasattr(context, 'language'):
language = context.__getattribute__('language')
detect_language_result = arabic_format(frag_text, language)
if detect_language_result:
return detect_language_result
 End of changes. 10 change blocks. 
9 lines changed or deleted 11 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)