本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.drawImage方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.drawImage方法的具体用法?Python Canvas.drawImage怎么用?Python Canvas.drawImage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.drawImage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_single_page_image
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def test_single_page_image():
filename = os.path.join(TEST_OUTPUT, 'image-mono.pdf')
pdf = Canvas(filename, pagesize=(72, 72))
with NamedTemporaryFile() as im_tmp:
im = Image.new('1', (8, 8), 0)
for n in range(8):
im.putpixel((n, n), 1)
im.save(im_tmp.name, format='PNG')
# Draw image in a 72x72 pt or 1"x1" area
pdf.drawImage(im_tmp.name, 0, 0, width=72, height=72)
pdf.showPage()
pdf.save()
pdfinfo = pageinfo.pdf_get_all_pageinfo(filename)
assert len(pdfinfo) == 1
page = pdfinfo[0]
assert not page['has_text']
assert len(page['images']) == 1
pdfimage = page['images'][0]
assert pdfimage['width'] == 8
# assert pdfimage['color'] == 'gray'
# While unexpected, this is correct
# PDF spec says /FlateDecode image must have /BitsPerComponent 8
# So mono images get upgraded to 8-bit
assert pdfimage['bpc'] == 8
# DPI in a 1"x1" is the image width
assert pdfimage['dpi_w'] == 8
assert pdfimage['dpi_h'] == 8
示例2: __init__
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
class AwardPrinter:
def __init__(self, output_filename, background_image, page_renderer):
self.background_image = background_image
self.page_renderer = page_renderer
self.pdf = Canvas(output_filename, pagesize = A4)
def draw(self, students):
for student in students:
self._draw_page(student)
self.pdf.save()
def _draw_page(self, student):
self.pdf.setFillColor(colors.black)
# export the image as a higter resolution image 1280x920 recommended, which is then reduced
# in size to have a higher resolution for printing
self.pdf.drawImage(self.background_image, .1 * inch, .3 * inch, width=580, height=800, preserveAspectRatio=True)
self.pdf.rotate(270)
self.page_renderer(self, student)
self.pdf.showPage()
def _draw_award(self, student):
name = student.split(',')[0].strip()
award = student.split(',')[1].strip()
self.pdf.setFont("Helvetica", 28)
# play with these dimensions if you want to move around the text in the screen
self.pdf.drawCentredString(-5.4 * inch, 4.5 * inch, name.encode('latin-1'))
self.pdf.setFont("Helvetica", 18)
# play with these dimensions if you want to move around the text in the screen
self.pdf.drawCentredString(-5.4 * inch, 3.5 * inch, award)
def _draw_certificate(self, student):
name = student.split(',')[0].strip()
self.pdf.setFont("Helvetica", 32)
# play with these dimensions if you want to move around the text in the screen
self.pdf.drawCentredString(-5.75 * inch, 5.5 * inch, name.encode('latin-1'))
示例3: process_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def process_pdf(self, image_data, hocr_data, pdf_filename):
"""Utility function if you'd rather get the PDF data back instead of save it automatically."""
pdf = Canvas(pdf_filename, pageCompression=1)
pdf.setCreator('hocr-tools')
pdf.setPageSize((self.width, self.height))
pdf.drawImage(image_data, 0, 0, width=self.width, height=self.height)
pdf = self.add_text_layer(pdf, hocr_data)
pdf_data = pdf.getpdfdata()
return pdf_data
示例4: overlay_hocr
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def overlay_hocr(self, dpi, hocr_filename):
hocr_dir, hocr_basename = os.path.split(hocr_filename)
logging.debug("hocr_filename:%s, hocr_dir:%s, hocr_basename:%s" % (hocr_filename, hocr_dir, hocr_basename))
basename = hocr_basename.split('.')[0]
pdf_filename = os.path.join("%s_ocr.pdf" % (basename))
# Switch to the hocr directory to make this easier
cwd = os.getcwd()
if hocr_dir != "":
os.chdir(hocr_dir)
with open(pdf_filename, "wb") as f:
logging.info("Overlaying hocr and creating final %s" % pdf_filename)
pdf = Canvas(f, pageCompression=1)
pdf.setCreator('pyocr')
pdf.setTitle(os.path.basename(hocr_filename))
logging.info("Analyzing OCR and applying text to PDF...")
pdf.setPageCompression(1)
logging.info("Searching for %s" % ("%s*.jpg" % basename))
for jpg_file in glob.glob("%s*.jpg" % basename):
jpg = Image.open(jpg_file)
w,h = jpg.size
dpi_jpg = jpg.info['dpi']
width = w*72.0/dpi_jpg[0]
height = h*72.0/dpi_jpg[1]
del jpg
pdf.setPageSize((width,height))
logging.info("Adding page image %s" % jpg_file)
logging.info("Page width=%f, height=%f" % (width, height))
pdf.drawImage(jpg_file,0,0, width=width, height=height)
# Get the page number
pg_num = int(jpg_file.split(basename)[1].split('.')[0])
logging.info("Adding text to page %d" % pg_num)
self.add_text_layer(pdf, hocr_basename,pg_num,height,dpi)
pdf.showPage()
os.remove(jpg_file)
pdf.save()
logging.info("Created OCR'ed pdf as %s" % (pdf_filename))
# Now we have to fix up stuff on windows because of reportlab
# adding \r\r\n on each line (instead of \r\n)
f = open(pdf_filename, "rb")
s = str(f.read())
f.close()
#s = s.replace('\r\r\n', '\r\n')
#s = re.sub("\r\r\n", "\r\n", s)
#f = open(pdf_filename, "wb")
#f.write(s)
#f.close()
os.chdir(cwd)
return os.path.join(hocr_dir,pdf_filename)
示例5: _save_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def _save_pdf(self):
"""
Output the current document to a PDF file using ReportLab.
"""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
document_model = self.application.get_document_model()
# TODO: seperate saving code into its own thread?
# Setup output pdf
pdf = PdfCanvas(save_model.filename)
pdf.setTitle(save_model.title)
pdf.setAuthor(save_model.author)
pdf.setKeywords(save_model.keywords)
# Generate pages
page_iter = document_model.get_iter_first()
while page_iter:
current_page = document_model.get_value(page_iter, 0)
# Write transformed image
temp_file_path = ''.join([tempfile.mktemp(), '.bmp'])
current_page.pil_image.save(temp_file_path)
assert os.path.exists(temp_file_path), \
'Temporary bitmap file was not created by PIL.'
size = constants.PAGESIZES_INCHES[current_page.page_size]
pdf_width = size[0] * points_per_inch
pdf_height = size[1] * points_per_inch
# Swizzle width and height if the page has been rotated on its side
if abs(current_page.rotation) % 180 == 90:
pdf_width, pdf_height = pdf_height, pdf_width
pdf.setPageSize((pdf_width, pdf_height))
pdf.drawImage(
temp_file_path,
0, 0, width=pdf_width, height=pdf_height,
preserveAspectRatio=True)
pdf.showPage()
os.remove(temp_file_path)
page_iter = document_model.iter_next(page_iter)
# Save complete PDF
pdf.save()
assert os.path.exists(save_model.filename), \
'Final PDF file was not created by ReportLab.'
document_model.clear()
示例6: toutesReservations
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def toutesReservations(self):
# Lister les réservations effectuées par chaque client
req ="SELECT titre, nom, e_mail, COUNT(place) FROM spectacles "\
"LEFT JOIN reservations USING(ref_spt) "\
"LEFT JOIN clients USING (ref_cli) "\
"GROUP BY nom, titre "\
"ORDER BY titre, nom"
res =BD.executerReq(req)
# Construction d'un tableau html pour lister les infos trouvées :
tabl ='<table border="1" cellpadding="5">\n'
tabs =""
for n in range(4):
tabs +="<td>{{{0}}}</td>".format(n)
ligneTableau ="<tr>" +tabs +"</tr>\n"
# La première ligne du tableau contient les en-têtes de colonnes :
tabl += ligneTableau.\
format("Titre", "Nom du client", "Courriel", "Places réservées")
# Lignes suivantes :
for tit, nom, mail, pla in res:
tabl += ligneTableau.format(tit, nom, mail, pla)
tabl +="</table>"
# ======= Construction du document PDF correspondant : =======
# D'après le fichier de configuration tutoriel.conf, les documents
# "statiques" doivent se trouver dans le sous-répertoire "annexes"
# pour être accessibles depuis l'application web (mesure de sécurité) :
fichier ="annexes/reservations.pdf"
can = Canvas("%s" % (fichier), pagesize=A4)
largeurP, hauteurP = A4 # largeur et hauteur de la page
# Dessin du logo (aligné par son coin inférieur gauche) :
can.drawImage("annexes/python.gif", 1*cm, hauteurP-6*cm, mask="auto")
can.setFont("Times-BoldItalic", 28)
can.drawString(6*cm, hauteurP-6*cm, "Grand théâtre de Python city")
# Tableau des réservations :
posY =hauteurP-9*cm # position verticale de départ
tabs =(1*cm, 7*cm, 11*cm, 16.5*cm) # tabulations
head =("Titre", "Nom du client", "Courriel", "Places réservées")
# En-têtes du tableau :
can.setFont("Times-Bold", 14)
t =0
for txt in head:
can.drawString(tabs[t], posY, head[t])
t +=1
# Lignes du tableau :
posY -=.5*cm
can.setFont("Times-Roman", 14)
for tupl in res:
posY, t = posY-15, 0
for champ in tupl:
can.drawString(tabs[t], posY, str(champ))
# (Les valeurs numériques doivent être converties en chaînes !)
t +=1
can.save() # Finalisation du PDF
return mep(Glob.html["toutesReservations"].format(tabl, fichier))
示例7: badge
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def badge():
name = request.form['name'][:MAX_CHARS_PER_LINE] if 'name' in request.form else ''
name2 = request.form['name2'][:MAX_CHARS_PER_LINE] if 'name2' in request.form else ''
nick = request.form['nick'][:MAX_CHARS_PER_LINE] if 'nick' in request.form else ''
community = request.form['community'][:MAX_CHARS_PER_LINE] if 'community' in request.form else ''
pdf = BytesIO()
c = Canvas(pdf, pagesize=(BADGE_W, BADGE_H))
c.translate(ORIGIN_X, ORIGIN_Y)
ico_center = 7*mm
offset = HEIGHT+2*mm
c.setFillGray(0.66)
c.setFont('Awesome', 42)
c.drawCentredString(ico_center, offset-42*pica/12, '\uf007')
c.setFont('Awesome', 38)
c.drawCentredString(ico_center, offset-(2*42+40)*pica/12, '\uf1fa')
c.drawCentredString(ico_center, offset-(2*42+2*40)*pica/12, '\uf041')
txt_start = 15*mm
c.setFillGray(0.0)
c.setFont('LeagueGothic', 42)
c.drawString(txt_start, offset-42*pica/12, name)
c.drawString(txt_start, offset-2*42*pica/12, name2)
c.setFont('LeagueGothic', 38)
c.drawString(txt_start, offset-(2*42+40)*pica/12, nick)
c.drawString(txt_start, offset-(2*42+2*40)*pica/12, community)
evt_width = 38*pica/12
evt_start = WIDTH - evt_width
img_width = 20*mm
img_start = evt_start - img_width
c.drawImage(path.join(path.dirname(__file__), 'images/ffrhein_logo_claim_line_rot.png'), img_start, 0, img_width, HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')
c.rotate(90)
c.rect(0, -WIDTH, HEIGHT, evt_width, 0, 1)
c.setFillGray(1.0)
c.drawCentredString(HEIGHT/2, -WIDTH+MARGIN_R, 'routing days')
c.showPage()
c.save()
_print(pdf.getvalue())
pdf.close()
# response = make_response('Meh')
# response.headers['Content-Type'] = 'text/plain'
# return response
return redirect('/badge/printing.html')
示例8: pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def pdf(files, outfile, useportrait=True):
print("Creating PDF...")
pdf = Canvas(outfile)
pagesize = portrait(A4) if useportrait else landscape(A4)
for i in files:
print("Creating PDF page for %s..." % i)
pdf.setPageSize(pagesize)
pdf.drawImage(i, 0, 0, *pagesize)
pdf.showPage()
print("Done!")
print("Saving PDF...")
pdf.save()
print("Done!")
示例9: paint_original_segments
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def paint_original_segments(fnames, transcriptions, page):
pdf_fname = 'tmp/search_{0}.pdf'.format(page)
pdf = Canvas(pdf_fname, pagesize=A4)
top = A4[1]
for fname, transcription in itertools.izip(fnames, transcriptions):
segment = Image.open(fname)
width, height = segment.size
p = Paragraph(transcription, ParagraphStyle('Normal', alignment=TA_CENTER))
p.wrapOn(pdf, A4[0] - PARA_PADDING * 2, height)
p.drawOn(pdf, PARA_PADDING, top - height / 2)
pdf.drawImage(fname, 0, top - height)
top -= height
pdf.save()
return pdf_fname
示例10: paint_original_segments
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def paint_original_segments(fnames, transcriptions, page):
page_file = NamedTemporaryFile(suffix='.pdf', dir=path.abspath('./tmp/'), delete=False)
pdf = Canvas(page_file.name, pagesize=A4)
page_width, top = A4
for fname, transcription in itertools.izip(fnames, transcriptions):
segment = Image.open(fname)
width, height = segment.size
p = Paragraph(transcription, ParagraphStyle('Normal', alignment=TA_CENTER))
p.wrapOn(pdf, page_width - PARA_PADDING * 2, height)
p.drawOn(pdf, PARA_PADDING, top - height / 2)
pdf.drawImage(fname, 0, top - height)
top -= height
pdf.save()
page_file.close()
return page_file.name
示例11: _draw_poweredby
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def _draw_poweredby(self, canvas: Canvas, op: OrderPosition, o: dict):
content = o.get('content', 'dark')
if content not in ('dark', 'white'):
content = 'dark'
img = finders.find('pretixpresale/pdf/powered_by_pretix_{}.png'.format(content))
ir = ThumbnailingImageReader(img)
try:
width, height = ir.resize(None, float(o['size']) * mm, 300)
except:
logger.exception("Can not resize image")
pass
canvas.drawImage(ir,
float(o['left']) * mm, float(o['bottom']) * mm,
width=width, height=height,
preserveAspectRatio=True, anchor='n',
mask='auto')
示例12: get_image_page
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def get_image_page(image):
inch = 72
bio = BytesIO()
c = Canvas(bio, pagesize=(8.5*inch, 11*inch))
dim = c.drawImage(image, 0.5*inch, 6.3*inch, 495, 290)
# print(dim)
c.save()
return PdfFileReader(bio).getPage(0)
示例13: generate_key
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def generate_key(verticalCardsCount,horizontalCardsCount,cards, filename="key.pdf", page_margins = 4 * (0.5 * pagesizes.inch, )):
(page_margin_top, page_margin_left, page_margin_bottom, page_margin_right) = page_margins
padding = 0.0625 * pagesizes.inch
spaces = (verticalCardsCount * horizontalCardsCount) * [None,]
for card in cards:
spaces[card.position] = card
pagesize = pagesizes.landscape( ( 8.5 * pagesizes.inch, 11 * pagesizes.inch))
pdf = Canvas(filename, pagesize=pagesize, pdfVersion=(1,4))
pdf.setAuthor('placecardboardgenerate.py')
pdf.setSubject('wedding placecards key')
pdf.setTitle('Key for Placecards for Wedding Reception')
pdf.setKeywords(('wedding', 'placecards'))
(page_width, page_height) = pagesize
pdf.drawCentredString(page_width/2.0,20,"key of place cards")
thumbnail_width = ((page_width - page_margin_left - page_margin_right) - (padding * (horizontalCardsCount - 1))) / horizontalCardsCount
thumbnail_height = ((page_height - page_margin_top - page_margin_bottom) - (padding * (verticalCardsCount - 1))) / verticalCardsCount
x_margin = page_margin_left
x_offset = thumbnail_width + padding
y_margin = page_margin_top
y_offset = thumbnail_height + padding
for row_index in range(verticalCardsCount):
for column_index in range(horizontalCardsCount):
position = (row_index * horizontalCardsCount) + column_index
card = spaces[position]
(card_x, card_y) = \
(x_margin + (x_offset * column_index),\
(page_height - thumbnail_height) - (y_margin + (y_offset * row_index)))
if card is not None:
pdf.drawImage(card.image, card_x, card_y, width = thumbnail_width, height = thumbnail_height)
pdf.drawCentredString(card_x + thumbnail_width/2.0,card_y + thumbnail_height/2.0, str(card.position))
pdf.showPage()
pdf.save()
示例14: __init__
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
class DesignShirtsFromCalifornia:
CHICAGO_HEADLINE=["ThoughtWorks Chicago", "Bringing it since 1992", "CHICAGO", "Rainey's People"]
ADJECTIVES=["Awesomist", "Best looking", "Happiest", "Legendary", "Transparent", "Shiny", "Dangerous", "Fastest"]
NOUNS=["Chicagoans", "Agilistas", "Wonderlic Masters", "Bears Fans"]
ATTRIBUTION="Designed by ThoughtWorks in California"
GIT_REF="Fork me on Github https://github.com/jawspeak/tw-california-tshirt-generator"
def __init__(self, output_filename):
self.pdf = Canvas(output_filename, pagesize = LETTER)
# self.headlines =
def draw(self):
for image in glob.glob('awesomeness/*.[jpg|png|gif]*'):
self._draw_page(image)
self.pdf.save()
def _draw_page(self, image):
self.pdf.setFillColor(colors.black)
# To have a higher resolution for printing export the image as a higter resolution image which is then reduced
self.pdf.drawImage(image, 2.25 * inch, 3.7 * inch, width=300, height=300, preserveAspectRatio=True)
height = 8
# print self.pdf.getAvailableFonts()
self.pdf.setFont("Times-Bold", 28)
random.shuffle(self.CHICAGO_HEADLINE, random.random)
self.pdf.drawCentredString(4.25* inch, height*inch, self.CHICAGO_HEADLINE[0].encode('latin-1'))
self.pdf.setFont("Times-Italic", 16)
if len(image.split('=')) == 2:
self.pdf.drawCentredString(4.25* inch, (height - 4.5)* inch, image.split('=')[1].split('.')[0].encode('latin-1'))
else:
random.shuffle(self.ADJECTIVES, random.random)
random.shuffle(self.NOUNS, random.random)
flattering_tagline = "Home of the %s %s!" % (', '.join(self.ADJECTIVES[:2]), self.NOUNS[0])
self.pdf.drawCentredString(4.25* inch, (height - 4.5)* inch, flattering_tagline.encode('latin-1'))
self.pdf.setFont("Times-Italic", 10)
self.pdf.drawCentredString(4.25 * inch, (height - 4.8) * inch, self.ATTRIBUTION)
self.pdf.drawCentredString(4.25 * inch, (height - 4.95) * inch, self.GIT_REF)
self.pdf.showPage()
示例15: test
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawImage [as 别名]
def test(self):
import os
c = Canvas(filename, invariant=1, pageCompression=0)
c.setFont('Helvetica-Bold', 36)
c.drawString(100,700, 'Hello World')
gif = os.path.join(os.path.dirname(unittest.__file__),'pythonpowered.gif')
c.drawImage(gif,100,600)
c.save()
raw1 = open(filename, 'rb').read()
c = Canvas(filename, invariant=1, pageCompression=0)
c.setFont('Helvetica-Bold', 36)
c.drawString(100,700, 'Hello World')
c.drawImage(gif,100,600)
c.save()
raw2 = open(filename, 'rb').read()
assert raw1 == raw2, 'repeated runs differ!'