def later_pages(canvas, document): canvas.saveState() #вывести внизу QR-code (ФИО, (номера направлений)) qr_code = qr.QrCodeWidget(qr_value) qr_code.barWidth = 70 qr_code.barHeight = 70 qr_code.qrVersion = 1 bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing() d.add(qr_code) renderPDF.draw(d, canvas, 90 * mm, 7) #вывести атрибуты для подписей canvas.setFont('PTAstraSerifReg', 10) canvas.drawString(40 * mm, 10 * mm, '____________________________') canvas.drawString(115 * mm, 10 * mm, '/{}/____________________________'.format(npf)) canvas.setFont('Symbola', 18) canvas.drawString(195 * mm, 10 * mm, '\u2713') canvas.setFont('PTAstraSerifReg', 8) canvas.drawString(50 * mm, 7 * mm, '(подпись сотрудника)') canvas.drawString(160 * mm, 7 * mm, '(подпись плательщика)') canvas.rotate(90) canvas.setFillColor(HexColor(0x4f4b4b)) canvas.setFont('PTAstraSerifReg', 5.2) canvas.drawString(10 * mm, -12 * mm, '{}'.format(6 * left_size_str)) canvas.restoreState()
def _draw_single_background(self, canvas, x, margins, width, height): canvas.saveState() clipping_mask = canvas.beginPath() clipping_mask.roundRect( x + margins[Border.LEFT], margins[Border.BOTTOM], width - margins[Border.RIGHT] - margins[Border.LEFT], height - margins[Border.TOP] - margins[Border.BOTTOM], self.BACKGROUND_CORNER_DIAMETER) canvas.clipPath(clipping_mask, stroke=0, fill=0) # get optimum background orientation background_orientation = best_orientation(self.background_image_path, width, height) if background_orientation == Orientation.TURN90: canvas.rotate(90) canvas.translate(0, -self.WIDTH * 2) canvas.drawImage(self.background_image_path, 0, 0, width=height, height=width, mask=None) else: canvas.drawImage(self.background_image_path, x, 0, width=width, height=height, mask=None) canvas.restoreState()
def _draw_front(self, canvas): canvas.saveState() # Set card orientation if self.front_orientation == Orientation.TURN90: canvas.rotate(90) canvas.translate(0, -self.WIDTH) width = self.HEIGHT height = self.WIDTH else: width = self.WIDTH height = self.HEIGHT # Draw red border self._draw_single_border(canvas, 0, width, height) # Parchment background self._draw_single_background(canvas, 0, self.BORDER_FRONT, width, height) # D&D logo dnd_logo = svg2rlg("logo.svg") if dnd_logo is not None: factor = self.LOGO_WIDTH/dnd_logo.width dnd_logo.width *= factor dnd_logo.height *= factor dnd_logo.scale(factor, factor) logo_margin = (self.BORDER_FRONT[Border.TOP]-dnd_logo.height)/2 renderPDF.draw(dnd_logo, canvas, (width-self.LOGO_WIDTH)/2, height - self.BORDER_FRONT[Border.TOP] + logo_margin, ) # Titles canvas.setFillColor("black") title_height = self.fonts.set_font(canvas, "title") canvas.drawCentredString(width * 0.5, self.FRONT_MARGINS[Border.BOTTOM], self.title.upper()) # Artist if self.artist: canvas.setFillColor("white") artist_font_height = self.fonts.set_font(canvas, "artist") canvas.drawCentredString(width/2, self.BORDER_FRONT[Border.BOTTOM] - artist_font_height - 1*mm, "Artist: {}".format(self.artist)) # Image image_bottom = self.FRONT_MARGINS[Border.BOTTOM] + title_height + 1*mm canvas.drawImage(self.front_image_path, self.FRONT_MARGINS[Border.LEFT], image_bottom, width=width \ - self.FRONT_MARGINS[Border.LEFT] \ - self.FRONT_MARGINS[Border.RIGHT], height=height \ - image_bottom \ - self.FRONT_MARGINS[Border.TOP], preserveAspectRatio=True, mask='auto') canvas.restoreState()
def draw_watermark(self, canvas): if self._watermark: canvas.saveState() canvas.rotate(60) canvas.setFillColorRGB(0.9, 0.9, 0.9) canvas.setFont('%s' % self.style.fontName, 120) canvas.drawCentredString(195 * mm, -30 * mm, self._watermark) canvas.restoreState()
def draw_watermark(self, canvas): if self._watermark: canvas.saveState() canvas.rotate(60) canvas.setFillColorRGB(0.9, 0.9, 0.9) canvas.setFont('%s' % self.style.fontName, 120) canvas.drawCentredString(195*mm, -30*mm, self._watermark) canvas.restoreState()
def draw_vertical_text(canvas, font_name, font_size, xto, ymid, text): tw = stringWidth(text, font_name, font_size); canvas.setFont(font_name, font_size); canvas.saveState(); canvas.translate(xto, ymid - tw/2); canvas.rotate(90); canvas.drawString(0, 0, text); canvas.restoreState();
def _draw_front(self, canvas): canvas.saveState() # Draw red border self._draw_single_border(canvas, 0, self.width, self.height) # Parchment background self._draw_single_background( canvas, 0, self.border_front, self.width, self.height, self.front_orientation, ) # Set card orientation if self.front_orientation == Orientation.TURN90: canvas.rotate(90) canvas.translate(0, -self.width) width = self.height height = self.width else: width = self.width height = self.height # D&D logo dnd_logo = svg2rlg(ASSET_DIR / "logo.svg") if dnd_logo is not None: factor = self.LOGO_WIDTH / dnd_logo.width dnd_logo.width *= factor dnd_logo.height *= factor dnd_logo.scale(factor, factor) logo_margin = (self.border_front[Border.TOP] - self.bleed - dnd_logo.height) / 2 renderPDF.draw( dnd_logo, canvas, (width - self.LOGO_WIDTH) / 2, height - self.border_front[Border.TOP] + logo_margin, ) self._draw_front_frame(canvas, width, height) # Artist if self.artist: canvas.setFillColor("white") artist_font_height = self.fonts.set_font(canvas, "artist") canvas.drawCentredString( width / 2, self.border_front[Border.BOTTOM] - artist_font_height - 1 * mm, "Artist: {}".format(self.artist), ) canvas.restoreState()
def first_pages(canvas, document): canvas.saveState() canvas.setFont("PTAstraSerifReg", 9) # вывести интерактивную форму "текст" form = canvas.acroForm # canvas.drawString(25, 780, '') form.textfield(name='comment', tooltip='comment', fontName='Times-Roman', fontSize=10, x=57, y=750, borderStyle='underlined', borderColor=black, fillColor=white, width=515, height=13, textColor=black, forceBorder=False) # Вывести на первой странице код-номер договора barcode128.drawOn(canvas, 120 * mm, 283 * mm) #вывести внизу QR-code (ФИО, (номера направлений)) qr_code = qr.QrCodeWidget(qr_value) qr_code.barWidth = 70 qr_code.barHeight = 70 qr_code.qrVersion = 1 bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing() d.add(qr_code) renderPDF.draw(d, canvas, 90 * mm, 7) #вывести атрибуты для подписей canvas.setFont('PTAstraSerifReg', 10) canvas.drawString(40 * mm, 10 * mm, '____________________________') canvas.drawString(115 * mm, 10 * mm, '/{}/____________________________'.format(npf)) canvas.setFont('Symbola', 18) canvas.drawString(195 * mm, 10 * mm, '\u2713') canvas.setFont('PTAstraSerifReg', 8) canvas.drawString(50 * mm, 7 * mm, '(подпись сотрудника)') canvas.drawString(160 * mm, 7 * mm, '(подпись плательщика)') #вывестии защитны вертикальный мелкий текст canvas.rotate(90) canvas.setFillColor(HexColor(0x4f4b4b)) canvas.setFont('PTAstraSerifReg', 5.2) canvas.drawString(10 * mm, -12 * mm, '{}'.format(6 * left_size_str)) canvas.restoreState()
def onMyFirstPage(self, canvas, doc): # If the left_footer attribute is not None, then add it to the page canvas.saveState() if self.left_footer is not None: # canvas.setFont('Helvetica', 8) # canvas.drawString(1 * cm, 1 * cm, self.left_footer) canvas.setFont("Times-Roman", 150) canvas.setStrokeColorRGB(0.74, 0.74, 0.74) canvas.setFillColorRGB(0.74, 0.74, 0.74) canvas.translate(A4[0] / 2, A4[1] / 2) canvas.rotate(45) canvas.drawCentredString(20, 0, self.left_footer) canvas.restoreState()
def draw_page(page, uid, survey_name, canvas: reportlab.pdfgen.canvas.Canvas): draw_qr_data(canvas, 'survey:' + survey_name + ':' + page.name + ':' + uid, 64, (48, height - 64 - 48)) canvas.setFillColorRGB(0.2, 0.2, 0.2) canvas.setStrokeColorRGB(0.2, 0.2, 0.2) canvas.circle(32, 32, 4, stroke=1, fill=1) canvas.circle(32 + 12, 32, 4, stroke=1, fill=1) canvas.circle(32, 32 + 12, 4, stroke=1, fill=1) canvas.circle(width - 32, height - 32, 4, stroke=1, fill=1) canvas.circle(width - 32 - 12, height - 32, 4, stroke=1, fill=1) canvas.circle(width - 32, height - 32 - 12, 4, stroke=1, fill=1) canvas.circle(width - 32, 32, 4, stroke=1, fill=1) canvas.circle(width - 32 - 12, 32, 4, stroke=1, fill=1) canvas.circle(width - 32, 32 + 12, 4, stroke=1, fill=1) canvas.circle(32, height - 32, 4, stroke=1, fill=1) canvas.circle(32 + 12, height - 32, 4, stroke=1, fill=1) canvas.circle(32, height - 32 - 12, 4, stroke=1, fill=1) canvas.setFillColorRGB(0.3, 0.3, 0.3) canvas.drawString(128, height - 67, survey_name + ':' + page.name + ':' + uid) canvas.setFillColorRGB(0.4, 0.4, 0.4) canvas.setStrokeColorRGB(0.2, 0.2, 0.2) canvas.setFont('Courier', 8) for field in page.get_binary_fields(): canvas.circle(field.position[0], height - field.position[1], 5, stroke=1, fill=0) canvas.drawCentredString(field.position[0], height - field.position[1] - 2, field.hint) canvas.setFillColorRGB(0.1, 0.1, 0.1) for text in page.get_text_areas(): if text.rotation != 0: canvas.saveState() canvas.rotate(text.rotation) tobj = canvas.beginText(text.position[0], height - text.position[1]) tobj.setFont(text.fontname, text.fontsize) for line in text.text.split(): tobj.textLine(line) canvas.drawText(tobj) if text.rotation != 0: canvas.restoreState() canvas.showPage()
def draw(self, pmlOp, pageNr, canvas, pe): # we need to adjust y position since PDF uses baseline of text as # the y pos, but pml uses top of the text as y pos. The Adobe # standard Courier family font metrics give 157 units in 1/1000 # point units as the Descender value, thus giving (1000 - 157) = # 843 units from baseline to top of text. # http://partners.adobe.com/asn/tech/type/ftechnotes.jsp contains # the "Font Metrics for PDF Core 14 Fonts" document. x = pe.x(pmlOp.x) y = pe.y(pmlOp.y) - 0.843 * pmlOp.size if pe.doc.tocs and pmlOp.toc: key = "id%d" % id(pmlOp) canvas.bookmarkPage(key, fit="XYZ", left=pe.x(pmlOp.x), top=pe.y(pmlOp.y)) canvas.addOutlineEntry(pmlOp.toc.text, key) newFont = (pe.getFontNr(pmlOp.flags), pmlOp.size) if newFont != pe.currentFont: canvas.setFont(*newFont) pe.currentFont = newFont if pmlOp.angle is None or pmlOp.angle == 0.0: canvas.drawString(x, y, pmlOp.text) else: canvas.saveState() canvas.translate(x, y) canvas.rotate(pmlOp.angle) canvas.drawString(0, 0, pmlOp.text) canvas.restoreState() if pmlOp.flags & pml.UNDERLINED: undLen = fontinfo.getMetrics(pmlOp.flags).getTextWidth( pmlOp.text, pmlOp.size) # all standard PDF fonts have the underline line 100 units # below baseline with a thickness of 50 undY = y - 0.1 * pmlOp.size canvas.setLineWidth(0.05 * pmlOp.size) canvas.line(x, undY, x + undLen, undY)
def draw(self, pmlOp, pageNr, canvas, pe): # we need to adjust y position since PDF uses baseline of text as # the y pos, but pml uses top of the text as y pos. The Adobe # standard Courier family font metrics give 157 units in 1/1000 # point units as the Descender value, thus giving (1000 - 157) = # 843 units from baseline to top of text. # http://partners.adobe.com/asn/tech/type/ftechnotes.jsp contains # the "Font Metrics for PDF Core 14 Fonts" document. x = pe.x(pmlOp.x) y = pe.y(pmlOp.y) - 0.843 * pmlOp.size if pe.doc.tocs and pmlOp.toc: key = "id%d" % id(pmlOp) canvas.bookmarkPage(key,fit="XYZ",left=pe.x(pmlOp.x),top=pe.y(pmlOp.y)) canvas.addOutlineEntry(pmlOp.toc.text,key) newFont = (pe.getFontNr(pmlOp.flags), pmlOp.size) if newFont != pe.currentFont: canvas.setFont(*newFont) pe.currentFont = newFont if pmlOp.angle is None or pmlOp.angle == 0.0: canvas.drawString(x,y,pmlOp.text) else: canvas.saveState() canvas.translate(x,y) canvas.rotate(pmlOp.angle) canvas.drawString(0,0,pmlOp.text) canvas.restoreState() if pmlOp.flags & pml.UNDERLINED: undLen = fontinfo.getMetrics(pmlOp.flags).getTextWidth( pmlOp.text, pmlOp.size) # all standard PDF fonts have the underline line 100 units # below baseline with a thickness of 50 undY = y - 0.1 * pmlOp.size canvas.setLineWidth(0.05 * pmlOp.size) canvas.line(x, undY, x + undLen, undY)
def draw_ruler(self, canvas, x, y, length, orientation=HORIZONTAL, units=METRIC): # Ruler attributes for METRIC and IMPERIAL measurements = { CalibrationPage.METRIC: { 'resolution': 0.1 * cm, 'tick_lengths': [(1, 0.1 * cm), (10, 0.2 * cm)] }, CalibrationPage.IMPERIAL: { 'resolution': 0.03125 * inch, 'tick_lengths': [(1, 0.1 * cm), (4, 0.15 * cm), (8, 0.2 * cm), (16, 0.25 * cm), (32, 0.3 * cm)] } } canvas.saveState() canvas.setLineWidth(0.2) if orientation == CalibrationPage.VERTICAL: canvas.rotate(90) (x, y) = (y, -x) canvas.line(x, y, x + length, y) tick_placement = x settings = measurements[units] for tick in range(int(math.ceil(length / settings['resolution'])) + 1): for division, size in settings['tick_lengths']: if tick % division == 0: tick_length = size canvas.line(tick_placement, y, tick_placement, y - tick_length) tick_placement += settings['resolution'] canvas.restoreState()
def draw_page(page, uid, survey_name, canvas : reportlab.pdfgen.canvas.Canvas): draw_qr_data(canvas, 'survey:'+survey_name+':'+page.name+':'+uid, 64, (48, height-64-48)) canvas.setFillColorRGB(0.2, 0.2, 0.2) canvas.setStrokeColorRGB(0.2, 0.2, 0.2) canvas.circle(32, 32, 4, stroke=1, fill=1) canvas.circle(32+12, 32, 4, stroke=1, fill=1) canvas.circle(32, 32+12, 4, stroke=1, fill=1) canvas.circle(width - 32, height - 32, 4, stroke=1, fill=1) canvas.circle(width - 32-12, height - 32, 4, stroke=1, fill=1) canvas.circle(width - 32, height - 32-12, 4, stroke=1, fill=1) canvas.circle(width - 32, 32, 4, stroke=1, fill=1) canvas.circle(width - 32-12, 32, 4, stroke=1, fill=1) canvas.circle(width - 32, 32+12, 4, stroke=1, fill=1) canvas.circle(32, height - 32, 4, stroke=1, fill=1) canvas.circle(32+12, height - 32, 4, stroke=1, fill=1) canvas.circle(32, height - 32-12, 4, stroke=1, fill=1) canvas.setFillColorRGB(0.3, 0.3, 0.3) canvas.drawString(128, height - 67, survey_name+':'+page.name+':'+uid) canvas.setFillColorRGB(0.4, 0.4, 0.4) canvas.setStrokeColorRGB(0.2, 0.2, 0.2) canvas.setFont('Courier', 8) for field in page.get_binary_fields(): canvas.circle(field.position[0], height - field.position[1], 5, stroke=1, fill=0) canvas.drawCentredString(field.position[0], height - field.position[1]-2, field.hint) canvas.setFillColorRGB(0.1, 0.1, 0.1) for text in page.get_text_areas(): if text.rotation != 0: canvas.saveState() canvas.rotate(text.rotation) tobj = canvas.beginText(text.position[0], height - text.position[1]) tobj.setFont(text.fontname, text.fontsize) for line in text.text.split(): tobj.textLine(line) canvas.drawText(tobj) if text.rotation != 0: canvas.restoreState() canvas.showPage()
def write_title_and_credits(canvas, text, nib_width, partitions, angles, pagesize, horizontal = False): canvas.setFillColorRGB(0, 0, 0, 1) if not horizontal: canvas.rotate(90) t = canvas.beginText() if text: canvas.setTitle(text) t.setTextOrigin(10*mm, 3*mm) t.setFont("Times-Italic", 20) t.textOut(text) t.setFont("Times-Italic", 10) t.textOut(" (%smm nib, Partitions:%s, angles:%s)"%(nib_width, partitions, angles)) # canvas.setFillColorRGB(0, 0, 0, 0.2) # w,l = (float(x)/100 for x in A4) # print w,",",l if not horizontal: t.setTextOrigin(10*mm, -pagesize[0]-5*mm) t.setFont("Times-Roman", 10) t.textOut(" Generated using ") t.setFont("Times-Italic", 10) t.textOut("http://calligraffiti.in/rulings") canvas.drawText(t)
def write_title_and_credits(canvas, opts, pagesize): canvas.saveState() if pagesize[0] > pagesize[1]: width = pagesize[0] height = pagesize[1] else: width = pagesize[1] height = pagesize[0] canvas.rotate(90) canvas.translate(0, -pagesize[0]) t = canvas.beginText() t.setFont("Times-Roman", 10) l = stringWidth(__COPYRIGHT__, "Times-Roman", 10) t.setTextOrigin(width - l - 5*mm, height+5*mm) t.textOut(__COPYRIGHT__) canvas.setFillColorRGB(0, 0, 0, 0.4) canvas.drawText(t) canvas.setFillColorRGB(0, 0, 0, 1) if opts.title: t = canvas.beginText() t.setTextOrigin(5*mm, height+5*mm) t.setFont("Times-Italic", 20) t.textOut(opts.title) canvas.drawText(t) t = canvas.beginText() t.setTextOrigin(5*mm, -5*mm) t.setFont("Times-Italic", 8) t.textOut(opts.subject) canvas.drawText(t) canvas.restoreState()
def render_text(deck, canvas, left, top): # deck name canvas.setStrokeColor(black) canvas.setFillColor(black) canvas.setFont("Roboto", 9) canvas.rotate(90) name_parts = deck['Name'].split(' ') char_count = 0 name_line_1 = "" name_line_2 = "" while len(name_parts) > 0: char_count += len(name_parts[0] + " ") if char_count <= 26: name_line_1 += name_parts[0] + " " else: name_line_2 += name_parts[0] + " " name_parts.pop(0) canvas.drawString(top + format['name'][1], (left + format['name'][0]) * -1, name_line_1) canvas.drawString(top + format['name'][1], (left + format['name'][0] + 3 * mm) * -1, name_line_2) canvas.setFont("Roboto", 7) canvas.drawString((top + format['sas_updated'][1]), (left + format['sas_updated'][0]) * -1, "SAS updated: " + str(deck['Last SAS Update'])) canvas.rotate(-90) canvas.setFont("Roboto Mono", 8) canvas.drawString(left + format['amber_control'][0], top + format['amber_control'][1], str(round(deck['Amber Control'], 2)).rjust(5)) canvas.drawString(left + format['expected_amber'][0], top + format['expected_amber'][1], str(round(deck['Expected Amber'], 2)).rjust(5)) canvas.drawString(left + format['artifact_control'][0], top + format['artifact_control'][1], str(round(deck['Artifact Control'], 2)).rjust(5)) canvas.drawString(left + format['creature_control'][0], top + format['creature_control'][1], str(round(deck['Creature Control'], 2)).rjust(5)) canvas.drawString(left + format['effective_power'][0], top + format['effective_power'][1], str(round(deck['Effective Power'], 2)).rjust(5)) canvas.drawString(left + format['creature_protection'][0], top + format['creature_protection'][1], str(round(deck['Creature Protection'], 2)).rjust(5)) canvas.drawString(left + format['efficiency'][0], top + format['efficiency'][1], str(round(deck['Efficiency'], 2)).rjust(5)) canvas.drawString(left + format['disruption'][0], top + format['disruption'][1], str(round(deck['Disruption'], 2)).rjust(5)) canvas.drawString(left + format['bonus_amber'][0], top + format['bonus_amber'][1], str(round(deck['Raw Amber'])).rjust(5)) canvas.drawString(left + format['key_cheat'][0], top + format['key_cheat'][1], str(round(deck['Key Cheat Count'])).rjust(5)) canvas.drawString(left + format['archive'][0], top + format['archive'][1], str(round(deck['Card Archive Count'])).rjust(5)) canvas.drawString(left + format['other'][0], top + format['other'][1], str(round(deck['Other'], 2)).rjust(5)) canvas.drawString(left + format['actions'][0], top + format['actions'][1], str(round(deck['Action Count'])).rjust(5)) canvas.drawString(left + format['creatures'][0], top + format['creatures'][1], str(round(deck['Creature Count'])).rjust(5)) canvas.drawString(left + format['artifacts'][0], top + format['artifacts'][1], str(round(deck['Artifact Count'])).rjust(5)) canvas.drawString(left + format['upgrades'][0], top + format['upgrades'][1], str(round(deck['Upgrade Count'])).rjust(5)) canvas.setFont("Roboto Mono", 8) canvas.drawString(left + format['common'][0], top + format['common'][1], rarities['common'].rjust(2)) canvas.drawString(left + format['uncommon'][0], top + format['uncommon'][1], rarities['uncommon'].rjust(2)) canvas.drawString(left + format['rare'][0], top + format['rare'][1], rarities['rare'].rjust(2)) canvas.drawString(left + format['special'][0], top + format['special'][1], rarities['special'].rjust(2)) canvas.drawString(left + format['maverick'][0], top + format['maverick'][1], rarities['maverick'].rjust(2)) canvas.drawString(left + format['legacy'][0], top + format['legacy'][1], rarities['legacy'].rjust(2)) canvas.drawString(left + format['anomaly'][0], top + format['anomaly'][1], rarities['anomaly'].rjust(2)) canvas.setFont("Roboto Mono", 20) canvas.setStrokeColor(white) canvas.setFillColor(white) canvas.drawString(left + format['sas'][0], top + format['sas'][1], str(deck['Sas Rating']).rjust(3)) canvas.setFont("Roboto Mono", 9) canvas.drawString(left + format['card_rating'][0], top + format['card_rating'][1], str(deck['Raw Aerc Score']).rjust(3)) canvas.drawString(left + format['synergy'][0], top + format['synergy'][1], "+" + str(deck['Synergy Rating']).rjust(2)) canvas.drawString(left + format['antisynergy'][0], top + format['antisynergy'][1], "-" + str(deck['Antisynergy Rating']).rjust(2)) canvas.drawString( left + format['meta'][0], top + format['meta'][1], "+" + str(deck['META Score']).rjust(2) if deck['META Score'] >= 0 else "-" + str(abs(deck['META Score'])).rjust(2)) canvas.setFont("Roboto Mono", 12) canvas.drawString(left + format['house_1_aerc'][0], top + format['house_1_aerc'][1], str(round(deck['House 1 SAS'])).rjust(2)) canvas.drawString(left + format['house_2_aerc'][0], top + format['house_2_aerc'][1], str(round(deck['House 2 SAS'])).rjust(2)) canvas.drawString(left + format['house_3_aerc'][0], top + format['house_3_aerc'][1], str(round(deck['House 3 SAS'])).rjust(2))
def add_length_legend(self, canvas, y, text): canvas.saveState() canvas.setFont(self.font, 10) canvas.rotate(90) canvas.drawString(y, self.length_legend, str(text)) canvas.restoreState()
def generatePage(words, canvas: canvas.Canvas, page: PageSettings, title): """ :param words: matrix of words (rows * columns) :param canvas: PDF canvas :param meta: other information (e.g page title) :return: """ if page.landscape: (marginR, marginT, marginL, marginB) = page.margins (height, width) = page.pagesize titleX = marginT titleY = width - marginR else: (marginT, marginL, marginB, marginR) = page.margins (width, height) = page.pagesize titleX = marginL titleY = height - marginT # if page.title: # canvas.setFont("HatWordFont", page.titleFontSize) # canvas.drawString(titleX + page.titleIndent, titleY - page.titleHeight / 2, title) if page.landscape: canvas.rotate(90) canvas.translate(0, -height) gwidth = width - marginL - marginR gheight = height - marginT - marginB goriginx = marginL goriginy = marginB # if page.title: # if page.landscape: # gwidth -= page.titleHeight # else: # gheight -= page.titleHeight if page.cutGrid: canvas.setStrokeColor(black) # Large bold rectangle canvas.setLineWidth(0.4 * mm) canvas.rect(goriginx, goriginy, gwidth, gheight) # outer cutting lines: canvas.setLineWidth(0.3 * mm) canvas.line(0, goriginy, width, goriginy) canvas.line(0, goriginy + gheight, width, goriginy + gheight) canvas.line(goriginx, 0, goriginx, height) canvas.line(goriginx + gwidth, 0, goriginx + gwidth, height) # grid cellWidth = gwidth / page.columns cellHeight = gheight / page.rows canvas.setLineWidth(0.2 * mm) canvas.grid([goriginx + i * cellWidth for i in range(page.columns + 1)], [goriginy + j * cellHeight for j in range(page.rows + 1)]) # add words canvas.setFont("HatWordFont", page.fontSize) # As y starts at the end of the page, adjust for it and start from the top # (so that empty cells will placed be at bottom). yoffset = goriginy + cellHeight / 2 + cellHeight * (page.rows - 1) for row in words: xoffset = goriginx + cellWidth / 2 for word in row: # scale down font size for long words numlines = word.count(";") + 1 fontSize = page.fontSize while fontSize > 0 and max( canvas.stringWidth(w, fontSize=fontSize) for w in word.split(";")) >= cellWidth - 2 * page.wordMargin - 0.5: fontSize -= 1 canvas.setFontSize(fontSize) # Somewhat cheap guess on string height : fontsize / 2 yoff = yoffset + fontSize * numlines * 0.65 - fontSize / 2 # print("99999999", word) flag = False for i in word.split(";"): print(i) if (flag): yoff -= fontSize * 1.1 if (i[:5] == "Место"): flag = True else: flag = False if (i == word.split(";")[0]): canvas.setFont("HatWordFontBold", page.titleFontSize) canvas.setFontSize(fontSize) canvas.drawCentredString(xoffset, yoff, i) yoff -= fontSize * 1.1 else: canvas.drawString(xoffset - cellWidth / 2 + 10, yoff, i) if (i == word.split(";")[0]): canvas.setFont("HatWordFont", page.titleFontSize) canvas.setFontSize(fontSize) yoff -= fontSize * 1.1 xoffset += cellWidth yoffset -= cellHeight
def render_element(root, element, canvas, styles, text_state=None): canvas.saveState() current_style = {} if len(styles): current_style.update(styles[-1]) for declaration in element.get("style", "").split(";"): if declaration == "": continue key, value = declaration.split(":") if key == "dominant-baseline" and value == "inherit": continue current_style[key] = value styles.append(current_style) if "stroke-width" in current_style: canvas.setLineWidth(float(current_style["stroke-width"])) if "stroke-dasharray" in current_style: canvas.setDash([float(length) for length in current_style["stroke-dasharray"].split(",")]) if current_style.get("visibility") != "hidden": if "transform" in element.attrib: for transformation in element.get("transform").split(")")[::1]: if transformation: type, arguments = transformation.split("(") arguments = arguments.split(",") if type.strip() == "translate": if len(arguments) == 2: canvas.translate(float(arguments[0]), float(arguments[1])) elif type.strip() == "rotate": if len(arguments) == 1: canvas.rotate(float(arguments[0])) if len(arguments) == 3: canvas.translate(float(arguments[1]), float(arguments[2])) canvas.rotate(float(arguments[0])) canvas.translate(-float(arguments[1]), -float(arguments[2])) if element.tag == "svg": if "background-color" in current_style: set_fill_color(canvas, toyplot.color.css(current_style["background-color"])) canvas.rect( 0, 0, float(element.get("width")[:-2]), float(element.get("height")[:-2]), stroke=0, fill=1 ) for child in element: render_element(root, child, canvas, styles) elif element.tag == "g": if element.get("clip-path", None) is not None: clip_id = element.get("clip-path")[5:-1] clip_path = root.find(".//*[@id='%s']" % clip_id) for child in clip_path: if child.tag == "rect": x = float(child.get("x")) y = float(child.get("y")) width = float(child.get("width")) height = float(child.get("height")) path = canvas.beginPath() path.moveTo(x, y) path.lineTo(x + width, y) path.lineTo(x + width, y + height) path.lineTo(x, y + height) path.close() canvas.clipPath(path, stroke=0, fill=1) else: toyplot.log.error("Unhandled clip tag: %s" % child.tag) # pragma: no cover for child in element: render_element(root, child, canvas, styles) elif element.tag == "clipPath": pass elif element.tag == "line": stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) canvas.line( float(element.get("x1")), float(element.get("y1")), float(element.get("x2")), float(element.get("y2")), ) elif element.tag == "path": stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) path = canvas.beginPath() commands = element.get("d").split() while len(commands): command = commands.pop(0) if command == "L": path.lineTo(float(commands.pop(0)), float(commands.pop(0))) elif command == "M": path.moveTo(float(commands.pop(0)), float(commands.pop(0))) canvas.drawPath(path) elif element.tag == "polygon": fill, fill_gradient = get_fill(root, current_style) if fill_gradient is not None: raise NotImplementedError("Gradient <polygon> not implemented.") # pragma: no cover if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) points = [point.split(",") for point in element.get("points").split()] path = canvas.beginPath() for point in points[:1]: path.moveTo(float(point[0]), float(point[1])) for point in points[1:]: path.lineTo(float(point[0]), float(point[1])) path.close() canvas.drawPath(path, stroke=stroke is not None, fill=fill is not None) elif element.tag == "rect": fill, fill_gradient = get_fill(root, current_style) if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) x = float(element.get("x")) y = float(element.get("y")) width = float(element.get("width")) height = float(element.get("height")) path = canvas.beginPath() path.moveTo(x, y) path.lineTo(x + width, y) path.lineTo(x + width, y + height) path.lineTo(x, y + height) path.close() if fill_gradient is not None: pdf_colors = [] pdf_offsets = [] for stop in fill_gradient: offset = float(stop.get("offset")) color = toyplot.color.css(stop.get("stop-color")) opacity = float(stop.get("stop-opacity")) pdf_colors.append(reportlab.lib.colors.Color(color["r"], color["g"], color["b"], color["a"])) pdf_offsets.append(offset) canvas.saveState() canvas.clipPath(path, stroke=0, fill=1) canvas.setFillAlpha(1) canvas.linearGradient( float(fill_gradient.get("x1")), float(fill_gradient.get("y1")), float(fill_gradient.get("x2")), float(fill_gradient.get("y2")), pdf_colors, pdf_offsets, ) canvas.restoreState() canvas.drawPath(path, stroke=stroke is not None, fill=fill is not None) elif element.tag == "circle": fill, fill_gradient = get_fill(root, current_style) if fill_gradient is not None: raise NotImplementedError("Gradient <circle> not implemented.") # pragma: no cover if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) cx = float(element.get("cx")) cy = float(element.get("cy")) r = float(element.get("r")) canvas.circle(cx, cy, r, stroke=stroke is not None, fill=fill is not None) elif element.tag == "text": text_state = {"x": 0, "y": 0, "chunks": [[]]} for child in element: render_element(root, child, canvas, styles, text_state) for chunk in text_state["chunks"]: width = sum([span[7] for span in chunk]) dx = 0 text_anchor = current_style.get("text-anchor", "start") if text_anchor == "middle": dx = -width * 0.5 elif text_anchor == "end": dx = -width for x, y, fill, stroke, font_family, font_size, text, width in chunk: canvas.saveState() canvas.setFont(font_family, font_size) if fill is not None: set_fill_color(canvas, fill) if stroke is not None: set_stroke_color(canvas, stroke) canvas.translate(x + dx, y) canvas.scale(1, -1) canvas.drawString(0, 0, text) canvas.restoreState() elif element.tag == "tspan": # if "font-weight" in current_style: # font_description.set_weight( # pango.WEIGHT_BOLD if current_style["font-weight"] == "bold" else pango.WEIGHT_NORMAL) font_family = get_font_family(current_style) font_size = toyplot.units.convert(current_style["font-size"].strip(), "px") string_width = reportlab.pdfbase.pdfmetrics.stringWidth(element.text, font_family, font_size) ascent, descent = reportlab.pdfbase.pdfmetrics.getAscentDescent(font_family, font_size) if "x" in element.attrib: text_state["x"] = float(element.get("x")) text_state["chunks"].append([]) if "dy" in element.attrib: text_state["y"] += float(element.get("dy")) x = text_state["x"] y = text_state["y"] alignment_baseline = current_style.get("alignment-baseline", "middle") if alignment_baseline == "hanging": y += ascent elif alignment_baseline == "central": y += ascent * 0.5 elif alignment_baseline == "middle": y += (ascent + descent) * 0.5 elif alignment_baseline == "alphabetic": pass else: raise ValueError("Unsupported alignment-baseline: %s" % alignment_baseline) # pragma: no cover baseline_shift = current_style.get("baseline-shift", "0").strip() baseline_shift = toyplot.units.convert(baseline_shift, "px", "px", ascent - descent) y -= baseline_shift fill, fill_gradient = get_fill(root, current_style) stroke = get_stroke(current_style) text_state["chunks"][-1].append( (x, y, fill, stroke, font_family, font_size, element.text, string_width) ) text_state["x"] += string_width elif element.tag in ["defs", "title"]: pass else: raise Exception("unhandled tag: %s" % element.tag) # pragma: no cover styles.pop() canvas.restoreState()
help = 'Prefix attached to the file name when processed', required = False) #this line is necessary to process arguments though #it should be done in an automatic mode args = parser.parse_args() packet = io.BytesIO() #Set the Arial font pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf')) canvas = Canvas(packet, pagesize=A4) canvas.setFont('Arial', 13) #Prepare in-memory PDF with inscription #to be merged into the existing PDFs canvas.rotate(90) canvas.drawString(20, -A4[0]+35, args.Name) canvas.drawString(20, -A4[0]+50, '') canvas.drawString(20, -A4[0]+65, args.Position) canvas.drawString(20, -A4[0]+80, "Копия верна") canvas.save() # move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDFs for pdf_file in args.FileNames: if os.path.exists(pdf_file) and os.path.isfile(pdf_file): existing_pdf = PdfFileReader(open(pdf_file, "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page
def render_element(root, element, canvas, styles): canvas.saveState() current_style = {} if len(styles): current_style.update(styles[-1]) for declaration in element.get("style", "").split(";"): if declaration == "": continue key, value = declaration.split(":") current_style[key] = value styles.append(current_style) if "stroke-width" in current_style: canvas.setLineWidth(float(current_style["stroke-width"])) if "stroke-dasharray" in current_style: canvas.setDash([ float(length) for length in current_style["stroke-dasharray"].split(",") ]) if current_style.get("visibility") != "hidden": if "transform" in element.attrib: for transformation in element.get("transform").split(")")[::1]: if transformation: transform, arguments = transformation.split("(") arguments = arguments.split(",") if transform.strip() == "translate": if len(arguments) == 2: canvas.translate(float(arguments[0]), float(arguments[1])) elif transform.strip() == "rotate": if len(arguments) == 1: canvas.rotate(float(arguments[0])) if len(arguments) == 3: canvas.translate(float(arguments[1]), float(arguments[2])) canvas.rotate(float(arguments[0])) canvas.translate(-float(arguments[1]), -float(arguments[2])) if element.tag == "svg": if "background-color" in current_style: set_fill_color( canvas, toyplot.color.css(current_style["background-color"])) canvas.rect( 0, 0, float(element.get("width")[:-2]), float(element.get("height")[:-2]), stroke=0, fill=1, ) for child in element: render_element(root, child, canvas, styles) elif element.tag == "g": if element.get("clip-path", None) is not None: clip_id = element.get("clip-path")[5:-1] clip_path = root.find(".//*[@id='%s']" % clip_id) for child in clip_path: if child.tag == "rect": x = float(child.get("x")) y = float(child.get("y")) width = float(child.get("width")) height = float(child.get("height")) path = canvas.beginPath() path.moveTo(x, y) path.lineTo(x + width, y) path.lineTo(x + width, y + height) path.lineTo(x, y + height) path.close() canvas.clipPath(path, stroke=0, fill=1) else: toyplot.log.error("Unhandled clip tag: %s", child.tag) # pragma: no cover for child in element: render_element(root, child, canvas, styles) elif element.tag == "clipPath": pass elif element.tag == "line": stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) canvas.setLineCap(get_line_cap(current_style)) canvas.line( float(element.get("x1", 0)), float(element.get("y1", 0)), float(element.get("x2", 0)), float(element.get("y2", 0)), ) elif element.tag == "path": stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) canvas.setLineCap(get_line_cap(current_style)) path = canvas.beginPath() commands = element.get("d").split() while len(commands): command = commands.pop(0) if command == "L": path.lineTo(float(commands.pop(0)), float(commands.pop(0))) elif command == "M": path.moveTo(float(commands.pop(0)), float(commands.pop(0))) canvas.drawPath(path) elif element.tag == "polygon": fill, fill_gradient = get_fill(root, current_style) if fill_gradient is not None: raise NotImplementedError( "Gradient <polygon> not implemented." ) # pragma: no cover if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) points = [ point.split(",") for point in element.get("points").split() ] path = canvas.beginPath() for point in points[:1]: path.moveTo(float(point[0]), float(point[1])) for point in points[1:]: path.lineTo(float(point[0]), float(point[1])) path.close() canvas.drawPath(path, stroke=stroke is not None, fill=fill is not None) elif element.tag == "rect": fill, fill_gradient = get_fill(root, current_style) if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) x = float(element.get("x", 0)) y = float(element.get("y", 0)) width = float(element.get("width")) height = float(element.get("height")) path = canvas.beginPath() path.moveTo(x, y) path.lineTo(x + width, y) path.lineTo(x + width, y + height) path.lineTo(x, y + height) path.close() if fill_gradient is not None: pdf_colors = [] pdf_offsets = [] for stop in fill_gradient: offset = float(stop.get("offset")) color = toyplot.color.css(stop.get("stop-color")) opacity = float(stop.get("stop-opacity")) pdf_colors.append( reportlab.lib.colors.Color(color["r"], color["g"], color["b"], color["a"] * opacity)) pdf_offsets.append(offset) canvas.saveState() canvas.clipPath(path, stroke=0, fill=1) canvas.setFillAlpha(1) canvas.linearGradient( float(fill_gradient.get("x1")), float(fill_gradient.get("y1")), float(fill_gradient.get("x2")), float(fill_gradient.get("y2")), pdf_colors, pdf_offsets, ) canvas.restoreState() canvas.drawPath(path, stroke=stroke is not None, fill=fill is not None) elif element.tag == "circle": fill, fill_gradient = get_fill(root, current_style) if fill_gradient is not None: raise NotImplementedError( "Gradient <circle> not implemented." ) # pragma: no cover if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) cx = float(element.get("cx", 0)) cy = float(element.get("cy", 0)) r = float(element.get("r")) canvas.circle(cx, cy, r, stroke=stroke is not None, fill=fill is not None) elif element.tag == "text": x = float(element.get("x", 0)) y = float(element.get("y", 0)) fill, fill_gradient = get_fill(element, current_style) stroke = get_stroke(current_style) font_family = get_font_family(current_style) font_size = toyplot.units.convert(current_style["font-size"], target="px") text = element.text canvas.saveState() canvas.setFont(font_family, font_size) if fill is not None: set_fill_color(canvas, fill) if stroke is not None: set_stroke_color(canvas, stroke) canvas.translate(x, y) canvas.scale(1, -1) canvas.drawString(0, 0, text) canvas.restoreState() elif element.tag == "image": # pylint: disable=redefined-variable-type import PIL.Image image = element.get("xlink:href") if not image.startswith("data:image/png;base64,"): raise ValueError( "Unsupported image type.") # pragma: no cover image = base64.standard_b64decode(image[22:]) image = io.BytesIO(image) image = PIL.Image.open(image) image = reportlab.lib.utils.ImageReader(image) x = float(element.get("x", 0)) y = float(element.get("y", 0)) width = float(element.get("width")) height = float(element.get("height")) canvas.saveState() path = canvas.beginPath() set_fill_color(canvas, toyplot.color.rgb(1, 1, 1)) canvas.rect(x, y, width, height, stroke=0, fill=1) canvas.translate(x, y + height) canvas.scale(1, -1) canvas.drawImage(image=image, x=0, y=0, width=width, height=height, mask=None) canvas.restoreState() elif element.tag in ["defs", "title"]: pass else: raise Exception("unhandled tag: %s" % element.tag) # pragma: no cover styles.pop() canvas.restoreState()
def render_element(root, element, canvas, styles, text_state=None): canvas.saveState() current_style = {} if len(styles): current_style.update(styles[-1]) for declaration in element.get("style", "").split(";"): if declaration == "": continue key, value = declaration.split(":") if key == "dominant-baseline" and value == "inherit": continue current_style[key] = value styles.append(current_style) if "stroke-width" in current_style: canvas.setLineWidth(float(current_style["stroke-width"])) if "stroke-dasharray" in current_style: canvas.setDash([ float(length) for length in current_style["stroke-dasharray"].split(",") ]) if current_style.get("visibility") != "hidden": if "transform" in element.attrib: for transformation in element.get("transform").split(")")[::1]: if transformation: type, arguments = transformation.split("(") arguments = arguments.split(",") if type.strip() == "translate": if len(arguments) == 2: canvas.translate(float(arguments[0]), float(arguments[1])) elif type.strip() == "rotate": if len(arguments) == 1: canvas.rotate(float(arguments[0])) if len(arguments) == 3: canvas.translate(float(arguments[1]), float(arguments[2])) canvas.rotate(float(arguments[0])) canvas.translate(-float(arguments[1]), -float(arguments[2])) if element.tag == "svg": if "background-color" in current_style: set_fill_color( canvas, toyplot.color.css(current_style["background-color"])) canvas.rect( 0, 0, float(element.get("width")[:-2]), float(element.get("height")[:-2]), stroke=0, fill=1, ) for child in element: render_element(root, child, canvas, styles) elif element.tag == "g": if element.get("clip-path", None) is not None: clip_id = element.get("clip-path")[5:-1] clip_path = root.find(".//*[@id='%s']" % clip_id) for child in clip_path: if child.tag == "rect": x = float(child.get("x")) y = float(child.get("y")) width = float(child.get("width")) height = float(child.get("height")) path = canvas.beginPath() path.moveTo(x, y) path.lineTo(x + width, y) path.lineTo(x + width, y + height) path.lineTo(x, y + height) path.close() canvas.clipPath(path, stroke=0, fill=1) else: toyplot.log.error("Unhandled clip tag: %s" % child.tag) # pragma: no cover for child in element: render_element(root, child, canvas, styles) elif element.tag == "clipPath": pass elif element.tag == "line": stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) canvas.line( float(element.get("x1")), float(element.get("y1")), float(element.get("x2")), float(element.get("y2")), ) elif element.tag == "path": stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) path = canvas.beginPath() commands = element.get("d").split() while len(commands): command = commands.pop(0) if command == "L": path.lineTo(float(commands.pop(0)), float(commands.pop(0))) elif command == "M": path.moveTo(float(commands.pop(0)), float(commands.pop(0))) canvas.drawPath(path) elif element.tag == "polygon": fill, fill_gradient = get_fill(root, current_style) if fill_gradient is not None: raise NotImplementedError( "Gradient <polygon> not implemented." ) # pragma: no cover if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) points = [ point.split(",") for point in element.get("points").split() ] path = canvas.beginPath() for point in points[:1]: path.moveTo(float(point[0]), float(point[1])) for point in points[1:]: path.lineTo(float(point[0]), float(point[1])) path.close() canvas.drawPath(path, stroke=stroke is not None, fill=fill is not None) elif element.tag == "rect": fill, fill_gradient = get_fill(root, current_style) if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) x = float(element.get("x")) y = float(element.get("y")) width = float(element.get("width")) height = float(element.get("height")) path = canvas.beginPath() path.moveTo(x, y) path.lineTo(x + width, y) path.lineTo(x + width, y + height) path.lineTo(x, y + height) path.close() if fill_gradient is not None: pdf_colors = [] pdf_offsets = [] for stop in fill_gradient: offset = float(stop.get("offset")) color = toyplot.color.css(stop.get("stop-color")) opacity = float(stop.get("stop-opacity")) pdf_colors.append( reportlab.lib.colors.Color(color["r"], color["g"], color["b"], color["a"])) pdf_offsets.append(offset) canvas.saveState() canvas.clipPath(path, stroke=0, fill=1) canvas.setFillAlpha(1) canvas.linearGradient( float(fill_gradient.get("x1")), float(fill_gradient.get("y1")), float(fill_gradient.get("x2")), float(fill_gradient.get("y2")), pdf_colors, pdf_offsets, ) canvas.restoreState() canvas.drawPath(path, stroke=stroke is not None, fill=fill is not None) elif element.tag == "circle": fill, fill_gradient = get_fill(root, current_style) if fill_gradient is not None: raise NotImplementedError( "Gradient <circle> not implemented." ) # pragma: no cover if fill is not None: set_fill_color(canvas, fill) stroke = get_stroke(current_style) if stroke is not None: set_stroke_color(canvas, stroke) cx = float(element.get("cx")) cy = float(element.get("cy")) r = float(element.get("r")) canvas.circle(cx, cy, r, stroke=stroke is not None, fill=fill is not None) elif element.tag == "text": text_state = {"x": 0, "y": 0, "chunks": [[]]} for child in element: render_element(root, child, canvas, styles, text_state) for chunk in text_state["chunks"]: width = sum([span[7] for span in chunk]) dx = 0 text_anchor = current_style.get("text-anchor", "start") if text_anchor == "middle": dx = -width * 0.5 elif text_anchor == "end": dx = -width for x, y, fill, stroke, font_family, font_size, text, width in chunk: canvas.saveState() canvas.setFont(font_family, font_size) if fill is not None: set_fill_color(canvas, fill) if stroke is not None: set_stroke_color(canvas, stroke) canvas.translate(x + dx, y) canvas.scale(1, -1) canvas.drawString(0, 0, text) canvas.restoreState() elif element.tag == "tspan": # if "font-weight" in current_style: # font_description.set_weight( # pango.WEIGHT_BOLD if current_style["font-weight"] == "bold" else pango.WEIGHT_NORMAL) font_family = get_font_family(current_style) font_size = toyplot.units.convert( current_style["font-size"].strip(), "px") string_width = reportlab.pdfbase.pdfmetrics.stringWidth( element.text, font_family, font_size) ascent, descent = reportlab.pdfbase.pdfmetrics.getAscentDescent( font_family, font_size) if "x" in element.attrib: text_state["x"] = float(element.get("x")) text_state["chunks"].append([]) if "dy" in element.attrib: text_state["y"] += float(element.get("dy")) x = text_state["x"] y = text_state["y"] alignment_baseline = current_style.get("alignment-baseline", "middle") if alignment_baseline == "hanging": y += ascent elif alignment_baseline == "central": y += ascent * 0.5 elif alignment_baseline == "middle": y += (ascent + descent) * 0.5 elif alignment_baseline == "alphabetic": pass else: raise ValueError("Unsupported alignment-baseline: %s" % alignment_baseline) # pragma: no cover baseline_shift = current_style.get("baseline-shift", "0").strip() baseline_shift = toyplot.units.convert(baseline_shift, "px", "px", ascent - descent) y -= baseline_shift fill, fill_gradient = get_fill(root, current_style) stroke = get_stroke(current_style) text_state["chunks"][-1].append( (x, y, fill, stroke, font_family, font_size, element.text, string_width)) text_state["x"] += string_width elif element.tag in ["defs", "title"]: pass else: raise Exception("unhandled tag: %s" % element.tag) # pragma: no cover styles.pop() canvas.restoreState()
def gerafolha(intmarg, extmarg, infmarg, supmarg): global numos canvas.setLineWidth(0.6 * mm) canvas.line(intmarg * mm, infmarg * mm, intmarg * mm, (297 - supmarg) * mm) # Desenhor da borda interna canvas.line(intmarg * mm, infmarg * mm, (210 - extmarg) * mm, infmarg * mm) # Desenhor da borda inferior canvas.line((210 - extmarg) * mm, infmarg * mm, (210 - extmarg) * mm, 287 * mm) # Desenhor da borda externa canvas.line((210 - extmarg) * mm, (297 - supmarg) * mm, intmarg * mm, (297 - supmarg) * mm) # Desenhor da borda superior canvas.line((210 - extmarg) * mm, 280 * mm, intmarg * mm, 280 * mm) # Linha inferir do cabeçalho for linha in range(1, 34): # Linhas para escrita altura = 280 - (8 * linha) canvas.setLineWidth(0.254 * mm) canvas.line(intmarg * mm, altura * mm, (210 - extmarg) * mm, altura * mm) if numos % 100 == 0: canvas.setFont('Garamond-Negrito', 18) else: canvas.setFont('Garamond-Italico', 18) canvas.drawCentredString((intmarg + 12.5) * mm, (altura + 2) * mm, str(numos)) numos += 1 canvas.setFont('Times-Regular', 18) canvas.drawCentredString((intmarg + 157.5) * mm, (altura + 2) * mm, "/ /") canvas.setLineWidth(0.254 * mm) canvas.setDash(1, 1) canvas.line((intmarg + 25) * mm, 16 * mm, (intmarg + 25) * mm, 287 * mm) # Borda direita Num. O.S. canvas.line((intmarg + 70) * mm, 16 * mm, (intmarg + 70) * mm, 287 * mm) # Borda direita Cliente canvas.line((intmarg + 115) * mm, 16 * mm, (intmarg + 110) * mm, 287 * mm) # Borda direita Motor canvas.line((intmarg + 145) * mm, 16 * mm, (intmarg + 145) * mm, 287 * mm) # Borda direita Montador canvas.line((intmarg + 170) * mm, 16 * mm, (intmarg + 170) * mm, 287 * mm) # Borda direita Data canvas.setDash(1, 0) canvas.setFont('Times-Regular', 18) canvas.drawCentredString((intmarg + 12.5) * mm, 281.5 * mm, "OS") canvas.drawCentredString((intmarg + 47.5) * mm, 281.5 * mm, "Cliente") canvas.drawCentredString((intmarg + 90) * mm, 281.5 * mm, "Motor") canvas.drawCentredString((intmarg + 127.5) * mm, 281.5 * mm, "Montador") canvas.drawCentredString((intmarg + 157.5) * mm, 281.5 * mm, "Data") canvas.drawCentredString((intmarg + 177.5) * mm, 281.5 * mm, "Ass.") canvas.setFont('Times-Regular', 12) canvas.drawCentredString((intmarg + 85) * mm, 10 * mm, "Página _____") # ----------- IMPRESSÃO DO CARIMBO DE TEMPO E NOME DE USUÁRIO ----------- canvas.setFont('Consola', 8) canvas.saveState() canvas.rotate(90) if intmarg > extmarg: canvas.drawString( infmarg * mm, -(intmarg - 5) * mm, str("{} - {}".format(time.time(), getpass.getuser()))) else: canvas.drawString( infmarg * mm, -(210 - extmarg + 5) * mm, str("{} - {}".format(time.time(), getpass.getuser()))) canvas.restoreState() canvas.showPage() # Adiciona uma nova página
def draw(self): canvas = self.canv canvas.rotate(-90) canvas.drawString(8, -1, self.text)