本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.drawInlineImage方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.drawInlineImage方法的具体用法?Python Canvas.drawInlineImage怎么用?Python Canvas.drawInlineImage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.drawInlineImage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def create_pdf(image_paths, output_filepath):
image_paths.sort()
pdf = Canvas(output_filepath)
pdf.setAuthor("MangaCreator")
for image_path in image_paths:
image = Image.open(image_path)
width, height = A4
pdf.drawInlineImage(image, x=0, y=0, width=width, height=height)
pdf.showPage()
pdf.save()
示例2: test_single_page_inline_image
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def test_single_page_inline_image():
filename = os.path.join(TEST_OUTPUT, "image-mono-inline.pdf")
pdf = Canvas(filename, pagesize=(8 * 72, 6 * 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.drawInlineImage(im_tmp.name, 0, 0, width=72, height=72)
pdf.showPage()
pdf.save()
with pytest.raises(NotImplementedError):
pageinfo.pdf_get_all_pageinfo(filename)
示例3: test_single_page_inline_image
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def test_single_page_inline_image(outdir):
filename = outdir / 'image-mono-inline.pdf'
pdf = Canvas(str(filename), pagesize=(8*72, 6*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.drawInlineImage(im_tmp.name, 0, 0, width=72, height=72)
pdf.showPage()
pdf.save()
pdf = pdfinfo.PdfInfo(filename)
print(pdf)
pdfimage = pdf[0].images[0]
assert isclose(pdfimage.xres, 8)
assert pdfimage.color == Colorspace.rgb # reportlab produces color image
assert pdfimage.width == 8
示例4: generateCollage
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def generateCollage(self,session):
file_name = 'collage.pdf' #TODO image should be created in a temp directory
pdf = Canvas(file_name,pagesize=self._pagesize)
# add metadata
pdf.setAuthor('photobooth') #TODO add app version to author
pdf.setSubject('wedding photos')
pdf.setTitle('pictures for session %s' % session.get_name())
pdf.setKeywords(('wedding', 'pictures','photobooth'))
# add pictures
#TODO add padding
(total_width, total_height) = self._pagesize
(image_width, image_height) = (total_width, total_height / len(session.get_photos()))
for (i,photo) in enumerate(session.get_photos()):
pdf.drawInlineImage(photo,0,i * image_height, image_width, image_height, preserveAspectRatio=True, anchor='n')
pdf.showPage()
pdf.save()
return file_name
示例5: save_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def save_pdf(self, filename, margins=(1,1)):
'''
Make and save a PDF of this coverage plot, including a legend.
Margins are expressed in inches: (top-bottom, left-right).
'''
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
c = Canvas(filename, pagesize=letter)
# Compute margins.
margin_top, margin_left = margins
margin_top *= inch; margin_left *= inch
whole_page_width, whole_page_height = letter
page_top = whole_page_height - margin_top
page_left = margin_left
page_width = whole_page_width - 2*margin_left
# Show the main image.
image = self.img
image_width = page_width
image_height = image_width / image.size[0] * image.size[1]
image_x = page_left
image_y = page_top - image_height
c.drawInlineImage(image, image_x, image_y, width=image_width, height=image_height)
# Draw legends beneath the image.
textobject = c.beginText()
textobject.setTextOrigin(page_left, image_y - .5*inch)
textobject.setFont('Helvetica', 14)
for name, color in izip(self.names, self.colors):
textobject.setFillColorRGB(*color)
textobject.textLine(name)
c.drawText(textobject)
# Done.
c.showPage()
c.save()
示例6: card
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
serials.append(serial);
# Writing text
coords = card(x, y)
pdf.setFont("Helvetica", URLSIZE)
px = coords[0] + URLOFFSET[0]
py = coords[1] + URLOFFSET[1]
pdf.drawString(px, py, URL)
pdf.setFont("Helvetica", SERIALSIZE)
px = coords[0] + SERIALOFFSET[0]
py = coords[1] + SERIALOFFSET[1]
pdf.drawString(px, py, serial)
# Generating and writing the QR code
os.system("qrencode -o .tempqr.png -s 30 -m 0 -l H " + serial)
px = coords[0] + QROFFSET[0];
py = coords[1] + QROFFSET[1]
pdf.drawInlineImage(".tempqr.png", px, py,
width=QRSIZE, height=QRSIZE)
os.remove(".tempqr.png")
# Closing the page
pdf.showPage()
pdf.save()
示例7: Reporter
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
class Reporter(object):
def __init__(self,vapp):
self.dataApp = vapp
path = self.dataApp.repoPath + self.dataApp.rdataName + '.pdf'
self.canvas = Canvas(path)
self.page = 1
def header(self):
self.canvas.setFont("Helvetica", 10)
self.canvas.drawCentredString(4.135*inch, 10.74*inch, '[email protected] : ycroft.net')
self.canvas.setFont("Helvetica", 11.5)
self.canvas.line(1*inch, 10.69*inch, 7.27*inch, 10.69*inch)
def footer(self):
self.canvas.setFont("Helvetica", 11.5)
self.canvas.line(1*inch, 1*inch, 7.27*inch, 1*inch)
self.canvas.setFont("Helvetica", 10)
self.canvas.drawCentredString(4.135*inch, 0.83*inch, '- '+str(self.page)+' -')
def cover(self,coverInfo):
dataName = coverInfo.get('dataName','no name')
author = coverInfo.get('author','no name')
version = coverInfo.get('version','unknown')
self.header()
self.footer()
self.canvas.setFont("Helvetica-Bold", 40)
self.canvas.drawCentredString(4.135*inch, 7.5*inch, 'Analysis Report')
self.canvas.setFont("Helvetica", 20)
self.canvas.drawCentredString(4.135*inch, 6.8*inch, 'for data \'' + dataName + '\'')
self.canvas.setFont("Helvetica", 15)
self.canvas.drawRightString(3.935*inch, 4.4*inch, 'author:')
self.canvas.drawRightString(3.935*inch, 3.9*inch, 'date:')
self.canvas.drawRightString(3.935*inch, 3.4*inch, 'version:')
self.canvas.drawString(4.335*inch, 4.4*inch, author)
self.canvas.drawString(4.335*inch, 3.9*inch, str(datetime.now().strftime('%a, %b %d %H:%M')))
self.canvas.drawString(4.335*inch, 3.4*inch, version)
self.canvas.showPage()
self.page += 1
def body(self):
self.header()
self.footer()
sdataName = self.dataApp.sdataName
rdataName = self.dataApp.rdataName
imgPath = './spec_data/img/'
self.canvas.setFont("Helvetica-Bold", 15)
self.canvas.drawString(1.25*inch, 10*inch, 'I. Modulation Factors ')
self.canvas.setFont("Helvetica", 12)
self.canvas.drawString(1.5*inch, 9.7*inch, 'These factors are derived from the file \''+sdataName+'\'')
self.canvas.drawInlineImage(imgPath + sdataName + '_cs0.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + sdataName + '_cs1.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
self.canvas.showPage()
self.page += 1
self.header()
self.footer()
self.canvas.drawInlineImage(imgPath + sdataName + '_cs2.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + sdataName + '_cs3.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
self.canvas.showPage()
self.page += 1
self.header()
self.footer()
self.canvas.setFont("Helvetica-Bold", 15)
self.canvas.drawString(1.25*inch, 10*inch, 'II. Measured Data & FFT ')
self.canvas.setFont("Helvetica", 12)
self.canvas.drawString(1.5*inch, 9.7*inch, 'The data is derived from the file \''+rdataName+'\', and each fft channel has been filtered.')
self.canvas.drawInlineImage(imgPath + rdataName + '_rd.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + rdataName + '_fft.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
self.canvas.showPage()
self.page += 1
self.header()
self.footer()
self.canvas.setFont("Helvetica-Bold", 15)
self.canvas.drawString(1.25*inch, 10*inch, 'III. Modulation Signals ')
self.canvas.setFont("Helvetica", 12)
self.canvas.drawString(1.5*inch, 9.7*inch, 'These signals are derived by ifft on the corresponding channel.')
self.canvas.drawInlineImage(imgPath + rdataName + '_fa0.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + rdataName + '_fa1.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
self.canvas.showPage()
self.page += 1
self.header()
self.footer()
self.canvas.drawInlineImage(imgPath + rdataName + '_fa2.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + rdataName + '_fa3.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
self.canvas.showPage()
self.page += 1
self.header()
self.footer()
self.canvas.setFont("Helvetica-Bold", 15)
self.canvas.drawString(1.25*inch, 10*inch, 'IV. Stokes Vectors ')
self.canvas.setFont("Helvetica", 12)
self.canvas.drawString(1.5*inch, 9.7*inch, 'This can be figured out using modulation signals and modulation factors.')
self.canvas.drawInlineImage(imgPath + rdataName + '_s0.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + rdataName + '_s1.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
self.canvas.showPage()
self.page += 1
self.header()
self.footer()
self.canvas.drawInlineImage(imgPath + rdataName + '_s2.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch)
self.canvas.drawInlineImage(imgPath + rdataName + '_s3.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch)
#.........这里部分代码省略.........
示例8: draw
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def draw(self, invoice, items_page=10):
""" Draws the invoice """
buffer = cStringIO.StringIO()
invoice_items = invoice['items']
pages = max((len(invoice_items)-2)/items_page+1,1)
canvas = Canvas(buffer, pagesize=self.page_size)
for page in range(pages):
canvas.translate(0, 29.7 * cm)
canvas.setFont(self.font_face, 10)
canvas.saveState()
canvas.setStrokeColorRGB(0.9, 0.5, 0.2)
canvas.setFillColorRGB(0.2, 0.2, 0.2)
canvas.setFont(self.font_face, 16)
canvas.drawString(1 * cm, -1 * cm, invoice.get('title',''))
if self.logo:
canvas.drawInlineImage(self.logo, 1 * cm, -1 * cm, 250, 16)
canvas.setLineWidth(4)
canvas.line(0, -1.25 * cm, 21.7 * cm, -1.25 * cm)
canvas.restoreState()
canvas.saveState()
notes = listify(invoice.get('notes',''))
textobject = canvas.beginText(1 * cm, -25 * cm)
for line in notes:
textobject.textLine(line)
canvas.drawText(textobject)
textobject = canvas.beginText(18 * cm, -28 * cm)
textobject.textLine('Pag.%s/%s' % (page+1,pages))
canvas.drawText(textobject)
canvas.restoreState()
canvas.saveState()
business_details = listify(invoice.get('from','FROM:'))
canvas.setFont(self.font_face, 9)
textobject = canvas.beginText(13 * cm, -2.5 * cm)
for line in business_details:
textobject.textLine(line)
canvas.drawText(textobject)
canvas.restoreState()
canvas.saveState()
client_info = listify(invoice.get('to','TO:'))
textobject = canvas.beginText(1.5 * cm, -2.5 * cm)
for line in client_info:
textobject.textLine(line)
canvas.drawText(textobject)
canvas.restoreState()
textobject = canvas.beginText(1.5 * cm, -6.75 * cm)
textobject.textLine(u'Invoice ID: %s' % invoice.get('id','<invoice id>'))
textobject.textLine(u'Invoice Date: %s' % invoice.get('date',datetime.date.today()))
textobject.textLine(u'Client: %s' % invoice.get('client_name','<invoice client>'))
canvas.drawText(textobject)
items = invoice_items[1:][page*items_page:(page+1)*items_page]
if items:
data = [invoice_items[0]]
for item in items:
data.append([
self.format_currency(x)
if isinstance(x,float) else x
for x in item])
righta = [k for k,v in enumerate(items[0])
if isinstance(v,(int,float,Decimal))]
if page == pages-1:
total = self.format_currency(invoice['total'])
else:
total = ''
data.append(['']*(len(items[0])-1)+[total])
colWidths = [2.5*cm]*len(items[0])
colWidths[1] = (21.5-2.5*len(items[0]))*cm
table = Table(data, colWidths=colWidths)
table.setStyle([
('FONT', (0, 0), (-1, -1), self.font_face),
('FONTSIZE', (0, 0), (-1, -1), 8),
('TEXTCOLOR', (0, 0), (-1, -1), (0.2, 0.2, 0.2)),
('GRID', (0, 0), (-1, -2), 1, (0.7, 0.7, 0.7)),
('GRID', (-1, -1), (-1, -1), 1, (0.7, 0.7, 0.7)),
('BACKGROUND', (0, 0), (-1, 0), (0.8, 0.8, 0.8)),
]+[('ALIGN',(k,0),(k,-1),'RIGHT') for k in righta])
tw, th, = table.wrapOn(canvas, 15 * cm, 19 * cm)
table.drawOn(canvas, 1 * cm, -8 * cm - th)
if page == pages-1:
items = invoice['totals'][1:]
if items:
data = [invoice['totals'][0]]
for item in items:
data.append([
self.format_currency(x)
if isinstance(x,float) else x
for x in item])
righta = [k for k,v in enumerate(items[0])
if isinstance(v,(int,float,Decimal))]
total = self.format_currency(invoice['total'])
data.append(['']*(len(items[0])-1)+[total])
colWidths = [2.5*cm]*len(items[0])
colWidths[1] = (21.5-2.5*len(items[0]))*cm
table = Table(data, colWidths=colWidths)
#.........这里部分代码省略.........
示例9: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [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()
示例10: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [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: get
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def get(self, request, *args, **kwargs):
self.object = self.get_object()
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{0}-{1}.pdf"'.format(self.object.registru.serie, self.object.numar_inregistrare)
pdf = Canvas(response, pagesize = A4)
import os
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph
pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf"))
pdfmetrics.registerFont(TTFont("DejaVuSans", "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf"))
if self.object.registru.centru_local.antet:
antet_path = os.path.join(settings.MEDIA_ROOT, "%s" % self.object.registru.centru_local.antet)
pdf.drawInlineImage(antet_path, 2.5 * cm, 10.8 * cm, width=16. * cm, height=2.66 * cm)
pdf.drawInlineImage(antet_path, 2.5 * cm, 24.5 * cm, width=16. * cm, height=2.66 * cm)
pdf.setStrokeColorRGB(0, 0, 0)
pdf.rect(2. * cm, 2. * cm, 17. * cm, 12. * cm)
pdf.rect(2. * cm, 15.7 * cm, 17. * cm, 12 * cm)
pdf.setStrokeColorRGB(0.5, 0.5, 0.5)
pdf.setDash(1, 2)
pdf.line(0 * cm, 14.85 * cm, 21. * cm, 14.85 * cm)
pdf.setFont("DejaVuSans-Bold", 0.5 * cm, leading=None)
pdf.drawCentredString(10.5 * cm, 9.5 * cm, u"Chitanță")
pdf.drawCentredString(10.5 * cm, 23.2 * cm, u"Chitanță")
text_serie = u"seria {0}, nr. {1} / {2}".format(self.object.registru.serie, self.object.numar_inregistrare,
self.object.data_inregistrare.strftime("%d.%m.%Y"))
pdf.setFont("DejaVuSans-Bold", 4. * cm, leading=None)
pdf.setFillColorRGB(0.95, 0.95, 0.95)
pdf.rotate(15)
pdf.drawString(4.5 * cm, 2. * cm, u"COPIE")
pdf.rotate(-15)
pdf.setFillColorRGB(0, 0, 0)
pdf.setFont("DejaVuSans", 0.35 * cm, leading=None)
pdf.drawCentredString(10.5 * cm, 8.9 * cm, text_serie)
pdf.drawCentredString(10.5 * cm, 22.6 * cm, text_serie)
reprezinta = self.object.descriere
if hasattr(self.object, "chitantacotizatie"):
reprezinta = []
for p in self.object.chitantacotizatie.platacotizatietrimestru_set.all().order_by("index"):
date_reprezinta = (p.trimestru.__unicode__(), p.suma, u"- parțial" if p.partial else "")
reprezinta.append("{0} ({1} RON{2})".format(*date_reprezinta))
reprezinta = ", ".join(reprezinta)
reprezinta = u"cotizație membru pentru {0}".format(reprezinta)
date_chitanta = (self.object.platitor().__unicode__(), self.object.suma, suma2text(self.object.suma).strip(), reprezinta)
text_chitanta = u"Am primit de la <strong>{0}</strong> suma de {1} lei, adică {2}, reprezentând {3}.".format(*date_chitanta)
style_sheet = getSampleStyleSheet()
style = style_sheet['Normal']
style.alignment = TA_JUSTIFY
style.fontName = "DejaVuSans"
style.leading = 0.85 * cm
paragraph = Paragraph(text_chitanta, style)
w, h = paragraph.wrap(15. * cm, 5. * cm)
# print w, h
paragraph.drawOn(pdf, 3. * cm, 5.5 * cm)
paragraph.drawOn(pdf, 3. * cm, 19.2 * cm)
pdf.drawString(12.5 * cm, 4.5 * cm, u"Casier,")
pdf.drawString(12.5 * cm, 18.2 * cm, u"Casier, ")
trezorier = self.object.registru.centru_local.ocupant_functie(u"Trezorier Centru Local")
pdf.drawString(12.5 * cm, 3.8 * cm, trezorier.__unicode__())
pdf.drawString(12.5 * cm, 17.5 * cm, trezorier.__unicode__())
pdf.showPage()
pdf.save()
return response
示例12: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
#.........这里部分代码省略.........
self.canvas.line(
self.report.margin_left + graphic.left,
top_position - graphic.top,
self.report.margin_left + graphic.right,
top_position - graphic.bottom,
)
elif isinstance(element, Circle):
self.canvas.circle(
self.report.margin_left + graphic.left_center,
top_position - graphic.top_center,
graphic.radius,
graphic.stroke,
graphic.fill,
)
elif isinstance(element, Arc):
self.canvas.arc(
self.report.margin_left + graphic.left,
top_position - graphic.top,
self.report.margin_left + graphic.right,
top_position - graphic.bottom,
graphic.start_angle,
graphic.extent,
)
elif isinstance(element, Ellipse):
self.canvas.ellipse(
self.report.margin_left + graphic.left,
top_position - graphic.top,
self.report.margin_left + graphic.right,
top_position - graphic.bottom,
graphic.stroke,
graphic.fill,
)
elif isinstance(element, Image):
self.canvas.drawInlineImage(
graphic.image,
self.report.margin_left + graphic.left,
top_position - graphic.top - graphic.height,
graphic.width,
graphic.height,
)
# Band borders
if band.borders.get('all', None):
self.canvas.rect(
band_rect['left'],
band_rect['top'] - band.height,
band_rect['right'] - band_rect['left'],
band.height,
)
if band.borders.get('top', None):
self.canvas.line(band_rect['left'], band_rect['top'], band_rect['right'],
band_rect['top'])
if band.borders.get('right', None):
self.canvas.line(band_rect['right'], band_rect['top'], band_rect['right'],
band_rect['bottom'])
if band.borders.get('bottom', None):
self.canvas.line(band_rect['left'], band_rect['bottom'], band_rect['right'],
band_rect['bottom'])
if band.borders.get('left', None):
self.canvas.line(band_rect['left'], band_rect['top'], band_rect['left'],
band_rect['bottom'])
示例13: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
#.........这里部分代码省略.........
vprint( VERBOSE, "ocrwidth, ocrheight :", ocrwidth, ocrheight )
if ( ( not ocrwidth ) and ( ( not width ) or ( not withVisibleImage ) ) ) or ( ( not ocrheight) and ( ( not height ) or ( not withVisibleImage ) ) ):
vprint( WARN, "Page with extension 0 or without content. Skipping." )
else:
if page is not None:
ocr_dpi = (300, 300) # a default, in case we can't find it
if width is None:
# no dpi info with the image
# assume OCR was done at 300 dpi
width = ocrwidth / 300.0
height = ocrheight / 300.0
vprint( VERBOSE, "Assuming width, height:",width,height )
ocr_dpi = (ocrwidth/width, ocrheight/height)
vprint( VERBOSE, "ocr_dpi :", ocr_dpi )
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
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 )
示例14: Canvas
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
SMALLFONTSIZE = 8
width, height = A4
centerh = height/2 # horizontal center, used to center text strings on the page
# create the PDF --- DO NOT EDIT AFTER THIS LINE !!! ---
pdf = Canvas("lipflyer.pdf")
pdf.setPageSize([height, width]) # only trick I found to have a A4 in LANDSCAPE mode
# 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"
示例15: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import drawInlineImage [as 别名]
def to_pdf(self, outFileName, imageFileName, showBoundingboxes, fontname="Helvetica"):
"""
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
pdf = Canvas(outFileName, pagesize=(self.width, self.height), pageCompression=1) # page size in points (1/72 in.)
# draw bounding box for each paragraph
pdf.setStrokeColorRGB(0,1,1) # light blue for bounding box of paragraph
pdf.setFillColorRGB(0,1,1) # light blue for bounding box of paragraph
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
coords = self.element_coordinates(elem)
x1=self.px2pt(coords[0])
y1=self.px2pt(coords[1])
x2=self.px2pt(coords[2])
y2=self.px2pt(coords[3])
# draw the bbox border
if showBoundingboxes == True:
pdf.rect(x1, self.height-y2, x2-x1, y2-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
pdf.setStrokeColorRGB(1,0,0) # light green for bounding box of word/line
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
coords = self.element_coordinates(elem)
x1=self.px2pt(coords[0])
y1=self.px2pt(coords[1])
x2=self.px2pt(coords[2])
y2=self.px2pt(coords[3])
# draw the bbox border
if showBoundingboxes == True:
pdf.rect(x1, self.height-y2, x2-x1, y2-y1, fill=0)
text = pdf.beginText()
fontsize=self.px2pt(coords[3]-coords[1])
text.setFont(fontname, fontsize)
# set cursor to bottom left corner of bbox (adjust for dpi)
text.setTextOrigin(x1, self.height-y2)
# scale the width of the text to fill the width of the bbox
text.setHorizScale(100*(x2-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 != None:
im = Image.open(imageFileName)
pdf.drawInlineImage(im, 0, 0, width=self.width, height=self.height)
# finish up the page and save it
pdf.showPage()
pdf.save()