本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.stringWidth方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.stringWidth方法的具体用法?Python Canvas.stringWidth怎么用?Python Canvas.stringWidth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.stringWidth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def test0(self):
"A basic document drawing some strings"
c = Canvas(outputfile('test_multibyte_jpn.pdf'))
c.setFont('Helvetica', 30)
c.drawString(100,700, 'Japanese Font Support')
c.setStrokeColor(colors.red)
#unicode font automatically supplies the encoding
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3'))
msg = u'\u6771\u4EAC : Unicode font, unicode input'
self.hDraw(c, msg, 'HeiseiMin-W3', 100, 600)
msg = u'\u6771\u4EAC : Unicode font, utf8 input'.encode('utf8')
self.hDraw(c, msg, 'HeiseiMin-W3', 100, 575)
# now try verticals - this is broken, not sure how to make it
# work in post Unicode world.
pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-V'))
c.setFont('HeiseiMin-W3-90ms-RKSJ-V', 16)
c.drawString(450, 650, '\223\214\213\236 vertical Shift-JIS')
height = c.stringWidth('\223\214\213\236 vertical Shift-JIS', 'HeiseiMin-W3-90ms-RKSJ-V', 16)
c.rect(450-8,650,16,-height)
pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','EUC-V'))
c.setFont('HeiseiMin-W3-EUC-V', 16)
c.drawString(475, 650, '\xC5\xEC\xB5\xFE vertical EUC')
height = c.stringWidth('\xC5\xEC\xB5\xFE vertical EUC', 'HeiseiMin-W3-EUC-V', 16)
c.rect(475-8,650,16,-height)
from reportlab.platypus.paragraph import Paragraph
from reportlab.lib.styles import ParagraphStyle
jStyle = ParagraphStyle('jtext',
fontName='HeiseiMin-W3',
fontSize=12,
wordWrap="CJK"
)
gatwickText = '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99\xe3\x81\x97\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
gatwickText2= '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf<font color=red>\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90</font>\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88<link fg="blue" href="http://www.reportlab.com">\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99</link>\xe3\x81\x97\xe3\x81\xa6<u>\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99</u>\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
c.setFont('HeiseiMin-W3', 12)
jPara = Paragraph(gatwickText, jStyle)
jPara.wrap(300, 200)
jPara.drawOn(c, 100, 220)
jPara = Paragraph(gatwickText2, jStyle)
jPara.wrap(300, 200)
jPara.drawOn(c, 100, 320)
c.setFillColor(colors.purple)
tx = c.beginText(100, 200)
tx.setFont('Helvetica', 12)
tx.textLines("""This document shows sample output in Japanese
from the Reportlab PDF library. This page shows the two fonts
available and tests our ability to measure the width of glyphs
in both horizontal and vertical writing, with proportional and
fixed-width characters. The red boxes should be the same width
(or height) as the character strings they surround.
The next pages show more samples and information.
""")
c.drawText(tx)
c.setFont('Helvetica',10)
c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())
c.showPage()
c.setFont('Helvetica', 30)
c.drawString(100,700, 'Japanese TrueType Font Support')
msg = u'\u6771\u4EAC : Unicode font'.encode('utf8')
msg2 = u'utf8 input 0123456789 ABCDEF'.encode('utf8')
from reportlab.pdfbase.ttfonts import TTFont
try:
msmincho = TTFont('MS Mincho','msmincho.ttc',subfontIndex=0,asciiReadable=0)
fn = ' file=msmincho.ttc subfont 0'
except:
try:
msmincho = TTFont('MS Mincho','msmincho.ttf',asciiReadable=0)
fn = 'file=msmincho.ttf'
except:
#Ubuntu - works on Lucid Lynx if xpdf-japanese installed
try:
msmincho = TTFont('MS Mincho','ttf-japanese-mincho.ttf')
fn = 'file=msmincho.ttf'
except:
msmincho = None
if msmincho is None:
c.setFont('Helvetica', 12)
c.drawString(100,600, 'Cannot find msmincho.ttf or msmincho.ttc')
else:
#.........这里部分代码省略.........
示例2: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def test0(self):
"""Make documents with embedded fonts.
Just vam Rossum has kindly donated a font which we may use
for testing purposes. You need to contact him at [email protected]
if you want to use it for real."""
#LettError fonts should always be there. The others are voluntary.
ok = 1
c = Canvas(outputfile('test_pdfbase_fontembed.pdf'))
c.setPageCompression(0)
c.setFont('Helvetica', 12)
c.drawString(100, 700, 'This is Helvetica. The text below should be different fonts...')
if os.path.isfile('GDB_____.AFM') and os.path.isfile('GDB_____.PFB'):
# a normal text font
garaFace = pdfmetrics.EmbeddedType1Face('GDB_____.AFM','GDB_____.PFB')
faceName = 'AGaramond-Bold' # pulled from AFM file
pdfmetrics.registerTypeFace(garaFace)
garaFont = pdfmetrics.Font('MyGaramondBold', faceName, 'WinAnsiEncoding')
pdfmetrics.registerFont(garaFont)
c.setFont('AGaramond-Bold', 12)
c.drawString(100, 650, 'This should be in AGaramond-Bold')
if os.path.isfile('CR______.AFM') and os.path.isfile('CR______.PFB'):
# one with a custom encoding
cartaFace = pdfmetrics.EmbeddedType1Face('CR______.AFM','CR______.PFB')
faceName = 'Carta' # pulled from AFM file
pdfmetrics.registerTypeFace(cartaFace)
cartaFont = pdfmetrics.Font('Carta', 'Carta', 'CartaEncoding')
pdfmetrics.registerFont(cartaFont)
text = 'This should be in Carta, a map symbol font:'
c.setFont('Helvetica', 12)
c.drawString(100, 600, text)
w = c.stringWidth(text, 'Helvetica', 12)
c.setFont('Carta', 12)
c.drawString(100+w, 600, ' Hello World')
# LettError sample - creates on demand, we hope
y = 550
## justFace = pdfmetrics.EmbeddedType1Face('LeERC___.AFM','LeERC___.PFB')
##
## faceName = 'LettErrorRobot-Chrome' # pulled from AFM file
## pdfmetrics.registerTypeFace(justFace)
##
## justFont = pdfmetrics.Font('LettErrorRobot-Chrome', faceName, 'WinAnsiEncoding')
## pdfmetrics.registerFont(justFont)
c.setFont('LettErrorRobot-Chrome', 12)
c.drawString(100, y, 'This should be in LettErrorRobot-Chrome')
def testNamedFont(canv, fontName):
canv.showPage()
makeWidthTestForAllGlyphs(canv, fontName, outlining=0)
testNamedFont(c, 'LettErrorRobot-Chrome')
c.save()
示例3: main
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def main():
pdfmetrics.registerFont(TTFont('Dosis', 'Dosis-Medium.ttf'))
stars = []
with open('bsc5.dat', 'rb') as f:
for line in f:
line = '.' + line # switch to 1-based indexing
if not line[62].strip():
continue # skip coordinate-less novas
letter = intern(line[8:11])
if letter == ' ':
letter = None
h, m, s = float(line[61:63]), float(line[63:65]), float(line[65:69])
ra = (h + (m + s / 60.0) / 60.0) * tau / 24.0
d, m, s = float(line[69:72]), float(line[72:74]), float(line[76:78])
dec = (d + (m + s / 60.0) / 60.0) * tau / 360.0
mag = float(line[103:108])
stars.append((letter, ra, dec, mag))
h, w = 48, 96
c = Canvas('logo.pdf', pagesize=(w, h))
c.setFillColor('white')
c.rect(0, 0, w, h, stroke=0, fill=1)
c.setFillColor(bright_star_color)
rotation = 10.0 * tau / 360.0
# magscale = 0.1
# For 10 degrees:
x_offset = 96 -33.5
y_offset = h +37.5
# For 15 degrees:
# x_offset = 96 -28.5
# y_offset = 96 +0.5
# for 45 degrees:
# x_offset = 96 -13.5
# y_offset = 96 -10
small_glyphs = []
c.setFont('Helvetica', 2)
for letter, ra, dec, mag in stars:
# if mag > 4.0:
# continue
d = - (dec - quarter_tau) * 100
ra += rotation
x = d * sin(ra)
y = d * cos(ra)
if y < -63.0 or y > -39.0:
continue
if x < -43.0 or x > 19.0:
continue
x += x_offset
y += y_offset
r = ((13.0 - mag) / 10.0) ** 4.0 #* magscale
r = min(r, 1.0)
if r < 0.5:
small_glyphs.append((x, y, r))
else:
if letter is not None:
c.saveState()
greek_letter, offset = greeks[letter]
c.setFillColor(greek_color)
c.drawString(x+offset, y+0.5, greek_letter)
if letter == 'Alp':
c.setFillColor(alpha_star_color)
c.circle(x, y, r, stroke=0, fill=1)
c.restoreState()
if letter != 'Alp':
c.circle(x, y, r, stroke=0, fill=1)
else:
c.circle(x, y, r, stroke=0, fill=1)
c.setFillColor(dim_star_color)
for x, y, r in small_glyphs:
c.circle(x, y, r, stroke=0, fill=1)
c.setFillColor(text_color) #, alpha=0.5)
c.setFont('Dosis', 24)
sw = c.stringWidth('Skyfield')
c.drawString(w // 2 - sw // 2, h - 40, 'Skyfield')
c.showPage()
with open('logo.pdf', 'wb') as f:
f.write(c.getpdfdata())
示例4: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def test0(self):
"Make custom encodings of standard fonts"
# make a custom encoded font.
c = Canvas(outputfile('test_pdfbase_encodings.pdf'))
c.setPageCompression(0)
c.setFont('Helvetica', 12)
c.drawString(100, 700, 'The text below should be in a custom encoding in which all vowels become "z"')
# invent a new language where vowels are replaced with letter 'z'
zenc = pdfmetrics.Encoding('EncodingWithoutVowels', 'WinAnsiEncoding')
for ch in 'aeiou':
zenc[ord(ch)] = 'z'
for ch in 'AEIOU':
zenc[ord(ch)] = 'Z'
pdfmetrics.registerEncoding(zenc)
# now we can make a font based on this encoding
# AR hack/workaround: the name of the encoding must be a Python codec!
f = pdfmetrics.Font('FontWithoutVowels', 'Helvetica-Oblique', 'EncodingWithoutVowels')
pdfmetrics.registerFont(f)
c.setFont('FontWithoutVowels', 12)
c.drawString(125, 675, "The magic word is squamish ossifrage")
# now demonstrate adding a Euro to MacRoman, which lacks one
c.setFont('Helvetica', 12)
c.drawString(100, 650, "MacRoman encoding lacks a Euro. We'll make a Mac font with the Euro at #219:")
# WinAnsi Helvetica
pdfmetrics.registerFont(pdfmetrics.Font('Helvetica-WinAnsi', 'Helvetica-Oblique', 'WinAnsiEncoding'))
c.setFont('Helvetica-WinAnsi', 12)
c.drawString(125, 625, 'WinAnsi with Euro: character 128 = "\200"')
pdfmetrics.registerFont(pdfmetrics.Font('MacHelvNoEuro', 'Helvetica-Oblique', 'MacRomanEncoding'))
c.setFont('MacHelvNoEuro', 12)
c.drawString(125, 600, 'Standard MacRoman, no Euro: Character 219 = "\333"') # oct(219)=0333
# now make our hacked encoding
euroMac = pdfmetrics.Encoding('MacWithEuro', 'MacRomanEncoding')
euroMac[219] = 'Euro'
pdfmetrics.registerEncoding(euroMac)
pdfmetrics.registerFont(pdfmetrics.Font('MacHelvWithEuro', 'Helvetica-Oblique', 'MacWithEuro'))
c.setFont('MacHelvWithEuro', 12)
c.drawString(125, 575, 'Hacked MacRoman with Euro: Character 219 = "\333"') # oct(219)=0333
# now test width setting with and without _rl_accel - harder
# make an encoding where 'm' becomes 'i'
c.setFont('Helvetica', 12)
c.drawString(100, 500, "Recode 'm' to 'i' and check we can measure widths. Boxes should surround letters.")
sample = 'Mmmmm. ' * 6 + 'Mmmm'
c.setFont('Helvetica-Oblique',12)
c.drawString(125, 475, sample)
w = c.stringWidth(sample, 'Helvetica-Oblique', 12)
c.rect(125, 475, w, 12)
narrowEnc = pdfmetrics.Encoding('m-to-i')
narrowEnc[ord('m')] = 'i'
narrowEnc[ord('M')] = 'I'
pdfmetrics.registerEncoding(narrowEnc)
pdfmetrics.registerFont(pdfmetrics.Font('narrow', 'Helvetica-Oblique', 'm-to-i'))
c.setFont('narrow', 12)
c.drawString(125, 450, sample)
w = c.stringWidth(sample, 'narrow', 12)
c.rect(125, 450, w, 12)
c.setFont('Helvetica', 12)
c.drawString(100, 400, "Symbol & Dingbats fonts - check we still get valid PDF in StandardEncoding")
c.setFont('Symbol', 12)
c.drawString(100, 375, 'abcdefghijklmn')
c.setFont('ZapfDingbats', 12)
c.drawString(300, 375, 'abcdefghijklmn')
c.save()
示例5: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def test0(self):
"A basic document drawing some strings"
# if they do not have the Japanese font files, go away quietly
try:
from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile
findCMapFile("90ms-RKSJ-H")
findCMapFile("90msp-RKSJ-H")
findCMapFile("UniJIS-UCS2-H")
findCMapFile("EUC-H")
except:
# don't have the font pack. return silently
return
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "90ms-RKSJ-H"))
pdfmetrics.registerFont(CIDFont("HeiseiKakuGo-W5", "90ms-RKSJ-H"))
c = Canvas(outputfile("test_multibyte_jpn.pdf"))
c.setFont("Helvetica", 30)
c.drawString(100, 700, "Japanese Font Support")
c.setStrokeColor(colors.red)
# the two typefaces
c.setFont("HeiseiMin-W3-90ms-RKSJ-H", 16)
# this says "This is HeiseiMincho" in shift-JIS. Not all our readers
# have a Japanese PC, so I escaped it. On a Japanese-capable
# system, print the string to see Kanji
message1 = "\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B"
c.drawString(100, 675, message1)
wid = pdfmetrics.stringWidth(message1, "HeiseiMin-W3-90ms-RKSJ-H", 16)
c.rect(100, 675, wid, 16, stroke=1, fill=0)
c.setFont("HeiseiKakuGo-W5-90ms-RKSJ-H", 16)
# this says "This is HeiseiKakugo" in shift-JIS
message2 = "\202\261\202\352\202\315\225\275\220\254\212p\203S\203V\203b\203N\202\305\202\267\201B"
c.drawString(100, 650, message2)
wid = pdfmetrics.stringWidth(message2, "HeiseiKakuGo-W5-90ms-RKSJ-H", 16)
c.rect(100, 650, wid, 16, stroke=1, fill=0)
self.hDraw(c, "\223\214\213\236 says Tokyo in Shift-JIS", "HeiseiMin-W3-90ms-RKSJ-H", 100, 600)
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "90msp-RKSJ-H"))
self.hDraw(c, "\223\214\213\236, but in proportional Shift-JIS.", "HeiseiMin-W3-90msp-RKSJ-H", 100, 575)
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "EUC-H"))
self.hDraw(c, "\xC5\xEC\xB5\xFE says Tokyo in EUC", "HeiseiMin-W3-EUC-H", 100, 550)
if 0:
# this is super-slow until we do encoding caching.
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "UniJIS-UCS2-H"))
def asciiToUCS2(text):
s = ""
for ch in text:
s = s + chr(0) + ch
return s
self.hDraw(
c, "\x67\x71\x4E\xAC" + asciiToUCS2(" says Tokyo in UCS2"), "HeiseiMin-W3-UniJIS-UCS2-H", 100, 525
)
# now try verticals
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "90ms-RKSJ-V"))
c.setFont("HeiseiMin-W3-90ms-RKSJ-V", 16)
c.drawString(400, 650, "\223\214\213\236 vertical Shift-JIS")
height = c.stringWidth("\223\214\213\236 vertical Shift-JIS", "HeiseiMin-W3-90ms-RKSJ-V", 16)
c.rect(400 - 8, 650, 16, -height)
pdfmetrics.registerFont(CIDFont("HeiseiMin-W3", "EUC-V"))
c.setFont("HeiseiMin-W3-EUC-V", 16)
c.drawString(425, 650, "\xC5\xEC\xB5\xFE vertical EUC")
height = c.stringWidth("\xC5\xEC\xB5\xFE vertical EUC", "HeiseiMin-W3-EUC-V", 16)
c.rect(425 - 8, 650, 16, -height)
c.setFillColor(colors.purple)
tx = c.beginText(100, 250)
tx.setFont("Helvetica", 12)
tx.textLines(
"""This document shows sample output in Japanese
from the Reportlab PDF library. This page shows the two fonts
available and tests our ability to measure the width of glyphs
in both horizontal and vertical writing, with proportional and
fixed-width characters. The red boxes should be the same width
(or height) as the character strings they surround.
The next pages show more samples and information.
"""
)
c.drawText(tx)
c.setFont("Helvetica", 10)
c.drawCentredString(297, 36, "Page %d" % c.getPageNumber())
c.showPage()
# realistic text sample
sample = """Adobe Acrobat
\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xaa\x8aJ\x82\xa9\x82\xc8\x82\xad\x82\xc4\x8d\xa2\x82\xc1\x82\xbd\x82\xb1\x82\xc6\x82\xcd
\x82\xa0\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x82\xa9\x81B\x8e\x96\x8b\xc6\x8cv\x89\xe6\x8f\x91\x81A\x89c\x8b\xc6\x83\x8c\x83|\x81[\x83g
\x81A\x83J\x83^\x83\x8d\x83O\x82\xe2\x83p\x83\x93\x83t\x83\x8c\x83b\x83g\x82\xc8\x82\xc7\x90\xa7\x8d\xec\x95\xa8\x82\xcc\x8e\xed
\x97\xde\x82\xc9\x82\xa9\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A
#.........这里部分代码省略.........
示例6: get_text_width
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def get_text_width(font, size, text):
c = Canvas(test,pagesize=pagesize)
length= c.stringWidth(str(text),font,size)
return length
示例7: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def test0(self):
"""Make documents with embedded fonts.
Just vam Rossum has kindly donated a font which we may use
for testing purposes. You need to contact him at [email protected]
if you want to use it for real."""
# LettError fonts should always be there. The others are voluntary.
ok = 1
c = Canvas(outputfile("test_pdfbase_fontembed.pdf"))
c.setPageCompression(0)
c.setFont("Helvetica", 12)
c.drawString(100, 700, "This is Helvetica. The text below should be different fonts...")
if os.path.isfile("GDB_____.AFM") and os.path.isfile("GDB_____.PFB"):
# a normal text font
garaFace = pdfmetrics.EmbeddedType1Face("GDB_____.AFM", "GDB_____.PFB")
faceName = "AGaramond-Bold" # pulled from AFM file
pdfmetrics.registerTypeFace(garaFace)
garaFont = pdfmetrics.Font("MyGaramondBold", faceName, "WinAnsiEncoding")
pdfmetrics.registerFont(garaFont)
c.setFont("AGaramond-Bold", 12)
c.drawString(100, 650, "This should be in AGaramond-Bold")
if os.path.isfile("CR______.AFM") and os.path.isfile("CR______.PFB"):
# one with a custom encoding
cartaFace = pdfmetrics.EmbeddedType1Face("CR______.AFM", "CR______.PFB")
faceName = "Carta" # pulled from AFM file
pdfmetrics.registerTypeFace(cartaFace)
cartaFont = pdfmetrics.Font("Carta", "Carta", "CartaEncoding")
pdfmetrics.registerFont(cartaFont)
text = "This should be in Carta, a map symbol font:"
c.setFont("Helvetica", 12)
c.drawString(100, 600, text)
w = c.stringWidth(text, "Helvetica", 12)
c.setFont("Carta", 12)
c.drawString(100 + w, 600, " Hello World")
# LettError sample - creates on demand, we hope
y = 550
## dgmkFace = pdfmetrics.EmbeddedType1Face('DarkGardenMK.afm','DarkGardenMK.PFB')
##
## faceName = 'DarkGardenMK' # pulled from AFM file
## pdfmetrics.registerTypeFace(dgmkFace)
##
## dgmkFont = pdfmetrics.Font('DarkGardenMK', faceName, 'WinAnsiEncoding')
## pdfmetrics.registerFont(dgmk)
c.setFont("DarkGardenMK", 12)
c.drawString(100, y, "This should be in DarkGardenMK")
def testNamedFont(canv, fontName):
canv.showPage()
makeWidthTestForAllGlyphs(canv, fontName, outlining=0)
testNamedFont(c, "DarkGardenMK")
c.save()
示例8:
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
# Busy with "header"
pdf.setTitle(TITLE)
pdf.setSubject(SUBJECT)
# pdf.setKeywords(KEYWORDS) # not working?
pdf.setAuthor(AUTHOR)
# Putting the 3 images
pdf.drawInlineImage("images/tchantchux.jpg", 40, 240, width=158, height=283)
pdf.drawImage("images/logo-lilit.png", 40, 40, width=None, height=None, mask=[255, 255, 255, 255, 226, 226])
pdf.drawInlineImage("images/penguin.png", 600, 250, width=217, height=260)
# Putting the central text
pdf.setFont(FONT, FONTSIZE) # xème journée d'installation de
pdf.setFillColorRGB(255, 0, 0)
chaine = NUMBER + " journée d'installation de"
x = pdf.stringWidth(chaine, FONTBOLD, FONTSIZE)
pdf.drawString(centerh - x/2, 530, chaine)
xx = pdf.stringWidth(NUMBER, FONTBOLD, FONTSIZE) # superscript in the previous string
pdf.setFont(FONT, FONTSIZE2)
chaine = "ème"
pdf.drawString(centerh - x/2 + xx, 540, chaine)
pdf.setFont(FONTBOLD, FONTSIZE) # GNU/Linux
pdf.setFillColorRGB(0, 0, 0)
chaine = "GNU/Linux"
x = pdf.stringWidth(chaine, FONTBOLD, FONTSIZE)
pdf.drawString(centerh - x/2, 480, chaine)
pdf.setFont(FONT, FONTSIZE) # sur votre machine
chaine = "sur votre machine"
x = pdf.stringWidth(chaine, FONT, FONTSIZE)
pdf.drawString(centerh - x/2, 440, chaine)
pdf.setFont(FONTBOLD, FONTSIZE) # date
示例9: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
#.........这里部分代码省略.........
vprint( WARN, "Warning: DPI unavailable for image %s. Assuming 96 DPI."%(imageFileName) )
width = float(im.size[0])/96
height = float(im.size[1])/96
# PDF page size
pdf.setPageSize((width*inch, height*inch)) # page size in points (1/72 in.)
# put the image on the page, scaled to fill the page
if withVisibleImage:
if im:
pdf.drawInlineImage(im, 0, 0, width=width*inch, height=height*inch)
else:
vprint( INFO, "No inline image file supplied." )
# put ocr-content on the page
if self.hocr is not None:
text_elements = self.getTextElements( page )
for line in text_elements:
import pdb
vprint( VVERBOSE, line.tag, line.attrib )
if line.attrib.has_key('class'):
text_class = line.attrib['class']
else:
text_class = None
if text_class in [ 'ocr_line', 'ocrx_word', 'ocr_carea', 'ocr_par' ]:
if text_class == 'ocr_line':
textColor = (255,0,0)
bboxColor = (0,255,0)
elif text_class == 'ocrx_word' :
textColor = (255,0,0)
bboxColor = (0,255,255)
elif text_class == 'ocr_carea' :
textColor = (255,0,0)
bboxColor = (255,255,0)
elif text_class == 'ocr_par' :
textColor = (255,0,0)
bboxColor = (255,0,0)
coords = self.element_coordinates( line )
parse_result = self.parse_element_title( line )
text = pdf.beginText()
text.setFont(fontname, fontsize)
text_corner1x = (float(coords[0])/ocr_dpi[0])*inch
text_corner1y = (float(coords[1])/ocr_dpi[1])*inch
text_corner2x = (float(coords[2])/ocr_dpi[0])*inch
text_corner2y = (float(coords[3])/ocr_dpi[1])*inch
text_width = text_corner2x - text_corner1x
text_height = text_corner2y - text_corner1y
if verticalInversion:
text_corner2y_inv = (height*inch) - text_corner1y
text_corner1y_inv = (height*inch) - text_corner2y
text_corner1y = text_corner1y_inv
text_corner2y = text_corner2y_inv
# set cursor to bottom left corner of line bbox (adjust for dpi)
text.setTextOrigin( text_corner1x, text_corner1y )
# The content of the text to write
textContent = line.text
if ( textContent == None ):
textContent = u""
textContent = textContent.rstrip()
# scale the width of the text to fill the width of the line's bbox
if len(textContent) != 0:
text.setHorizScale( ((( float(coords[2])/ocr_dpi[0]*inch ) - ( float(coords[0])/ocr_dpi[0]*inch )) / pdf.stringWidth( textContent, fontname, fontsize))*100)
if not withVisibleOCRText:
text.setTextRenderMode(3) # invisible
# Text color
text.setFillColorRGB(textColor[0],textColor[1],textColor[2])
# write the text to the page
text.textLine( textContent )
vprint( VVERBOSE, "processing", text_class, coords,"->", text_corner1x, text_corner1y, text_corner2x, text_corner2y, ":", textContent )
pdf.drawText(text)
pdf.setLineWidth(0.1)
pdf.setStrokeColorRGB(bboxColor[0],bboxColor[1],bboxColor[2])
# Draw a box around the text object
if withVisibleBoundingBoxes:
pdf.rect( text_corner1x, text_corner1y, text_width, text_height);
# finish up the page. A blank new one is initialized as well.
pdf.showPage()
# save the pdf file
vprint( INFO, "Writing pdf." )
pdf.save()
示例10: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def to_pdf(self, imageFileName, outFileName, fontname="Courier", fontsize=8):
"""
Creates a PDF file with an image superimposed on top of the text.
Text is positioned according to the bounding box of the lines in
the hOCR file.
The image need not be identical to the image used to create the hOCR file.
It can be scaled, have a lower resolution, different color mode, etc.
"""
if self.hocr is None:
# warn that no text will be embedded in the output PDF
print "Warning: No hOCR file specified. PDF will be image-only."
im = Image.open(imageFileName)
imwidthpx, imheightpx = im.size
if 'dpi' in im.info:
width = float(im.size[0])/im.info['dpi'][0]
height = float(im.size[1])/im.info['dpi'][1]
else:
# we have to make a reasonable guess
# set to None for now and try again using info from hOCR file
width = height = None
ocr_dpi = (300, 300) # a default, in case we can't find it
# get dimensions of the OCR, which may not match the image
if self.hocr is not None:
for div in self.hocr.findall(".//%sdiv"%(self.xmlns)):
if div.attrib['class'] == 'ocr_page':
coords = self.element_coordinates(div)
ocrwidth = coords[2]-coords[0]
ocrheight = coords[3]-coords[1]
if width is None:
# no dpi info with the image
# assume OCR was done at 300 dpi
width = ocrwidth/300
height = ocrheight/300
ocr_dpi = (ocrwidth/width, ocrheight/height)
break # there shouldn't be more than one, and if there is, we don't want it
if width is None:
# no dpi info with the image, and no help from the hOCR file either
# this will probably end up looking awful, so issue a warning
print "Warning: DPI unavailable for image %s. Assuming 96 DPI."%(imageFileName)
width = float(im.size[0])/96
height = float(im.size[1])/96
# create the PDF file
pdf = Canvas(outFileName, pagesize=(width*inch, height*inch), pageCompression=1) # page size in points (1/72 in.)
# put the image on the page, scaled to fill the page
pdf.drawInlineImage(im, 0, 0, width=width*inch, height=height*inch)
if self.hocr is not None:
for line in self.hocr.findall(".//%sspan"%(self.xmlns)):
if line.attrib['class'] == 'ocr_line':
coords = self.element_coordinates(line)
text = pdf.beginText()
text.setFont(fontname, fontsize)
text.setTextRenderMode(3) # invisible
# set cursor to bottom left corner of line bbox (adjust for dpi)
text.setTextOrigin((float(coords[0])/ocr_dpi[0])*inch, (height*inch)-(float(coords[3])/ocr_dpi[1])*inch)
# scale the width of the text to fill the width of the line's bbox
text.setHorizScale((((float(coords[2])/ocr_dpi[0]*inch)-(float(coords[0])/ocr_dpi[0]*inch))/pdf.stringWidth(line.text.rstrip(), fontname, fontsize))*100)
# write the text to the page
text.textLine(line.text.rstrip())
pdf.drawText(text)
# finish up the page and save it
pdf.showPage()
pdf.save()
示例11: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def to_pdf(self, imageFileName, outFileName, fontname="Times-Roman", fontsize=10, withVisibleOCRText=False, withVisibleImage=True, withVisibleBoundingBoxes=False):
"""
Creates a PDF file with an image superimposed on top of the text.
Text is positioned according to the bounding box of the lines in
the hOCR file.
The image need not be identical to the image used to create the hOCR file.
It can be scaled, have a lower resolution, different color mode, etc.
"""
if self.hocr is None:
# warn that no text will be embedded in the output PDF
print "Warning: No hOCR file specified. PDF will be image-only."
im = Image.open(imageFileName)
imwidthpx, imheightpx = im.size
if 'dpi' in im.info:
width = float(im.size[0])/im.info['dpi'][0]
height = float(im.size[1])/im.info['dpi'][1]
else:
# we have to make a reasonable guess
# set to None for now and try again using info from hOCR file
width = height = None
ocr_dpi = (300, 300) # a default, in case we can't find it
# get dimensions of the OCR, which may not match the image
if self.hocr is not None:
for div in self.hocr.findall(".//%sdiv"%(self.xmlns)):
if div.attrib['class'] == 'ocr_page':
coords = self.element_coordinates(div)
ocrwidth = coords[2]-coords[0]
ocrheight = coords[3]-coords[1]
if width is None:
# no dpi info with the image
# assume OCR was done at 300 dpi
width = ocrwidth/300
height = ocrheight/300
ocr_dpi = (ocrwidth/width, ocrheight/height)
break # there shouldn't be more than one, and if there is, we don't want it
if width is None:
# no dpi info with the image, and no help from the hOCR file either
# this will probably end up looking awful, so issue a warning
print "Warning: DPI unavailable for image %s. Assuming 96 DPI."%(imageFileName)
width = float(im.size[0])/96
height = float(im.size[1])/96
# create the PDF file
pdf = Canvas(outFileName, pagesize=(width*inch, height*inch), pageCompression=1) # page size in points (1/72 in.)
# put the image on the page, scaled to fill the page
if withVisibleImage:
pdf.drawInlineImage(im, 0, 0, width=width*inch, height=height*inch)
if self.hocr is not None:
for word in self.hocr.findall(".//%sspan"%(self.xmlns)):
if word.attrib['class'] == 'ocr_word':
coords = self.element_coordinates(word)
content = self._get_element_text(word)
if content.rstrip() == '':
continue
text = pdf.beginText()
text.setFont(fontname, fontsize)
if not withVisibleOCRText:
#text.setTextRenderMode(0) # visible
#else:
text.setTextRenderMode(3) # invisible
# set cursor to bottom left corner of line bbox (adjust for dpi)
# Can't determine original text's baseline, but guess that ypg
# roughly push it down by ~2/3 of line height. Correct for that.
# PDF y coords increase going *up* the page, remember. Assume "o" is
# round so width == line height.
origin_y = (height*inch)-(float(coords[3])/ocr_dpi[1])*inch
if re.search(r"[gjpqy()]", content):
origin_y += pdf.stringWidth("o") * 1/3
if re.search(r"[\[\]()]", content):
origin_y += pdf.stringWidth("o") * 1/3.5
elif re.search(r"[,;]", content):
origin_y += pdf.stringWidth("o") * 1/4
text.setTextOrigin((float(coords[0])/ocr_dpi[0])*inch, origin_y)
# scale the width of the text to fill the width of the line's bbox
text.setHorizScale((((float(coords[2])/ocr_dpi[0]*inch)-(float(coords[0])/ocr_dpi[0]*inch))/pdf.stringWidth(content.rstrip(), fontname, fontsize))*100)
# write the text to the page
text.textLine(content.rstrip())
pdf.drawText(text)
# finish up the page and save it
pdf.showPage()
pdf.save()
示例12: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
#.........这里部分代码省略.........
word_dict = dict()
word_array = dict()
paragraph_count = 0
for paragraph_element in hocr_tree.findall(".//%sp[@class='%s']" % (xmlns, "ocr_par")):
element_text = self._get_element_text(paragraph_element).rstrip()
if len(element_text) == 0:
continue
paragraph_count += 1
word_array[paragraph_count] = {}
if show_bounding_boxes:
x1, y1, x2, y2 = self.convert_px_coordinates_to_pt(self.element_coordinates(paragraph_element), dpi)
self.draw_box(pdf, pt_page_height, x1, y1, x2, y2, lime_green, blue, is_filled=1, line_width=4)
self.annotate_box(
pdf,
x1,
pt_page_height - y1,
"p-%d_%s" % (paragraph_count, paragraph_element.get("id").rsplit("_", 1)[1]),
)
line_count = 0
for line_element in paragraph_element.findall(".//%sspan[@class='%s']" % (xmlns, "ocr_line")):
element_text = self._get_element_text(line_element).rstrip()
if len(element_text) == 0:
continue
line_count += 1
word_array[paragraph_count][line_count] = {}
if show_bounding_boxes:
x1, y1, x2, y2 = self.convert_px_coordinates_to_pt(self.element_coordinates(line_element), dpi)
self.draw_box(pdf, pt_page_height, x1, y1, x2, y2, green, blue, is_filled=1, line_width=1)
self.annotate_box(
pdf,
x1,
pt_page_height - y2,
"l-%d_%s" % (line_count, line_element.get("id").rsplit("_", 1)[1]),
right_align=1,
)
word_count = 0
for word_element in paragraph_element.findall(".//%sspan[@class='%s']" % (xmlns, "ocrx_word")):
element_text = self._get_element_text(word_element).rstrip()
element_text = self.replace_unsupported_chars(element_text)
if len(element_text) == 0:
continue
word_count += 1
coordinates = self.element_coordinates(word_element)
x1, y1, x2, y2 = HocrTransform2.convert_px_coordinates_to_pt(coordinates, dpi)
# draw the bbox border
if show_bounding_boxes:
self.draw_box(pdf, pt_page_height, x1, y1, x2, y2, red, black, line_width=0.5, is_dashed=1)
self.annotate_box(pdf, x1, pt_page_height - y1, "w-%d" % word_count, top_align=1)
# count_path = 'p(%d)l(%d)w(%d)' % (paragraph_count, line_count, word_count)
# id_path = '%s %s %s' % (paragraph_element.get('id'), line_element.get('id'), word_element.get('id'))
# print '%s] %s = "%s"' % (count_path, id_path, element_text)
# word_dict[word_element.attrib['id']] = self._get_element_text(word_element)
# print '%s="%s"' % (word_element.attrib['id'], word_dict[word_element.attrib['id']])
word_array[paragraph_count][line_count][word_count] = {
"p": paragraph_count,
"l": line_count,
"w": word_count,
"id": word_element.attrib["id"],
"word": element_text,
"path": hocr_tree.getpath(word_element),
}
print word_array[paragraph_count][line_count][word_count]
fontsize = self.px2pt(coordinates[3] - coordinates[1], dpi)
pdf.setLineWidth(1)
pdf.setDash([], 0)
pdf.setStrokeColor(black)
pdf.setFillColor(black)
text = pdf.beginText()
text.setTextRenderMode(0)
text.setFont(font_name, fontsize)
text.setTextOrigin(x1, pt_page_height - y2)
text.setHorizScale(100 * (x2 - x1) / pdf.stringWidth(element_text, font_name, fontsize))
text.textLine(element_text)
pdf.drawText(text)
# print "Word Dict"
print word_dict
# print "Word Array"
# print word_array
# pdf.textAnnotation(repr(word_array), name='word_array')
# put the image on the page, scaled to fill the page
if image_filename is not None:
im = Image.open(image_filename)
pdf.drawInlineImage(im, 0, 0, width=pt_page_width, height=pt_page_height)
# finish up the page and save it
pdf.showPage()
pdf.save()
示例13: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
def to_pdf(self, outFileName, imageFileName=None, showBoundingboxes=False,
fontname="Helvetica", invisibleText=False):
"""
Creates a PDF file with an image superimposed on top of the text.
Text is positioned according to the bounding box of the lines in
the hOCR file.
The image need not be identical to the image used to create the hOCR
file.
It can have a lower resolution, different color mode, etc.
"""
# create the PDF file
# page size in points (1/72 in.)
pdf = Canvas(
outFileName, pagesize=(self.width, self.height), pageCompression=1)
# draw bounding box for each paragraph
# light blue for bounding box of paragraph
pdf.setStrokeColorRGB(0, 1, 1)
# light blue for bounding box of paragraph
pdf.setFillColorRGB(0, 1, 1)
pdf.setLineWidth(0) # no line for bounding box
for elem in self.hocr.findall(
".//%sp[@class='%s']" % (self.xmlns, "ocr_par")):
elemtxt = self._get_element_text(elem).rstrip()
if len(elemtxt) == 0:
continue
pxl_coords = self.element_coordinates(elem)
pt = self.pt_from_pixel(pxl_coords)
# draw the bbox border
if showBoundingboxes:
pdf.rect(
pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1,
fill=1)
# check if element with class 'ocrx_word' are available
# otherwise use 'ocr_line' as fallback
elemclass = "ocr_line"
if self.hocr.find(
".//%sspan[@class='ocrx_word']" % (self.xmlns)) is not None:
elemclass = "ocrx_word"
# itterate all text elements
# light green for bounding box of word/line
pdf.setStrokeColorRGB(1, 0, 0)
pdf.setLineWidth(0.5) # bounding box line width
pdf.setDash(6, 3) # bounding box is dashed
pdf.setFillColorRGB(0, 0, 0) # text in black
for elem in self.hocr.findall(
".//%sspan[@class='%s']" % (self.xmlns, elemclass)):
elemtxt = self._get_element_text(elem).rstrip()
elemtxt = self.replace_unsupported_chars(elemtxt)
if len(elemtxt) == 0:
continue
pxl_coords = self.element_coordinates(elem)
pt = self.pt_from_pixel(pxl_coords)
# draw the bbox border
if showBoundingboxes:
pdf.rect(
pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1,
fill=0)
text = pdf.beginText()
fontsize = pt.y2 - pt.y1
text.setFont(fontname, fontsize)
if invisibleText:
text.setTextRenderMode(3) # Invisible (indicates OCR text)
# set cursor to bottom left corner of bbox (adjust for dpi)
text.setTextOrigin(pt.x1, self.height - pt.y2)
# scale the width of the text to fill the width of the bbox
text.setHorizScale(
100 * (pt.x2 - pt.x1) / pdf.stringWidth(
elemtxt, fontname, fontsize))
# write the text to the page
text.textLine(elemtxt)
pdf.drawText(text)
# put the image on the page, scaled to fill the page
if imageFileName is not None:
pdf.drawImage(imageFileName, 0, 0,
width=self.width, height=self.height)
# finish up the page and save it
pdf.showPage()
pdf.save()
示例14: PDFInvoice
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
class PDFInvoice(object):
def __init__(self, recipient, invoicedate, duedate, invoicenum=None, imagedir=None, currency='€', preview=False, receipt=False, bankinfo=True):
self.pdfdata = StringIO.StringIO()
self.canvas = Canvas(self.pdfdata)
self.recipient = recipient
self.invoicenum = invoicenum
self.invoicedate = invoicedate
self.duedate = duedate
self.imagedir = imagedir or '.'
self.currency = currency or '€'
self.preview = preview
self.receipt = receipt
self.bankinfo = bankinfo
self.rows = []
if self.receipt:
# Never include bank info on receipts
self.bankinfo = False
self.canvas.setTitle("PostgreSQL Europe Invoice #%s" % self.invoicenum)
self.canvas.setSubject("PostgreSQL Europe Invoice #%s" % self.invoicenum)
self.canvas.setAuthor("PostgreSQL Europe")
self.canvas._doc.info.producer = "PostgreSQL Europe Invoicing System"
def addrow(self, title, cost, count=1):
self.rows.append((title, cost, count,))
def trimstring(self, s, maxlen, fontname, fontsize):
while len(s) > 5:
if self.canvas.stringWidth(s, fontname, fontsize) <= maxlen:
return s
s = s[:len(s)-2]
return s
def _pageheader(self):
if self.preview:
t = self.canvas.beginText()
t.setTextOrigin(6*cm, 4*cm)
t.setFont("Times-Italic", 70)
t.setFillColorRGB(0.9,0.9,0.9)
t.textLines("PREVIEW PREVIEW")
self.canvas.rotate(45)
self.canvas.drawText(t)
self.canvas.rotate(-45)
im = Image("%s/PostgreSQL_logo.1color_blue.300x300.png" % self.imagedir, width=3*cm, height=3*cm)
im.drawOn(self.canvas, 2*cm, 25*cm)
t = self.canvas.beginText()
t.setFillColorRGB(0,0,0,0)
t.setFont("Times-Roman", 10)
t.setTextOrigin(6*cm, 27.5*cm)
t.textLines("""PostgreSQL Europe
Carpeaux Diem
13, rue du Square Carpeaux
75018 PARIS
France
""")
self.canvas.drawText(t)
t = self.canvas.beginText()
t.setTextOrigin(2*cm, 23*cm)
t.setFont("Times-Roman", 10)
t.textLine("")
t.textLines("""
Your contact: Guillaume Lelarge
Function: PostgreSQL Europe Treasurer
E-mail: [email protected]
""")
self.canvas.drawText(t)
t = self.canvas.beginText()
t.setTextOrigin(11*cm, 23*cm)
t.setFont("Times-Italic", 11)
t.textLine("To:")
t.setFont("Times-Roman", 11)
t.textLines(self.recipient)
self.canvas.drawText(t)
p = self.canvas.beginPath()
p.moveTo(2*cm, 18.9*cm)
p.lineTo(19*cm, 18.9*cm)
self.canvas.drawPath(p)
def save(self):
# We can fit 15 rows on one page. We might want to do something
# cute to avoid a single row on it's own page in the future, but
# for now, just split it evenly.
for pagenum in range(0, (len(self.rows)-1)/15+1):
self._pageheader()
islastpage = (pagenum == (len(self.rows)-1)/15)
if len(self.rows) > 15:
suffix = " (page %s/%s)" % (pagenum+1, len(self.rows)/15+1)
else:
suffix = ''
# Center between 2 and 19 is 10.5
if self.invoicenum:
#.........这里部分代码省略.........
示例15: PDFCreator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import stringWidth [as 别名]
class PDFCreator(object):
appName = "txt2pdf (version 1.0)"
def __init__(self, args, margins):
pageWidth, pageHeight = reportlab.lib.pagesizes.__dict__[args.media]
if args.landscape:
pageWidth, pageHeight = reportlab.lib.pagesizes.landscape(
(pageWidth, pageHeight))
self.author = args.author
self.title = args.title
self.keywords = args.keywords
self.subject = args.subject
self.canvas = Canvas(args.output, pagesize=(pageWidth, pageHeight))
self.canvas.setCreator(self.appName)
if len(args.author) > 0:
self.canvas.setAuthor(args.author)
if len(args.title) > 0:
self.canvas.setTitle(args.title)
if len(args.subject) > 0:
self.canvas.setSubject(args.subject)
if len(args.keywords) > 0:
self.canvas.setKeywords(args.keywords)
self.fontSize = args.font_size
if args.font not in ('Courier'):
self.font = 'myFont'
pdfmetrics.registerFont(TTFont('myFont', args.font))
else:
self.font = args.font
self.kerning = args.kerning
self.margins = margins
self.leading = (args.extra_vertical_space + 1.2) * self.fontSize
self.linesPerPage = int(
(self.leading + pageHeight
- margins.top - margins.bottom - self.fontSize) / self.leading)
self.lppLen = len(str(self.linesPerPage))
fontWidth = self.canvas.stringWidth(
".", fontName=self.font, fontSize=self.fontSize)
self.lineNumbering = args.line_numbers
if self.lineNumbering:
margins.adjustLeft(fontWidth * (self.lppLen + 2))
contentWidth = pageWidth - margins.left - margins.right
self.charsPerLine = int(
(contentWidth + self.kerning) / (fontWidth + self.kerning))
self.top = pageHeight - margins.top - self.fontSize
self.filename = args.filename
self.verbose = not args.quiet
self.breakOnBlanks = args.break_on_blanks
self.encoding = args.encoding
self.pageNumbering = args.page_numbers
if self.pageNumbering:
self.pageNumberPlacement = \
(pageWidth / 2, margins.bottom / 2)
def _process(self, data):
flen = os.fstat(data.fileno()).st_size
lineno = 0
read = 0
for line in data:
lineno += 1
if sys.version_info.major == 2:
read += len(line)
yield flen == \
read, lineno, line.decode(self.encoding).rstrip('\r\n')
else:
read += len(line.encode(self.encoding))
yield flen == read, lineno, line.rstrip('\r\n')
def _readDocument(self):
with open(self.filename, 'r') as data:
for done, lineno, line in self._process(data):
if len(line) > self.charsPerLine:
self._scribble(
"Warning: wrapping line %d in %s" %
(lineno + 1, self.filename))
while len(line) > self.charsPerLine:
yield done, line[:self.charsPerLine]
line = line[self.charsPerLine:]
yield done, line
def _newpage(self):
textobject = self.canvas.beginText()
textobject.setFont(self.font, self.fontSize, leading=self.leading)
textobject.setTextOrigin(self.margins.left, self.top)
textobject.setCharSpace(self.kerning)
if self.pageNumbering:
self.canvas.drawString(
self.pageNumberPlacement[0],
self.pageNumberPlacement[1],
str(self.canvas.getPageNumber()))
return textobject
def _scribble(self, text):
if self.verbose:
sys.stderr.write(text + os.linesep)
def generate(self):
self._scribble(
"Writing '%s' with %d characters per "
"line and %d lines per page..." %
(self.filename, self.charsPerLine, self.linesPerPage)
#.........这里部分代码省略.........