当前位置: 首页>>代码示例>>Python>>正文


Python Canvas.setLineWidth方法代码示例

本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setLineWidth方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setLineWidth方法的具体用法?Python Canvas.setLineWidth怎么用?Python Canvas.setLineWidth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在reportlab.pdfgen.canvas.Canvas的用法示例。


在下文中一共展示了Canvas.setLineWidth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test3

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
    def test3(self):
        from reportlab.pdfgen.canvas import Canvas

        aW=307
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']
        btj = ParagraphStyle('bodyText1j',parent=bt,alignment=TA_JUSTIFY)
        p=Paragraph("""<a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
                keepTogether attributes.  Generated at 1111. The number in brackets
                at the end of each paragraph is its position in the story. llllllllllllllllllllllllll 
                bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc ddddddddddddddddddddd eeeeyyy""",btj)

        w,h=p.wrap(aW,1000)
        canv=Canvas('test_platypus_paragraph_just.pdf',pagesize=(aW,h))
        i=len(canv._code)
        p.drawOn(canv,0,0)
        ParaCode=canv._code[i:]
        canv.saveState()
        canv.setLineWidth(0)
        canv.setStrokeColorRGB(1,0,0)
        canv.rect(0,0,aW,h)
        canv.restoreState()
        canv.showPage()
        canv.save()
        from reportlab import rl_config
        x = rl_config.paraFontSizeHeightOffset and '50' or '53.17'
        good = ['q', '1 0 0 1 0 0 cm', 'q', 'BT 1 0 0 1 0 '+x+' Tm 3.59 Tw 12 TL /F1 10 Tf 0 0 0 rg (Subsequent pages test pageBreakBefore, frameBreakBefore and) Tj T* 0 Tw .23 Tw (keepTogether attributes. Generated at 1111. The number in brackets) Tj T* 0 Tw .299167 Tw (at the end of each paragraph is its position in the story. llllllllllllllllllllllllll) Tj T* 0 Tw 66.9 Tw (bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc) Tj T* 0 Tw (ddddddddddddddddddddd eeeeyyy) Tj T* ET', 'Q', 'Q']
        ok= ParaCode==good
        assert ok, "\nParaCode=%r\nexpected=%r" % (ParaCode,good)
开发者ID:FatihZor,项目名称:infernal-twin,代码行数:31,代码来源:test_platypus_breaking.py

示例2: _build_omr_layer

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
    def _build_omr_layer(marks):
        padding_x = 4.2 * mm
        padding_y = 8.5 * mm
        top_mark_x = 7 * mm
        top_mark_y = 220 * mm
        mark_y_spacing = 4 * mm

        mark_width = 6.5 * mm
        marks_height = (len(marks) - 1) * mark_y_spacing

        logger.info('Mailer DS-75i OMR Settings: 1={} 2={}'.format(
            (297 * mm - top_mark_y) / mm,
            (top_mark_x + mark_width / 2) / mm + 0.5
        ))

        omr_buffer = StringIO.StringIO()
        omr_canvas = Canvas(omr_buffer)
        omr_canvas.setLineWidth(0.2 * mm)

        # add a white background for the omr code
        omr_canvas.setFillColor(white)
        omr_canvas.rect(
            x=top_mark_x - padding_x,
            y=top_mark_y - marks_height - padding_y,
            width=mark_width + 2 * padding_x,
            height=marks_height + 2 * padding_y,
            fill=True,
            stroke=False
        )

        for offset, mark in enumerate(marks):
            mark_y = top_mark_y - offset * mark_y_spacing
            if mark:
                omr_canvas.line(top_mark_x, mark_y,
                                top_mark_x + mark_width, mark_y)

        # Close the PDF object cleanly.
        omr_canvas.showPage()
        omr_canvas.save()

        # move to the beginning of the StringIO buffer
        omr_buffer.seek(0)
        omr_pdf = PdfFileReader(omr_buffer)

        return omr_pdf.getPage(0)
开发者ID:maxime-beck,项目名称:compassion-modules,代码行数:47,代码来源:communication_job.py

示例3: create_prod_labels

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
    def create_prod_labels(self):
        """
        These values should be measured from the printed page.
        In all the following calculations, the bottom left corner of
        the page is considered to be at the origin of the x-y plane.
        All the coordinates should be provided w.r.t. the this origin.
        """
        # page size
        page_H = 297*mm  # A4
        page_W = 210*mm   # A4
        # coordinates of lower left corner of single label w.r.t. origin
        box_X = 16.5*mm
        box_Y = 9.6*mm
        # distance between rows and columns of labels
        box_X_shift = 46.2*mm
        box_Y_shift = 36.0*mm

        pdfmetrics.registerFont(TTFont('Arial', 'ARIALN.TTF'))
        c = Canvas(self.outFile)
        c.setLineWidth(0.1)

        # horizontal lines
        for i in range(7):
            c.line(42*mm + i*box_Y_shift, 10*mm,
                   42*mm + i*box_Y_shift, page_W-10*mm)
        # vertical lines
        for i in range(3):
            c.line(2*mm, 58*mm + i*box_X_shift,
                   page_H-2*mm, 58*mm + i*box_X_shift)

        for i in range(4):
            dx = box_X + i*box_X_shift
            for j in range(8):
                dy = box_Y + j*box_Y_shift
                self.draw_single_label(dy, dx, c)

        c.setPageRotation(90)
        c.setPageSize((page_W, page_H))
        c.save()
        self.message.setText(
            "Creating " + self.outFile.replace(self.cdir, "Documents/"))
开发者ID:iyounus,项目名称:anaqa,代码行数:43,代码来源:anaqa.py

示例4: main

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
def main():
    currpos = PAGESIZE[1] - LINEHEIGHT # start at 1 line from top of page
    pdf = Canvas(OUTPUTFILE, pagesize = ORIENTATION(PAGESIZE))
    pdf.setFillGray(1)
    pdf.setLineWidth(GUIDETHICKNESS_MAIN)
    while currpos > LINEHEIGHT: # Loop until we reach one line from bottom of page
        # Draw tall ascender line
        pdf.setStrokeGray(0.5)
        pdf.line( 0, currpos, PAGESIZE[0], currpos)

        # Draw short ascender line, x-height-line, and baseline
        pdf.setStrokeGray(0.75)
        pdf.setLineWidth(GUIDETHICKNESS_SMALL)        
        pdf.line( 0, currpos - ( LINEHEIGHT/6 ),
                  PAGESIZE[0], currpos - ( LINEHEIGHT/6 ))
        pdf.line( 0, currpos - ( LINEHEIGHT/3 ),
                  PAGESIZE[0], currpos - ( LINEHEIGHT/3 ))
        pdf.line( 0, currpos - ( 2 * LINEHEIGHT/3 ),
                  PAGESIZE[0], currpos - ( 2 * LINEHEIGHT/3 ))

        currpos -= LINEHEIGHT

    # Draw a final line, and draw a margin
    pdf.setStrokeColorRGB(0.5, 0.5, 0.5)
    pdf.setLineWidth(GUIDETHICKNESS_MAIN)
    pdf.line( 0, currpos, PAGESIZE[0], currpos)
    if LEFTMARGIN:
        pdf.line( 2 * LINEHEIGHT, currpos,
                  2 * LINEHEIGHT, PAGESIZE[1] - LINEHEIGHT ) 

    # close up.
    pdf.showPage()
    pdf.save()
开发者ID:ChaseVoid,项目名称:python-play,代码行数:35,代码来源:writingpaper.py

示例5: grid_overlay

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
def grid_overlay(infile, outfile=sys.stdout, pagesize=letter, lpi=10):
    """Read PDF file 'infile'. Generates a new PDF file to 'outfile'
    containing the first page (only) of infile, with a 'lpi' grid
    overlaid.
    """

    c = Canvas(outfile, pagesize=pagesize)

    pdf = PdfReader(infile)
    xobj = pagexobj(pdf.pages[0])
    rlobj = makerl(c, xobj)

    c.doForm(rlobj)

    xmax = 9
    ymax = 12

    thickline = 0.5
    thinline = 0.1

    for x in range(0, xmax):
        c.setLineWidth(thickline)
        for xx in range(0, lpi):
            x0 = (x + (float(xx) / lpi)) * inch
            c.line(x0, 0, x0, ymax * inch)
            c.setLineWidth(thinline)

    for y in range(0, ymax):
        c.setLineWidth(thickline)
        for yy in range(0, lpi):
            y0 = (y + (float(yy) / lpi)) * inch
            c.line(0, y0, xmax * inch, y0)
            c.setLineWidth(thinline)

    c.showPage()
    c.save()
开发者ID:chmarr,项目名称:artshow-jockey,代码行数:38,代码来源:overgrid.py

示例6: __init__

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]

#.........这里部分代码省略.........

            # Préparation
            marge_haut = copy.copy(dictDonnees["page_marge_haut"])
            marge_bas = copy.copy(dictDonnees["page_marge_bas"])

            # Calcule la largeur des cases
            largeur_case = ((largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"]) - dictDonnees["page_espace_horizontal"] * (nbre_colonnes - 1)) / nbre_colonnes

            # Dessine l'image de fond
            if dictDonnees["page_fond_image"] != "aucune" :
                canvas.drawImage(Chemins.GetStaticPath("Images/%s" % dictDonnees["page_fond_image"]), 0, 0, largeur_page, hauteur_page, preserveAspectRatio=False)

            # Dessine le titre
            if dictDonnees["titre_afficher"] == True:
                if dictDonnees["titre_texte"] != "" :
                    texte_titre = u"%s %s" % (dictDonnees["titre_texte"], texte_titre)
                titre = Titre(parent=self, texte=texte_titre, canvas=canvas, largeur=largeur_page)
                marge_haut += dictDonnees["titre_hauteur"]

            # Dessine les entêtes
            if dictDonnees["entete_afficher"] == True:
                for num_colonne in range(0, nbre_colonnes):
                    # Calcule la position de la case
                    x_entete = dictDonnees["page_marge_gauche"] + ((largeur_case + dictDonnees["page_espace_horizontal"]) * num_colonne)
                    y_entete = hauteur_page - marge_haut - dictDonnees["entete_hauteur"]

                    # Dessine l'entête
                    texte = UTILS_Dates.LISTE_JOURS[dictDonnees["jours_semaine"][num_colonne]]
                    entete = Entete(parent=self, texte=texte, canvas=canvas, x=x_entete, y=y_entete, largeur_case=largeur_case)

                marge_haut += dictDonnees["entete_hauteur"] + dictDonnees["page_espace_vertical"]

            # Dessine le pied
            if dictDonnees["pied_afficher"] == True and len(dictDonnees["pied_texte"]) > 0 :
                pied = Pied(parent=self, texte=dictDonnees["pied_texte"], canvas=canvas, x=dictDonnees["page_marge_gauche"], y=marge_bas, largeur=largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"])
                marge_bas += dictDonnees["pied_hauteur"] + dictDonnees["page_espace_vertical"]

            # Dessine la légende
            self.dictNumerosLegendes = {}
            if dictDonnees["legende_afficher"] == True :

                # Recherche les légendes présentes dans la page
                liste_legendes = []
                for num_colonne in range(0, nbre_colonnes):
                    for num_ligne in range(0, nbre_lignes):
                        date, dictTextes = self.GetDateAndTextes(num_ligne=num_ligne, num_colonne=num_colonne, dict_page=dict_page, calendrier=calendrier)
                        for IDcategorie, dictTexte in dictTextes.iteritems():
                            for chaine in REGEX_LEGENDES.findall(dictTexte["texte"]):
                                try :
                                    IDlegende = int(chaine[1:-1])
                                    dictLegende = self.dictDonnees["legendes"][IDlegende]
                                    if dictLegende not in liste_legendes and self.dictDonnees["legendes"].has_key(IDlegende) :
                                        liste_legendes.append(dictLegende)
                                except :
                                    pass

                if len(liste_legendes) > 0 :
                    legende = Legende(parent=self, liste_legendes=liste_legendes, canvas=canvas, x=dictDonnees["page_marge_gauche"], y=marge_bas, largeur=largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"])
                    self.dictNumerosLegendes = legende.dictNumerosLegendes
                    marge_bas += dictDonnees["legende_hauteur"] + dictDonnees["page_espace_vertical"]


            # Calcul la hauteur des cases
            hauteur_case = ((hauteur_page - marge_haut - marge_bas) - dictDonnees["page_espace_vertical"] * (nbre_lignes - 1)) / nbre_lignes

            # Dessine les cases
            for num_colonne in range(0, nbre_colonnes):
                for num_ligne in range(0, nbre_lignes):

                    # Calcule la position de la case
                    x_case = dictDonnees["page_marge_gauche"] + ((largeur_case + dictDonnees["page_espace_horizontal"]) * num_colonne)
                    y_case = hauteur_page - marge_haut - hauteur_case - ((hauteur_case + dictDonnees["page_espace_vertical"]) * num_ligne)

                    # Recherche la date et les textes
                    date, dictTextes = self.GetDateAndTextes(num_ligne=num_ligne, num_colonne=num_colonne, dict_page=dict_page, calendrier=calendrier)

                    # Dessin de la case
                    case = Case(parent=self, date=date, dictTextes=dictTextes, canvas=canvas, x=x_case, y=y_case, largeur_case=largeur_case, hauteur_case=hauteur_case)

            # Dessine la grille
            if dictDonnees["page_grille"] == True :
                canvas.setStrokeColor(ColorWxToPdf(wx.LIGHT_GREY, alpha=0.5))
                canvas.setFillColor(ColorWxToPdf(wx.LIGHT_GREY, alpha=0.5))
                canvas.setLineWidth(0.25)
                canvas.grid(range(0, int(largeur_page)+50, 50), range(0, int(hauteur_page)+50, 50))
                canvas.setFont("Helvetica", 8)
                canvas.drawString(10, 10, _(u"Largeur carreau=50"))

            # Saut de page
            if num_page < len(liste_pages) - 1:
                canvas.showPage()


        # Finalisation du PDF
        canvas.save()

        try:
            FonctionsPerso.LanceFichierExterne(nomDoc)
        except:
            print "Probleme dans l'edition du menu"
开发者ID:bogucool,项目名称:Noethys,代码行数:104,代码来源:UTILS_Impression_menu.py

示例7: make_canvas

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
 def make_canvas(*args, **kwargs):
     canvas = Canvas(*args, **kwargs)
     canvas.setLineWidth(0.25)
     return canvas
开发者ID:mvpoland,项目名称:django-pdfgen,代码行数:6,代码来源:parser.py

示例8: PDFGenerator

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]

#.........这里部分代码省略.........
			if color[0] == uc2const.COLOR_RGB:
				r, g, b = color[1]
				return Color(r, g, b, alpha)
			elif color[0] == uc2const.COLOR_GRAY:
				k = 1.0 - color[1][0]
				c = m = y = 0.0
				pdfcolor = CMYKColor(c, m, y, k, alpha=alpha)
			else:
				c, m, y, k = self.cms.get_cmyk_color(color)[1]
				pdfcolor = CMYKColor(c, m, y, k, alpha=alpha)

		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)
开发者ID:sk1project,项目名称:sk1-wx,代码行数:70,代码来源:pdfgen.py

示例9: to_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [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()
开发者ID:c-holtermann,项目名称:HocrConverter,代码行数:104,代码来源:HocrConverter.py

示例10: __init__

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
    def __init__(self, 
                    IDmodele=None, 
                    taillePage=(210, 297),
                    listeValeurs=[],
                    margeHaut=10,
                    margeGauche=10,
                    margeBas = 10,
                    margeDroite=10,
                    espaceVertical=5,
                    espaceHorizontal=5,
                    nbre_copies=1,
                    AfficherContourEtiquette=True,
                    AfficherReperesDecoupe=True,
                    ):

        # ----------------------------------------------------------------------------------------------------------------------------------------
        
        def AfficheReperesDecoupe():
            if AfficherReperesDecoupe == True :
                canvas.setStrokeColor( (0.9, 0.9, 0.9) )
                canvas.setLineWidth(0.25)
                # Repères de colonnes
                for y1, y2 in [(hauteurPage*mm-4*mm, hauteurPage*mm-margeHaut*mm+2*mm), (4*mm, margeBas-2*mm)] :
                    x = margeGauche*mm
                    for numColonne in range(0, nbreColonnes):
                        canvas.line(x, y1, x, y2)
                        x += largeurEtiquette*mm
                        canvas.line(x, y1, x, y2)
                        x += espaceHorizontal*mm
                # Repères de lignes
                for x1, x2 in [(4*mm, margeGauche*mm-2*mm), (largeurPage*mm-4*mm, largeurPage*mm-margeDroite*mm+2*mm)] :
                    y = hauteurPage*mm - margeHaut*mm
                    for numLigne in range(0, nbreLignes):
                        canvas.line(x1, y, x2, y)
                        y -= hauteurEtiquette*mm
                        canvas.line(x1, y, x2, y)
                        y -= espaceVertical*mm
        
        # -----------------------------------------------------------------------------------------------------------------------------------------
        
        largeurPage = taillePage[0]
        hauteurPage = taillePage[1]

        # Initialisation du modèle de document
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        largeurEtiquette = modeleDoc.dictInfosModele["largeur"]
        hauteurEtiquette = modeleDoc.dictInfosModele["hauteur"]
        
        # Calcul du nbre de colonnes et de lignes
        nbreColonnes = (largeurPage - margeGauche - margeDroite + espaceHorizontal) / (largeurEtiquette + espaceHorizontal)
        nbreLignes = (hauteurPage - margeHaut - margeBas + espaceVertical) / (hauteurEtiquette + espaceVertical)
        
        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("ETIQUETTES", "pdf")
        canvas = Canvas(nomDoc, pagesize=(largeurPage*mm, hauteurPage*mm))
        
        # Création des étiquettes
        numColonne = 0
        numLigne = 0
        for dictValeurs in listeValeurs :
            for num_copie in range(0, nbre_copies) :
                x = margeGauche + ((largeurEtiquette + espaceHorizontal) * numColonne)
                y = hauteurPage - margeHaut - hauteurEtiquette - ((hauteurEtiquette + espaceVertical) * numLigne)

                # Positionnement sur la feuille
                canvas.saveState()
                canvas.translate(x*mm, y*mm)

                # Création du clipping
                p = canvas.beginPath()
                canvas.setStrokeColor( (1, 1, 1) )
                canvas.setLineWidth(0.25)
                p.rect(0, 0, largeurEtiquette*mm, hauteurEtiquette*mm)
                canvas.clipPath(p)

                # Dessin de l'étiquette
                modeleDoc.DessineFond(canvas, dictChamps=dictValeurs)
                etat = modeleDoc.DessineTousObjets(canvas, dictChamps=dictValeurs)
                if etat == False :
                    return

                # Dessin du contour de l'étiquette
                if AfficherContourEtiquette == True :
                    canvas.setStrokeColor( (0, 0, 0) )
                    canvas.setLineWidth(0.25)
                    canvas.rect(0, 0, largeurEtiquette*mm, hauteurEtiquette*mm)

                canvas.restoreState()

                # Saut de colonne
                numColonne += 1
                # Saut de ligne
                if numColonne > nbreColonnes - 1 :
                    numLigne += 1
                    numColonne = 0
                # Saut de page
                if numLigne > nbreLignes - 1 :
                    AfficheReperesDecoupe()
                    canvas.showPage()
                    numLigne = 0
#.........这里部分代码省略.........
开发者ID:CugeDe,项目名称:Noethys,代码行数:103,代码来源:UTILS_Impression_etiquettes.py

示例11: min

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
                    hi = hi - croplen.val + cropdist.val

                    cropposns = image.get(crops, cropdefault)
                    for cpos in cropposns:
                        if not cpos.abs:
                            cpos = cpos.normalise(image[pix], image[dim])
                        pmin = min(cpos.val, pmin)
                        pmax = max(cpos.val, pmax)

                image[pos] = ((lo+hi) - (pmax+pmin)) / 2.0
                image[minval] = image[pos] + pmin
                image[maxval] = image[pos] + pmax

        # Draw crop marks.
        if image.get('crops',False):
            pdf.setLineWidth(inch/720.0)
            pdf.setLineCap(0)
            for xcrop in image.get("xcrops", cropdefault):
                if not xcrop.abs:
                    xcrop = xcrop.normalise(image["pw"], image["w"])
                pdf.line(xcrop.val + image["x"], image["y0"] - cropdist.val,
                         xcrop.val + image["x"], image["y0"] - cropdist.val - croplen.val)
                pdf.line(xcrop.val + image["x"], image["y1"] + cropdist.val,
                         xcrop.val + image["x"], image["y1"] + cropdist.val + croplen.val)
            for ycrop in image.get("ycrops", cropdefault):
                if not ycrop.abs:
                    ycrop = ycrop.normalise(image["ph"], image["h"])
                pdf.line(image["x0"] - cropdist.val, ycrop.val + image["y"],
                         image["x0"] - cropdist.val - croplen.val, ycrop.val + image["y"])
                pdf.line(image["x1"] + cropdist.val, ycrop.val + image["y"],
                         image["x1"] + cropdist.val + croplen.val, ycrop.val + image["y"])
开发者ID:rdebath,项目名称:sgt,代码行数:33,代码来源:imagepdf.py

示例12: to_pdf

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [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()
开发者ID:rslinford,项目名称:H4D_Data_Liberation,代码行数:104,代码来源:HocrTransform2.py

示例13: yourfilename

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
class CreatePDF:
    """
    A class to create a PDF with the slides from AudioCours Version 2 recording
    
    Usage:
    
    Python CrezatePDF.py myDirectoryPath yourfilename (without the .pdf)
    """
    
    def __init__(self):
        """
        Initialize the PDF (A4) and reade the timecode file
        """
        self.pdf = Canvas(workingDirectory+"/"+pdfName+".pdf")
        timecode= open(workingDirectory+"/timecode.csv",'r')
        self.slides=[]
        for line in timecode:
            print "Found slide at t (seconds) = "+line
            self.slides.append(line)
        self.slides=self.slides[1:]#Don't use the first slide
        print "\nNumber of slides to process :", len(self.slides)
        print "\nPlease wait while processing ..."
        
    def timeToHMS(self,t):
        """ 
        Return a Hour Minute Seconds string from the time given in seconds
        """
        t=float(t)
        hours=int(t/3600)
        mins=int(t-hours*3600)/60
        seconds=int(t-hours*3600-mins*60)
        hms= str(hours)+" h "+str(mins)+" m "+str(seconds)+" s "
        return  hms
        
    def produce(self):
        """
        Draw in the PDF the screenshots and datas
        (2 screenshots per page : Up and Down)
        """
        d=1
        # Slides Positions
        SUx,SUy=3*cm,3*cm # upper slide
        SDx,SDy=3*cm,16*cm #Slide Down (bottom)
        Swidth,Sheight= 16*cm,11*cm
        
        while d <= len(self.slides):
            
            self.pdf.setFont("Courier", 10)
            #self.pdf.setStrokeColorRGB(1,1,0)
            self.pdf.setStrokeColor("grey")
            self.pdf.setLineWidth(2) 
        
            if d % 2 == 0: # Upper slide
                captureTime =self.timeToHMS(self.slides[d-1])
                self.pdf.drawString(SUx, SUy-0.5*cm, "^ Capture "+str(d)+\
                " (timing = "+ captureTime +")")
                self.pdf.drawImage(workingDirectory+"/screenshots/D"+str(d)+\
                ".jpg", SUx,SUy,width=Swidth,height=Sheight)
                self.pdf.rect(SUx,SUy,Swidth,Sheight, fill=0)
                self.pdf.showPage()
                if d==len(self.slides):
                    self.pdf.save()
                
            if d % 2 != 0: # Down slide (bottom)
                captureTime =self.timeToHMS(self.slides[d-1])
                self.pdf.drawString(SDx,SDy-cm*0.5, "^ Capture "+str(d)+\
                " (timing = "+ captureTime +")")
                self.pdf.drawImage(workingDirectory+"/screenshots/D"+str(d)+\
                ".jpg", SDx,SDy, width=Swidth,height=Sheight)
                self.pdf.rect(SDx,SDy,Swidth,Sheight, fill=0)
                if d==len(self.slides):
                    self.pdf.showPage()
                    self.pdf.save()
            d+=1
        if len (self.slides)>= 1: print "\nPDF File saved"
        if len(self.slides)<1: print "\nNo slides to process : No PDF produced"
开发者ID:nicktruch,项目名称:avc-client,代码行数:78,代码来源:PDFgen.py

示例14: print_many_areas

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]
def print_many_areas(areas):
    init_pdf()

    c = Canvas('1.pdf', pagesize = A4)

    x = (A4[0] - BLANK_WIDTH) / 2
    y = (A4[1] - 3*BLANK_HEIGHT) / 2


    map_urls = [ build_map_url(area.x, area.y, area.zoom, area.marks) for area in areas ]


    urls_to_fetch = []
    map_pngs = {}
    for url in map_urls:
        png = MapCache.get_map(url)
        if png:
            map_pngs[url] = png
        else:
            urls_to_fetch.append(url)


    if urls_to_fetch:
        pool = multiprocessing.Pool(16)
        fetched_pngs = pool.map(fetch_map, urls_to_fetch)
        pool.close()
    else:
        fetched_pngs = []


    for url, png in izip(urls_to_fetch, fetched_pngs):
        if png is None:
            raise Exception("Cannot fetch {0}".format(url))
        map_pngs[url] = png

    map_images = {}
    for url, png in map_pngs.iteritems():
        map_images[url] = adjust_colors(Image.open(StringIO.StringIO(png)).convert('RGB'))


    # Saving PNG to MapCache only after creating Image from it to insure it is proper PNG
    for url, png in izip(urls_to_fetch, fetched_pngs):
        MapCache.save_map(url, png)


    for page_no in xrange((len(areas) + 2) / 3):
        page_set = areas[page_no*3 : (page_no+1)*3]

        c.setLineWidth(0.5)
        c.setStrokeGray(0.5)
        c.line(x, 0, x, A4[1])
        c.line(x + BLANK_WIDTH, 0, x + BLANK_WIDTH, A4[1])

        c.line(0, y + 3*BLANK_HEIGHT, A4[0], y + 3*BLANK_HEIGHT)

        print_area_blank(c, x, y + 2*BLANK_HEIGHT, areas[page_no*3 + 0], map_images[map_urls[page_no*3 + 0]])
        c.line(0, y + 2*BLANK_HEIGHT, A4[0], y + 2*BLANK_HEIGHT)

        if len(page_set) >= 2:
            print_area_blank(c, x, y + BLANK_HEIGHT, areas[page_no*3 + 1], map_images[map_urls[page_no*3 + 1]])
            c.line(0, y + BLANK_HEIGHT, A4[0], y + BLANK_HEIGHT)

        if len(page_set) >= 3:
            print_area_blank(c, x, y, areas[page_no*3 + 2], map_images[map_urls[page_no*3 + 2]])
            c.line(0, y, A4[0], y)

        c.showPage()


    return c.getpdfdata()
开发者ID:IlyaSkriblovsky,项目名称:jwter,代码行数:72,代码来源:printer.py

示例15: PDF

# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setLineWidth [as 别名]

#.........这里部分代码省略.........
        if titulo == '':
            componentes = (Paragraph(dados, estilo),)
        elif titulo:
            componentes = (Paragraph(titulo, pequena_esquerda), Paragraph(dados, estilo))
        else:
            componentes = dados
        altura_total = 0
        altura_texto = altura - espacamento + ajuste_inferior
        largura_texto = largura - espacamento
        renderizados = []
        if not multilinha and titulo and dados != '&nbsp;':
            componentes[1].wrapOn(self.canvas, largura_texto, altura_texto)
            linhas = componentes[1].breakLines(largura_texto).lines
            if len(linhas) > 0:
                if isinstance(linhas[0], tuple): # texto comum
                    componentes = (componentes[0], Paragraph(' '.join(linhas[0][1]), estilo))
                else: # texto com formatação
                    componentes = (componentes[0], Paragraph(''.join([linhas[0].words[i].text for i in range(len(linhas[0].words))]), estilo))
        for componente in componentes:
            larg, alt = componente.wrapOn(self.canvas, largura_texto, altura_texto)
            altura_total += alt
            altura_texto -= alt
            renderizados.append((altura_total, componente, larg))
        altura_total -= ajuste_inferior
        if altura_total < altura - espacamento:
            altura_total = altura - espacamento
        if posicao:
            x, y = posicao
            y = self.canvas._pagesize[1] - y
        else:
            pi = self.ponto_insercao(largura, altura_total + espacamento)
            if pi:
                x, y = pi
            else:
                print ('Um objeto de %i cm x %i cm não coube na página do PDF "%s" e será apresentado'
                       'no canto inferior direito desta página' % (largura / cm, altura_total / cm, self.titulo))
                x = self.canvas._pagesize[0] - largura - espessura / 2
                y = altura_total + espacamento + espessura / 2
        #print "Posição:", x/mm, y/mm
        for renderizado in renderizados:
            self.canvas.setLineWidth(espessura)
            #renderizado[1].drawOn(self.canvas, x + espacamento / 2, y - renderizado[0] - espacamento / 2)
            renderizado[1].drawOn(self.canvas, x + (largura - renderizado[2]) / 2, y - renderizado[0] - espacamento / 2)
        if borda:
            self.canvas.roundRect(x, y - altura_total - espacamento, largura, altura_total + espacamento, arredondamento)
        return (x, y, largura, altura_total + espacamento)

    def altura(self, largura, altura, titulo, dados, borda = True, arredondamento = 0.5 * mm, ajuste_inferior = 0 * mm, espacamento = None, posicao = None, espessura = None, alinhamento = 'justa', multilinha = None):
        if espessura == None:
            espessura = self.espessura
        if not espacamento:
            espacamento = self.espacamento * 2
        else:
            espacamento *= 2
        if alinhamento.lower() == 'esquerda':
            estilo = normal_esquerda
        elif alinhamento.lower() == 'direita':
            estilo = normal_direita
        elif alinhamento.lower() == 'centro':
            estilo = normal_centro
        else:
            estilo = normal_justa
        if titulo == '':
            componentes = (Paragraph(dados, estilo),)
        elif titulo:
            componentes = (Paragraph(titulo, pequena_esquerda), Paragraph(dados, estilo))
        else:
            componentes = dados
        altura_total = 0
        altura_texto = altura - espacamento + ajuste_inferior
        largura_texto = largura - espacamento
        renderizados = []
        if not multilinha and titulo and dados != '&nbsp;':
            componentes[1].wrapOn(self.canvas, largura_texto, altura_texto)
            linhas = componentes[1].breakLines(largura_texto).lines
            if len(linhas) > 0:
                if isinstance(linhas[0], tuple): # texto comum
                    componentes = (componentes[0], Paragraph(' '.join(linhas[0][1]), estilo))
                else: # texto com formatação
                    componentes = (componentes[0], Paragraph(''.join([linhas[0].words[i].text for i in range(len(linhas[0].words))]), estilo))
        for componente in componentes:
            larg, alt = componente.wrapOn(self.canvas, largura_texto, altura_texto)
            altura_total += alt
            altura_texto -= alt
            renderizados.append((altura_total, componente, larg))
        altura_total -= ajuste_inferior
        if altura_total < altura - espacamento:
            altura_total = altura - espacamento
        return altura_total + espacamento

    def salvar(self):
        self.canvas.save()

    def mostrar(self, programa = 'evince'):
        self.canvas.save()
        subprocess.Popen([programa, self.nome_do_arquivo])

    def nova_pagina(self):
        self.canvas.showPage()
        self.retangulos = [(0, 0, self.canvas._pagesize[0] - 2 * self.margem, self.canvas._pagesize[1] - 2 * self.margem)]
开发者ID:paulom,项目名称:pole,代码行数:104,代码来源:PolePDF.py


注:本文中的reportlab.pdfgen.canvas.Canvas.setLineWidth方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。