Skip to content

Commit

Permalink
Several cleanups and optimisations, especially in loops.
Browse files Browse the repository at this point in the history
  • Loading branch information
BertrandBordage committed Jun 11, 2012
1 parent bf1213b commit 5bc1328
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 66 deletions.
10 changes: 5 additions & 5 deletions xhtml2pdf/context.py
Expand Up @@ -233,8 +233,8 @@ def atPage(self, name, pseudopage, declarations):
if isLandscape:
c.pageSize = landscape(c.pageSize)

for prop in ["margin-top", "margin-left", "margin-right", "margin-bottom",
"top", "left", "right", "bottom", "width", "height"]:
for prop in ("margin-top", "margin-left", "margin-right", "margin-bottom",
"top", "left", "right", "bottom", "width", "height"):
if data.has_key(prop):
c.frameList.append(self._pisaAddFrame(name, data, first=True, border=pageBorder, size=c.pageSize))
break
Expand Down Expand Up @@ -568,7 +568,7 @@ def addTOC(self):
#cssAttrs = copy.deepcopy(self.node.cssAttrs)
#frag = copy.deepcopy(self.frag)
styles = []
for i in range(0, 20):
for i in xrange(20):
self.node.attributes["class"] = "pdftoclevel%d" % i
#self.node.cssAttrs = copy.deepcopy(cssAttrs)
#self.frag = copy.deepcopy(frag)
Expand Down Expand Up @@ -632,7 +632,7 @@ def addPara(self, force=False):
maxLeading = max(leading, frag.fontSize + frag.leadingSpace, maxLeading)
frag.leading = leading

if force or (self.text.strip() and self.fragList):
if force or (self.text.strip() and self.fragList):

# Strip trailing whitespaces
#for f in self.fragList:
Expand Down Expand Up @@ -917,7 +917,7 @@ def loadFont(self, names, src, encoding="WinAnsiEncoding", bold=0, italic=0):
if type(names) is types.ListType:
fontAlias = names
else:
fontAlias = [x.lower().strip() for x in names.split(",") if x]
fontAlias = (x.lower().strip() for x in names.split(",") if x)

# XXX Problems with unicode here
fontAlias = [str(x) for x in fontAlias]
Expand Down
19 changes: 10 additions & 9 deletions xhtml2pdf/paragraph.py
Expand Up @@ -238,15 +238,15 @@ def doAlignment(self, width, alignment):
lineWidth = self[ - 1]["x"] + self[ - 1]["width"]
emptySpace = width - lineWidth
if alignment == TA_RIGHT:
for j, frag in enumerate(self):
for frag in self:
frag["x"] += emptySpace
elif alignment == TA_CENTER:
for j, frag in enumerate(self):
for frag in self:
frag["x"] += emptySpace / 2.0
elif alignment == TA_JUSTIFY and not self.isLast: # XXX last line before split
delta = emptySpace / (len(self) - 1)
for j, frag in enumerate(self):
frag["x"] += j * delta
for i, frag in enumerate(self):
frag["x"] += i * delta

# Boxes
for frag in self:
Expand Down Expand Up @@ -324,7 +324,8 @@ def calc(self):
# self.groups.append(group)
# self.
# gWidth += width
[word.calc() for word in self]
for word in self:
word.calc()

def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
"""
Expand Down Expand Up @@ -415,19 +416,18 @@ def splitIntoLines(self, maxWidth, maxHeight, splitted=False):

# Apply alignment
self.lines[ - 1].isLast = True
[line.doAlignment(maxWidth, style["textAlign"]) for line in self.lines]
for line in self.lines:
line.doAlignment(maxWidth, style["textAlign"])

return None

def dumpLines(self):
"""
For debugging dump all line and their content
"""
i = 0
for line in self.lines:
for i, line in enumerate(self.lines):
print "Line %d:" % i,
line.dumpFragments()
i += 1

class Paragraph(Flowable):
"""A simple Paragraph class respecting alignment.
Expand Down Expand Up @@ -825,4 +825,5 @@ def test():
test()
os.system("start test.pdf")

# FIXME: Useless line?
# createText(TEXT, styles["Normal"].fontName, styles["Normal"].fontSize)
26 changes: 13 additions & 13 deletions xhtml2pdf/paragraph2.py
Expand Up @@ -307,15 +307,15 @@ def doAlignment(self, width, alignment):
lineWidth = self[ - 1]["x"] + self[ - 1]["width"]
emptySpace = width - lineWidth
if alignment == TA_RIGHT:
for j, frag in enumerate(self):
for frag in self:
frag["x"] += emptySpace
elif alignment == TA_CENTER:
for j, frag in enumerate(self):
for frag in self:
frag["x"] += emptySpace / 2.0
elif alignment == TA_JUSTIFY and not self.br: # XXX Just spaces! Currently divides also sticky fragments
delta = emptySpace / (len(self) - 1)
for j, frag in enumerate(self):
frag["x"] += j * delta
for i, frag in enumerate(self):
frag["x"] += i * delta

# Boxes
for frag in self:
Expand Down Expand Up @@ -381,7 +381,8 @@ def calc(self):
"""
Calculate sizes of fragments.
"""
[word.calc() for word in self]
for word in self:
word.calc()

def getGroup(self):
self.oldSpace = self.newSpace # For Space recycing
Expand Down Expand Up @@ -426,7 +427,7 @@ def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
x = style["textIndent"]

# Loop for each line
while 1:
while True:

# Reset values for new line
posBegin = self.pos
Expand All @@ -438,7 +439,7 @@ def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
line.append(BoxBegin(box))

# Loop for collecting line elements
while 1:
while True:

# Get next group of unbreakable elements
self.groupPos = self.pos
Expand Down Expand Up @@ -500,19 +501,18 @@ def splitIntoLines(self, maxWidth, maxHeight, splitted=False):

# Apply alignment
self.lines[ - 1].br = True
[line.doAlignment(maxWidth, style["textAlign"]) for line in self.lines]
for line in self.lines:
line.doAlignment(maxWidth, style["textAlign"])

return None

def dumpLines(self):
"""
For debugging dump all line and their content
"""
i = 0
for line in self.lines:
for i, line in enumerate(self.lines):
print "Line %d:" % i,
line.dumpFragments()
i += 1

class Paragraph(Flowable):
"""A simple Paragraph class respecting alignment.
Expand Down Expand Up @@ -911,7 +911,7 @@ def test():
style,
debug=0))

if 0:
if 0: # FIXME: Why is this here?
for i in range(10):
style = copy.deepcopy(style)
style["textAlign"] = ALIGNMENTS[i % 4]
Expand All @@ -937,7 +937,7 @@ def test2():

# test2()

if 1:
if 1: # FIXME: Again, why this? And the commented lines around here.
test()
os.system("start test.pdf")

Expand Down
2 changes: 1 addition & 1 deletion xhtml2pdf/pdf.py
Expand Up @@ -50,7 +50,7 @@ def join(self, file=None):
output = pyPdf.PdfFileWriter()
for pdffile in self.files:
input = pyPdf.PdfFileReader(pdffile)
for pageNumber in range(0, input.getNumPages()):
for pageNumber in xrange(input.getNumPages()):
output.addPage(input.getPage(pageNumber))
if file is not None:
output.write(file)
Expand Down
2 changes: 1 addition & 1 deletion xhtml2pdf/pisa.py
Expand Up @@ -377,7 +377,7 @@ def execute():
if dest_part.lower().endswith(".html") or dest_part.lower().endswith(".htm"):
dest_part = ".".join(src.split(".")[:-1])
dest = dest_part + "." + format.lower()
for i in range(10):
for i in xrange(10):
try:
open(dest, "wb").close()
break
Expand Down
4 changes: 2 additions & 2 deletions xhtml2pdf/tables.py
Expand Up @@ -295,8 +295,8 @@ def start(self, c):
if begin != end:
#~ print begin, end
tdata.add_style(('SPAN', begin, end))
for x in range(begin[0], end[0] + 1):
for y in range(begin[1], end[1] + 1):
for x in xrange(begin[0], end[0] + 1):
for y in xrange(begin[1], end[1] + 1):
if x != begin[0] or y != begin[1]:
tdata.add_empty(x, y)

Expand Down
61 changes: 26 additions & 35 deletions xhtml2pdf/xhtml2pdf_reportlab.py
Expand Up @@ -175,11 +175,10 @@ def handle_nextPageTemplate(self, pt):
raise TypeError("Argument pt should be string or integer or list")

def _has_template_for_name(self, name):
result = False
for template in self.pageTemplates:
if template.id == name.strip():
result = True
return result
return True
return False


class PmlPageTemplate(PageTemplate):
Expand Down Expand Up @@ -409,8 +408,7 @@ def getRGBData(self):
# I just haven't found it yet...
pixels = []
a = pixels.append
for i in range(len(buffer)):
rgb = buffer[i]
for rgb in buffer:
a(chr((rgb >> 16) & 0xff))
a(chr((rgb >> 8) & 0xff))
a(chr(rgb & 0xff))
Expand All @@ -437,17 +435,16 @@ def getImageData(self):
def getTransparent(self):
if sys.platform[0:4] == 'java':
return None
elif "transparency" in self._image.info:
transparency = self._image.info["transparency"] * 3
palette = self._image.palette
try:
palette = palette.palette
except:
palette = palette.data
return map(ord, palette[transparency:transparency + 3])
else:
if self._image.info.has_key("transparency"):
transparency = self._image.info["transparency"] * 3
palette = self._image.palette
try:
palette = palette.palette
except:
palette = palette.data
return map(ord, palette[transparency:transparency + 3])
else:
return None
return None

def __str__(self):
try:
Expand Down Expand Up @@ -762,8 +759,7 @@ def wrap(self, availWidth, availHeight):
# Calculate widths that are fix
# IMPORTANT!!! We can not substitute the private value
# self._colWidths therefore we have to modify list in place
for i in range(len(newColWidths)):
colWidth = newColWidths[i]
for i, colWidth in enumerate(newColWidths):
if (colWidth is not None) or (colWidth == '*'):
colWidth = self._normWidth(colWidth, totalWidth)
remainingWidth -= colWidth
Expand All @@ -775,8 +771,8 @@ def wrap(self, availWidth, availHeight):
# Distribute remaining space
minCellWidth = totalWidth * 0.01
if remainingCols > 0:
for i in range(len(newColWidths)):
if newColWidths[i] is None:
for i, colWidth in enumerate(newColWidths):
if colWidth is None:
# print "*** ", i, newColWidths[i], remainingWidth, remainingCols
newColWidths[i] = max(minCellWidth, remainingWidth / remainingCols) # - 0.1

Expand All @@ -790,8 +786,7 @@ def wrap(self, availWidth, availHeight):
if sum(newColWidths) > totalWidth:
quotient = totalWidth / sum(newColWidths)
# print quotient
for i in range(len(newColWidths)):
newColWidths[i] = newColWidths[i] * quotient
newColWidths = [w * quotient for w in newColWidths]

# To avoid rounding errors adjust one col with the difference
diff = sum(newColWidths) - totalWidth
Expand Down Expand Up @@ -834,7 +829,6 @@ def wrap(self, availWidth, availHeight):
else:
_tempEntries = self._lastEntries

i = 0
lastMargin = 0
tableData = []
tableStyle = [
Expand All @@ -844,7 +838,7 @@ def wrap(self, availWidth, availHeight):
('TOPPADDING', (0, 0), (- 1, - 1), 0),
('BOTTOMPADDING', (0, 0), (- 1, - 1), 0),
]
for entry in _tempEntries:
for i, entry in enumerate(_tempEntries):
level, text, pageNum = entry[:3]
leftColStyle = self.levelStyles[level]
if i: # Not for first element
Expand All @@ -862,15 +856,14 @@ def wrap(self, availWidth, availHeight):
leftPara = Paragraph(text, leftColStyle)
rightPara = Paragraph(str(pageNum), rightColStyle)
tableData.append([leftPara, rightPara])
i += 1

self._table = Table(
tableData,
colWidths=widths,
style=TableStyle(tableStyle))

self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight)
return (self.width, self.height)
return self.width, self.height


class PmlRightPageBreak(CondPageBreak):
Expand All @@ -879,13 +872,12 @@ def __init__(self):
pass

def wrap(self, availWidth, availHeight):
if (0 == (self.canv.getPageNumber() % 2)):
if not self.canv.getPageNumber() % 2:
self.width = availWidth
self.height = availHeight
return (availWidth, availHeight)
self.width = 0
self.height = 0
return (0, 0)
return availWidth, availHeight
self.width = self.height = 0
return 0, 0


class PmlLeftPageBreak(CondPageBreak):
Expand All @@ -894,13 +886,12 @@ def __init__(self):
pass

def wrap(self, availWidth, availHeight):
if (1 == (self.canv.getPageNumber() % 2)):
if self.canv.getPageNumber() % 2:
self.width = availWidth
self.height = availHeight
return (availWidth, availHeight)
self.width = 0
self.height = 0
return (0, 0)
return availWidth, availHeight
self.width = self.height = 0
return 0, 0

# --- Pdf Form

Expand Down

0 comments on commit 5bc1328

Please sign in to comment.