本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setDash方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setDash方法的具体用法?Python Canvas.setDash怎么用?Python Canvas.setDash使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.setDash方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setDash [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()
示例2: to_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setDash [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()
示例3: get
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setDash [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
示例4: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setDash [as 别名]
#.........这里部分代码省略.........
self.set_rgb_values(color, pdfcolor)
return pdfcolor
def stroke_pdfpath(self, pdfpath, stroke_style, stroke_trafo=[]):
width = stroke_style[1]
if not stroke_style[8]:
width = stroke_style[1]
else:
if not stroke_trafo:
stroke_trafo = [] + sk2_const.NORMAL_TRAFO
points = [[0.0, 0.0], [1.0, 0.0]]
points = libgeom.apply_trafo_to_points(points, stroke_trafo)
coef = libgeom.distance(*points)
width = stroke_style[1] * coef
self.canvas.setStrokeColor(self.get_pdfcolor(stroke_style[2]))
dash = stroke_style[3]
caps = stroke_style[4]
joint = stroke_style[5]
miter = stroke_style[6]
self.canvas.setLineWidth(width)
self.canvas.setLineCap(caps - 1)
self.canvas.setLineJoin(joint)
dashes = []
if dash:
dashes = list(dash)
w = width
if w < 1.0: w = 1.0
for i in range(len(dashes)):
dashes[i] = w * dashes[i]
self.canvas.setDash(dashes)
self.canvas.setMiterLimit(miter)
self.canvas.drawPath(pdfpath, 1, 0)
self.canvas.setStrokeAlpha(1.0)
def fill_pdfpath(self, obj, pdfpath, fill_style, fill_trafo=None):
self.set_fill_rule(fill_style[0])
if fill_style[1] == sk2_const.FILL_SOLID:
self.canvas.setFillColor(self.get_pdfcolor(fill_style[2]))
self.canvas.drawPath(pdfpath, 0, 1)
elif fill_style[1] == sk2_const.FILL_GRADIENT:
gradient = fill_style[2]
stops = gradient[2]
transparency = False
for stop in stops:
if stop[1][2] < 1.0:
transparency = True
break
if transparency:
self.fill_tr_gradient(obj, pdfpath, fill_trafo, gradient)
else:
self.fill_gradient(pdfpath, fill_trafo, gradient)
elif fill_style[1] == sk2_const.FILL_PATTERN:
pattern = fill_style[2]
self.fill_pattern(obj, pdfpath, fill_trafo, pattern)
def fill_gradient(self, pdfpath, fill_trafo, gradient):
self.canvas.saveState()
self.canvas.clipPath(pdfpath, 0, 0)
if fill_trafo:
self.canvas.transform(*fill_trafo)