def run(): styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #for codeNames in code story.append(Paragraph('I2of5', styleN)) story.append(I2of5(1234, barWidth=inch * 0.02, checksum=0)) story.append(Paragraph('MSI', styleN)) story.append(MSI(1234)) story.append(Paragraph('Codabar', styleN)) story.append(Codabar("A012345B", barWidth=inch * 0.02)) story.append(Paragraph('Code 11', styleN)) story.append(Code11("01234545634563")) story.append(Paragraph('Code 39', styleN)) story.append(Standard39("A012345B%R")) story.append(Paragraph('Extended Code 39', styleN)) story.append(Extended39("A012345B}")) story.append(Paragraph('Code93', styleN)) story.append(Standard93("CODE 93")) story.append(Paragraph('Extended Code93', styleN)) story.append(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch)) story.append(Paragraph('Code 128', styleN)) c = Code128("AB-12345678") #, barWidth=0.005 * inch) #print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch) #print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch) story.append(c) story.append(Paragraph('USPS FIM', styleN)) story.append(FIM("A")) story.append(Paragraph('USPS POSTNET', styleN)) story.append(POSTNET('78247-1043')) story.append(Paragraph('USPS 4 State', styleN)) story.append(USPS_4State('01234567094987654321', '01234567891')) from reportlab.graphics.barcode import createBarcodeDrawing story.append(Paragraph('EAN13', styleN)) bcd = createBarcodeDrawing('EAN13', value='123456789012') story.append(bcd) story.append(Paragraph('EAN8', styleN)) bcd = createBarcodeDrawing('EAN8', value='1234567') story.append(bcd) story.append(Paragraph('UPCA', styleN)) bcd = createBarcodeDrawing('UPCA', value='03600029145') story.append(bcd) story.append(Paragraph('USPS_4State', styleN)) bcd = createBarcodeDrawing('USPS_4State', value='01234567094987654321', routing='01234567891') story.append(bcd) story.append(Paragraph('Label Size', styleN)) story.append(XBox((2.0 + 5.0 / 8.0) * inch, 1 * inch, '1x2-5/8"')) story.append(Paragraph('Label Size', styleN)) story.append(XBox((1.75) * inch, .5 * inch, '1/2x1-3/4"')) c = Canvas('out.pdf') f = Frame(inch, inch, 6 * inch, 9 * inch, showBoundary=1) f.addFromList(story, c) c.save() print('saved out.pdf')
def drawCard(index, item): p.saveState() p.translate(0, height / 3 * (2 - index % 3)) # retrieve record while making sure it's accessible to presentation owner record = Record.filter_one_by_access(presentation.owner, item.record.id) if record: image = get_image_for_record(record, presentation.owner, 800, 800, passwords) if image: p.drawImage(image, inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, preserveAspectRatio=True) f = Frame(width / 2 + inch / 2, inch / 2, width=width / 2 - inch, height = height / 3 - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) data = [] data.append(getParagraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber'])) values = item.get_fieldvalues(owner=request.user) for value in values: v = value.value if len(value.value) < 100 else value.value[:100] + '...' data.append(getParagraph('<b>%s:</b> %s' % (value.resolved_label, v), styles['Data'])) annotation = item.annotation if annotation: data.append(getParagraph('<b>%s:</b> %s' % ('Annotation', annotation), styles['Data'])) data = filter(None, data) f.addFromList(data, p) if data: p.setFont('Helvetica', 8) p.setFillColorRGB(0, 0, 0) p.drawRightString(width - inch / 2, inch / 2, '...') p.restoreState()
def prepare_first_page(canvas, document): p1 = Paragraph(presentation.title, styles['Heading']) p2 = Paragraph( presentation.owner.get_full_name(), styles['SubHeading']) avail_width = width - inch avail_height = height - inch w1, h1 = p1.wrap(avail_width, avail_height) w2, h2 = p2.wrap(avail_width, avail_height) f = Frame( inch / 2, inch / 2, width - inch, height - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0 ) f.addFromList([p1, p2], canvas) document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2 document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.line( width / 2, inch / 2, width / 2, height - inch - h1 - h2) canvas.restoreState()
def prepare_first_page(canvas, document): p1 = Paragraph(presentation.title, styles['Heading']) p2 = Paragraph(presentation.owner.get_full_name(), styles['SubHeading']) avail_width = width - inch avail_height = height - inch w1, h1 = p1.wrap(avail_width, avail_height) w2, h2 = p2.wrap(avail_width, avail_height) f = Frame(inch / 2, inch / 2, width - inch, height - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) f.addFromList([p1, p2], canvas) document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2 document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.line(width / 2, inch / 2, width / 2, height - inch - h1 - h2) canvas.restoreState()
def drawCard(index, item): p.saveState() p.translate(0, height / 3 * (2 - index % 3)) # retrieve record while making sure it's accessible to presentation owner record = Record.filter_one_by_access(presentation.owner, item.record.id) if record: image = get_image_for_record(record, presentation.owner, 800, 800, passwords) if image: p.drawImage(image, inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, preserveAspectRatio=True) f = Frame(width / 2 + inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) data = [] data.append(getParagraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber'])) values = item.get_fieldvalues(owner=request.user) for value in values: v = value.value if len(value.value) < 100 else value.value[:100] + '...' v = remove_rels_from_a_tags(v) data.append(getParagraph('<b>%s:</b> %s' % (value.resolved_label, v), styles['Data'])) annotation = item.annotation if annotation: data.append(getParagraph('<b>%s:</b> %s' % ('Annotation', annotation), styles['Data'])) data = filter(None, data) f.addFromList(data, p) if data: p.setFont('Helvetica', 8) p.setFillColorRGB(0, 0, 0) p.drawRightString(width - inch / 2, inch / 2, '...') p.restoreState()
def run(): styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #for codeNames in code story.append(Paragraph('I2of5', styleN)) story.append(I2of5(1234, barWidth = inch*0.02, checksum=0)) story.append(Paragraph('MSI', styleN)) story.append(MSI(1234)) story.append(Paragraph('Codabar', styleN)) story.append(Codabar("A012345B", barWidth = inch*0.02)) story.append(Paragraph('Code 11', styleN)) story.append(Code11("01234545634563")) story.append(Paragraph('Code 39', styleN)) story.append(Standard39("A012345B%R")) story.append(Paragraph('Extended Code 39', styleN)) story.append(Extended39("A012345B}")) story.append(Paragraph('Code93', styleN)) story.append(Standard93("CODE 93")) story.append(Paragraph('Extended Code93', styleN)) story.append(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch)) story.append(Paragraph('Code 128', styleN)) c=Code128("AB-12345678") #, barWidth=0.005 * inch) #print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch) #print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch) story.append(c) story.append(Paragraph('USPS FIM', styleN)) story.append(FIM("A")) story.append(Paragraph('USPS POSTNET', styleN)) story.append(POSTNET('78247-1043')) story.append(Paragraph('USPS 4 State', styleN)) story.append(USPS_4State('01234567094987654321','01234567891')) from reportlab.graphics.barcode import createBarcodeDrawing story.append(Paragraph('EAN13', styleN)) bcd = createBarcodeDrawing('EAN13', value='123456789012') story.append(bcd) story.append(Paragraph('EAN8', styleN)) bcd = createBarcodeDrawing('EAN8', value='1234567') story.append(bcd) story.append(Paragraph('UPCA', styleN)) bcd = createBarcodeDrawing('UPCA', value='03600029145') story.append(bcd) story.append(Paragraph('USPS_4State', styleN)) bcd = createBarcodeDrawing('USPS_4State', value='01234567094987654321',routing='01234567891') story.append(bcd) story.append(Paragraph('Label Size', styleN)) story.append(XBox((2.0 + 5.0/8.0)*inch, 1 * inch, '1x2-5/8"')) story.append(Paragraph('Label Size', styleN)) story.append(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"')) c = Canvas('out.pdf') f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story, c) c.save() print('saved out.pdf')
def draw_card(index, item): p.saveState() p.translate(0, height / 3 * (2 - index % 3)) # retrieve record while making sure it's accessible # to presentation owner record = Record.filter_one_by_access(presentation.owner, item.record.id) if record: image = get_image_for_record(record, self.user, 800, 800, passwords) if image: p.drawImage(image, inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, preserveAspectRatio=True) f = Frame(width / 2 + inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) data = [] data.append( get_paragraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber'])) values = get_metadata(item.get_fieldvalues(owner=request.user)) for value in values: v = _clean_for_render(value['value']) data.append( get_paragraph('<b>%s:</b> %s' % (value['label'], v), styles['Data'])) annotation = item.annotation if annotation: annotation = _clean_for_render(annotation) data.append( get_paragraph( '<b>%s:</b> %s' % ('Annotation', annotation), styles['Data'])) data = [_f for _f in data if _f] incomplete = False while data: f.addFromList(data, p) if data: data = data[1:] incomplete = True if incomplete: p.setFont('Helvetica', 8) p.setFillColorRGB(0, 0, 0) p.drawRightString(width - inch / 2, inch / 2, '...') p.restoreState()
def write(self, canvas): """Writes the frame to the given canvas. @param canvas: reportlab.pdfgen.canvas.Canvas object that represents the canvas that the container should write the frame to. @return: None """ self._check_canvas(canvas) self._check_start_point() frame = Frame(self._x, self._y, self._width, self._height, topPadding=0, bottomPadding=0) frame.addFromList(self._components, canvas)
def test6(self): """test of single/multi-frag text and shrinkSpace calculation""" pagesize = (200 + 20, 400) canv = Canvas(outputfile('test_platypus_breaking_lelegaifax.pdf'), pagesize=pagesize) f = Frame(10, 0, 200, 400, showBoundary=ShowBoundaryValue(dashArray=(1, 1)), leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0) style = ParagraphStyle( 'normal', fontName='Helvetica', fontSize=11.333628, spaceBefore=20, hyphenationLang='en-US', alignment=TA_JUSTIFY, spaceShrinkage=0.05, ) text1 = """My recent use case was the preparation""" text2 = """<span color='red'>My </span> recent use case was the preparation""" ix0 = len(canv._code) f.addFromList([ Paragraph(text1, style), Paragraph(text2, style), ], canv) self.assertEqual( canv._code[ix0:], [ 'q', '0 0 0 RG', '.1 w', '[1 1] 0 d', 'n 10 0 200 400 re S', 'Q', 'q', '1 0 0 1 10 388 cm', 'q', '0 0 0 rg', 'BT 1 0 0 1 0 .666372 Tm /F1 11.33363 Tf 12 TL -0.157537 Tw' ' (My recent use case was the preparation) Tj T* 0 Tw ET', 'Q', 'Q', 'q', '1 0 0 1 10 356 cm', 'q', 'BT 1 0 0 1 0 .666372 Tm -0.157537 Tw 12 TL /F1 11.33363 Tf 1 0 0 rg' ' (My ) Tj 0 0 0 rg (recent use case was the preparation) Tj T* 0 Tw ET', 'Q', 'Q' ], 'Lele Gaifax bug example did not produce the right code', ) canv.showPage() canv.save()
def prepare_first_page(canvas, document): p1 = Paragraph(presentation.title, styles['Heading']) p2 = Paragraph(presentation.owner.get_full_name(), styles['SubHeading']) avail_width = width - inch # TODO: determine if the complaint about height being undeclared is just pycharm or if its a problem # if it is possibly a problem "it's better to be explicit" so refactor avail_height = height - inch w1, h1 = p1.wrap(avail_width, avail_height) w2, h2 = p2.wrap(avail_width, avail_height) f = Frame(inch / 2, inch / 2, width - inch, height - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) f.addFromList([p1, p2], canvas) document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2 document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.line(width / 2, inch / 2, width / 2, height - inch - h1 - h2) canvas.restoreState()
def HeaderFooter(canvas, doc): canvas.saveState() styleN = PS('nomal', fontName='Times-Roman', leading=9, fontSize=9) P = Paragraph("This is a multi-line footer or header", styleN) w, h = P.wrap(doc.width, doc.bottomMargin) #print doc.width, doc.bottomMargin #print w, h #print dir(doc) #print dir(canvas) global pageNum if doc.page < pageNum: global ChapterName ChapterName = 'Table of contents' #print doc.page #print ChapterName pageNum = doc.page if doc.page == 1: footerMsg = [] footerMsg.append(Paragraph("Lei Yang", styleN)) footerMsg.append(Paragraph("Wei Gao", styleN)) footerMsg.append(Paragraph("XiangYu Dong", styleN)) footerMsg.append(Paragraph("Liang Chi", styleN)) footerMsg.append(Paragraph("Beijing ChaoYang, China", styleN)) canvas.line(2.5*cm, h+50, w+2.5*cm, h+50) f = Frame(70, 2, 16*cm, 2.1*cm, showBoundary=0) f.addFromList(footerMsg,canvas) else: P = Paragraph("User Guide", styleN) w, h = P.wrap(doc.width, doc.bottomMargin) P.drawOn(canvas, doc.leftMargin, h+789) P = Paragraph(ChapterName, PS('nomal', fontName='Times-Roman', fontSize=9, alignment = TA_RIGHT, leading=9)) w, h = P.wrap(doc.width, doc.bottomMargin) P.drawOn(canvas, doc.rightMargin, h+789) P = Paragraph("Page %d" % doc.page, PS('nomal', fontName='Times-Roman', fontSize=9, alignment = 1)) w, h = P.wrap(doc.width, doc.bottomMargin) P.drawOn(canvas, doc.leftMargin, h) canvas.line(2.5*cm, h+780, w+2.5*cm, h+780) canvas.restoreState()
def drawHeader(self): self.drawLogo() styles = getSampleStyleSheet() sN = styles['Normal'] sH = styles['Heading1'] sH.fontName = "OldEngMT" sH.textColor = red sH.leading = 18 sH.fontSize = 16 sN.fontSize = 9 sN.leading = 10 sN.alignment = sH.alignment = TA_CENTER sN.spaceBefore = sH.spaceBefore = 0 sN.spaceAfter = sH.spaceAfter = 0 story = [] story.append(Paragraph("Holy Child Colleges of Butuan - Hospital", sH)) story.append(Paragraph("<b>(JP Esteves Clinical Laboratory)</b>", sN)) story.append( Paragraph("2nd St., Guingona Subd., " + "Butuan City, Philippines", sN)) story.append(Paragraph("Tel. No.: +63 (85) 342-5186", sN)) story.append(Paragraph("Telefax No.: +63 (95) 342-397/225-6872", sN)) story.append(Paragraph("email: [email protected]", sN)) w, h = self.pagesize f = Frame(0, h - self.topMargin, w, self.topMargin, showBoundary=False) f.addFromList(story, self.canv) self.canv.setStrokeColor(red) self.canv.setLineWidth(3) self.canv.line( 0.15 * cm, h - self.topMargin, w - 0.15 * cm, h - self.topMargin, )
def drawHeader(self): self.drawLogo() styles = getSampleStyleSheet() sN = styles['Normal'] sH = styles['Heading1'] sH.fontName = "OldEngMT" sH.textColor = red sH.leading = 18 sH.fontSize = 16 sN.fontSize = 9 sN.leading = 10 sN.alignment = sH.alignment = TA_CENTER sN.spaceBefore = sH.spaceBefore = 0 sN.spaceAfter = sH.spaceAfter = 0 story = [] story.append(Paragraph("Holy Child Colleges of Butuan - Hospital", sH)) story.append(Paragraph("<b>(JP Esteves Clinical Laboratory)</b>", sN)) story.append(Paragraph("2nd St., Guingona Subd., " + "Butuan City, Philippines", sN)) story.append(Paragraph("Tel. No.: +63 (85) 342-5186", sN)) story.append(Paragraph("Telefax No.: +63 (95) 342-397/225-6872", sN)) story.append(Paragraph("email: [email protected]", sN)) w, h = self.pagesize f = Frame(0, h-self.topMargin, w, self.topMargin, showBoundary=False) f.addFromList(story, self.canv) self.canv.setStrokeColor(red) self.canv.setLineWidth(3) self.canv.line(0.15*cm, h-self.topMargin, w-0.15*cm, h-self.topMargin, )
class BaseInvoiceTemplate(PageTemplate): width = 210 * mm height = 297 * mm def __init__(self, name=None, rcptaddr=[], senderaddr=[], kind='purchase', phone=None, email=None, url=None, seat=None, orgnum=None, vatnum=None, fskatt=None, date=None, ocr='', expiryDate=None, conditions=None, latefee=None, buyerref='', annotation='', pgnum=None, total=0, qrcode=None, styles={}, showBoundary=0, frames=[]): self.kind = kind self.date = date or time.time() self.ocr = ocr self.expiryDate = expiryDate self.conditions = conditions self.latefee = latefee self.buyerref = buyerref self.annotation = annotation self.pgnum = pgnum self.total = total self.qrcode = qrcode self.showBoundary = showBoundary self.styles = styles self.smallstyle = smallstyle = ParagraphStyle('Small', fontName='Helvetica', fontSize=8, leading=9) self.detailsFooterFrame = Frame(75 * mm, 12 * mm, 55 * mm, 20 * mm, id='phonefooter', leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=showBoundary) self.detailstext = s = [] if phone: s.append(Paragraph(_(u'Phone: %s') % py3txt(phone), smallstyle)) if email: s.append(Paragraph(_(u'Email: %s') % py3txt(email), smallstyle)) if url: s.append(Paragraph(_(u'Web: %s') % py3txt(url), smallstyle)) if seat: s.append( Paragraph( _(u'Registered office: %s') % py3txt(seat), smallstyle)) self.bankFooterFrame = Frame(140 * mm, 12 * mm, 55 * mm, 20 * mm, id='bankfooter', leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=showBoundary) self.banktext = s = [] if pgnum: s.append( Paragraph( _('Pg: %s') % py3txt(formatters.pgnum(pgnum)), smallstyle)) s.append(Paragraph(_('Org no: %s') % py3txt(orgnum), smallstyle)) if vatnum: s.append(Paragraph(_('VAT no: %s') % py3txt(vatnum), smallstyle)) if fskatt: s.append(Paragraph('Innehar F-skattsedel', smallstyle)) PageTemplate.__init__(self, name, frames) @property def kind_text(self): if self.kind == 'purchase': return _(u'Order') else: return _(u'Invoice') @property def date_text(self): if self.kind == 'purchase': return _(u'Order date') else: return _(u'Invoice date') @property def ocr_text(self): if self.kind == 'purchase': return _(u'Order number') else: return _(u'Invoice number') def beforeDrawPage(self, canvas, doc): self.senderFrame._reset() self.senderFrame.addFromList(self.sendertext[:], canvas) self.senderFooterFrame._reset() self.senderFooterFrame.addFromList(self.sendertext[:], canvas) self.detailsFooterFrame._reset() self.detailsFooterFrame.addFromList(self.detailstext, canvas) self.bankFooterFrame._reset() self.bankFooterFrame.addFromList(self.banktext, canvas) with save_state(canvas): p = canvas.beginPath() p.moveTo(15 * mm, 35 * mm) p.lineTo(self.width - 15 * mm, 35 * mm) canvas.drawPath(p) to = canvas.beginText() to.setTextOrigin(118 * mm, self.height - 15 * mm) to.setFont('Helvetica-Bold', 24) to.textOut(self.kind_text) to.moveCursor(50 * mm, 0) to.setFont('Helvetica', 10) to.textOut(_(u'page %d') % doc.page) to.setTextOrigin(118 * mm, self.height - 21 * mm) to.textOut(self.date_text) to.moveCursor(50 * mm, 0) to.textLine(formatters.date(self.date)) to.moveCursor(-50 * mm, 0) to.textOut(self.ocr_text) to.moveCursor(50 * mm, 0) to.textLine(self.ocr) to.moveCursor(-50 * mm, 0) if self.expiryDate: to.textOut(_(u'Due date')) to.moveCursor(50 * mm, 0) to.textLine(formatters.date(self.expiryDate)) to.moveCursor(-50 * mm, 0) canvas.drawText(to)
def beforePage(self): self.context.current_page += 1 if self.context.has_header(): # HEADER header = self.context.get_header() self.canv.saveState() # calculate height if self.platypus_header_calculate is False: element = header[0] height = element.wrap(self.width_available, self.pagesize[1])[1] height += self.frame_attr['topPadding'] height += self.frame_attr['bottomPadding'] self.platypus_header_height = height height = self.platypus_header_height # calculate coordinates x = self.leftMargin y = self.pagesize[1] - height # resize margin if the frame is too big if self.platypus_header_calculate is False: if self.topMargin < height: self.platypus_header_calculate = True self.topMargin = height # calculate self.width and self.height self._calc() # reset the main frame with new margin self.main_frame_attr['x1'] = self.leftMargin self.main_frame_attr['y1'] = self.bottomMargin self.main_frame_attr['width'] = self.width self.main_frame_attr['height'] = self.height self.main_frame.__init__(**self.main_frame_attr) else: # frame is centered in top margin y -= (self.topMargin - height) / 2 else: # frame is centered in top margin y -= (self.topMargin - height) / 2 # create a frame which will contain all platypus objects defined # in the footer fh = Frame(x, y, self.width_available, height, **self.frame_attr) fh.addFromList(self.context.get_header_copy(), self.canv) self.canv.restoreState() if self.context.has_footer(): # FOOTER footer = self.context.get_footer() self.canv.saveState() # calculate height element = footer[0] height = element.wrap(self.width_available, self.pagesize[1])[1] height += self.frame_attr['topPadding'] height += self.frame_attr['bottomPadding'] # calculate coordinates x = self.leftMargin y = 0 # resize margin if the frame is too big if self.bottomMargin < height: self.bottomMargin = height # calculate self.width and self.height self._calc() # reset the main frame with new margin self.main_frame_attr['x1'] = self.leftMargin self.main_frame_attr['y1'] = self.bottomMargin self.main_frame_attr['width'] = self.width self.main_frame_attr['height'] = self.height self.main_frame.__init__(**self.main_frame_attr) else: # frame is centered in bottom margin y = (self.bottomMargin - height) / 2 # create a frame which will contain all platypus objects defined # in the footer ff = Frame(x, y, self.width_available, height, **self.frame_attr) ff.addFromList(self.context.get_footer_copy(), self.canv) self.canv.restoreState()
class Div(Flowable): def __init__(self, story, height=None, width=None, pos_x=None, pos_y=None, frame_attrs=freeze({}), attributes=freeze({}), pto_trailer=None, pto_header=None): Flowable.__init__(self) # get on story self.div_story = story # set frame style self.frame_attrs = {'leftPadding': 0, 'bottomPadding': 0, 'rightPadding': 0, 'topPadding': 0, 'showBoundary': 0} # PTO initialisation self.pto_trailer = pto_trailer self.pto_header = pto_header if frame_attrs is not None: self.frame_attrs.update(frame_attrs) for margin in ('topMargin', 'bottomMargin', 'leftMargin', 'rightMargin'): if margin in self.frame_attrs: del self.frame_attrs[margin] border = self.frame_attrs['showBoundary'] if isinstance(border, ShowBoundaryValue): border = border.width if border: for padding_attr in FRAME_PADDINGS_KEYS: self.frame_attrs[padding_attr] += border self.frame_width = width # Overflow # TODO to improve self.keep_in_frame = None style = attribute_style_to_dict(attributes.get((None, 'style'), '')) self.overflow = style.get('overflow-y', None) if self.overflow == 'hidden': self.overflow = 'truncate' else: self.overflow = None def draw(self): # set position for the frame self.pos_x, self.pos_y = self._get_current_position(self.canv) # XXX This is false, height=drawHeigh and drawHeight should take into # account the frame padding height = (self.drawHeight + self.frame_attrs['leftPadding'] + self.frame_attrs['rightPadding']) width = (self.drawWidth + self.frame_attrs['topPadding'] + self.frame_attrs['bottomPadding']) self.frame = Frame(self.pos_x, self.pos_y, width, height, **self.frame_attrs) if self.overflow: # Hack, We lie by setting the new created frame as default frame # of the doc template # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" _doctemplate = self.canv._doctemplate # save state current_frame = getattr(_doctemplate, 'frame', None) _doctemplate.frame = self.frame # Check if PTO is defined if self.pto_trailer or self.pto_header: ptocontainer = PTOContainer(self.div_story[:], self.pto_trailer, self.pto_header) ptocontainer.canv = self.canv pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight) # XXX Round the height to avoid problems with decimal if int(pto_size[1]) > int(self.drawHeight): pto_story = ptocontainer.split(self.drawWidth, self.drawHeight) self.frame.addFromList(pto_story, self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) # restore state if current_frame: _doctemplate.frame = current_frame else: self.frame.addFromList(self.div_story[:], self.canv) def wrap(self, availWidth, availHeight): canv = self.canv if self.overflow: if self.keep_in_frame is None: # FIXME if the availHeight is very small # We consider that there is no enough space # and we calculate the real size of the flowables if availHeight <= 0: width, height = self._get_real_size(availWidth) else: width, height = availWidth, availHeight # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height(availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) self.keep_in_frame = KeepInFrame(width, height, self.div_story[:], mode=self.overflow) else: width, height = availWidth, availHeight # FIXME Usefull ? # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height(availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) # Set the canva self.keep_in_frame.canv = canv # Hack, We remove the attribute _doctemplate of the canv # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" if hasattr(canv, '_doctemplate'): _doctemplate = canv._doctemplate # Remove _doctemplate canv._doctemplate = None w, h = self.keep_in_frame.wrap(width, height) if hasattr(canv, '_doctemplate'): # Restore _doctemplate canv._doctemplate = _doctemplate self.drawWidth, self.drawHeight = w, h else: width, height = self._get_real_size(availWidth) self.drawWidth, self.drawHeight = width, height return self.drawWidth, self.drawHeight def getSpaceBefore(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceBefore() # XXX default value return 0 def getSpaceAfter(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceAfter() # XXX default value return 0 def _get_real_size(self, availWidth, availHeight=10000000): """By default we use a fake height to calculate the real height of the flowables""" self.drawWidth = self.width or availWidth self.drawWidth -= self.frame_attrs['leftPadding'] self.drawWidth -= self.frame_attrs['rightPadding'] self.drawHeight = 0 at_top = True for element in self.div_story[:]: if at_top: at_top = False else: self.drawHeight += element.getSpaceBefore() flowHeight = element.wrap(availWidth, availHeight-self.drawHeight)[1] self.drawHeight += flowHeight self.drawHeight += element.getSpaceAfter() self.drawHeight += self.frame_attrs['topPadding'] self.drawHeight += self.frame_attrs['bottomPadding'] return (self.drawWidth, self.drawHeight) def _align_frame(self, available_width, hAlign): if hAlign == 'CENTER': self.pox_x = (available_width - self.frame_width) / 2 + self.pos_x elif hAlign == 'RIGHT': self.pos_x = available_width - self.frame_width + self.pox_x def _get_current_position(self, canv): return (canv._x, canv._y) def _get_current_absolute_position(self, canv): return canv.absolutePosition(canv._x, canv._y) def _get_main_frame_height(self, default, ratio=0.9): if self.canv is None: return default value = self.canv._doctemplate.main_frame_attr.get('height', default) return value * ratio
def build_pdf(self, response): cleaned_data = self.filterset.form.cleaned_data impresso = cleaned_data['impresso'] fs = int(impresso.fontsize) if cleaned_data['fontsize']: fs = int(cleaned_data['fontsize']) stylesheet = StyleSheet1() stylesheet.add( ParagraphStyle(name='pronome_style', fontName="Helvetica", fontSize=fs * 0.8, leading=fs)) stylesheet.add( ParagraphStyle(name='nome_style', fontName="Helvetica-Bold", fontSize=fs, leading=fs * 1.3)) stylesheet.add( ParagraphStyle(name='endereco_style', fontName="Helvetica", fontSize=fs * 0.9, leading=fs)) pagesize = (float(impresso.largura_pagina) * cm, float(impresso.altura_pagina) * cm) ms = pagesize[1] - float(impresso.margem_superior) * cm me = float(impresso.margem_esquerda) * cm ae = float(impresso.alturaetiqueta) * cm le = float(impresso.larguraetiqueta) * cm el = float(impresso.entre_linhas) * cm ec = float(impresso.entre_colunas) * cm col = float(impresso.colunasfolha) row = float(impresso.linhasfolha) cr = int(col * row) p = canvas.Canvas(response, pagesize=pagesize) if impresso.rotate: p.translate(pagesize[1], 0) p.rotate(90) i = -1 for contato in self.object_list.all(): i += 1 if i != 0 and i % cr == 0: p.showPage() if impresso.rotate: p.translate(pagesize[1], 0) p.rotate(90) q = floor(i / col) % row r = i % int(col) l = me + r * ec + r * le b = ms - (q + 1) * ae - q * el f = Frame(l, b, le, ae, leftPadding=fs / 3, bottomPadding=fs / 3, topPadding=fs / 3, rightPadding=fs / 3, showBoundary=0) # f.drawBoundary(p) f.addFromList(self.createParagraphs(contato, stylesheet), p) p.showPage() p.save()
def exportMonthlyReport(self, file, month, year): """Outputs the monthly report to the specified file location Parameters: self: the class instance file: str - file location and name ending in .pdf month: str - required month year: int - required year """ # For conversion of month to three letter abbreviation months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] # Creating a title title = Label() title.setOrigin(300, 20) title.boxAnchor = 'ne' title.dx = 0 title.dy = -5 title.fontSize = 30 title.setText("Monthly Report") # Adding title to a drawing draw_title = Drawing(0, 40) draw_title.add(title) # Creating a subtitle subtitle = Label() subtitle.setOrigin(320, 20) subtitle.boxAnchor = 'ne' subtitle.dx = 0 subtitle.dy = -10 subtitle.fontSize = 14 # Converts month to three letter abbreviation str_month = months[int(month) - 1] # Setting the subtitle's text subtitle.setText("Australia Zoo Wildlife Hospital, " + str_month + " " + str(year)) # Adding subtitle to a drawing draw_subtitle = Drawing(0, 30) draw_subtitle.add(subtitle) # Creating a label for the first chart label_lga = Label() label_lga.setOrigin(180, 20) label_lga.boxAnchor = 'ne' label_lga.dx = 0 label_lga.dy = -20 label_lga.setText("Local Government Area Totals") # Adding label to a drawing draw_label_lga = Drawing(0, 40) draw_label_lga.add(label_lga) # Creating drawing for the lga chart draw_lga = Drawing(0, 270) draw_lga.add(self.getSpecificBarChart("LGA", month, year)) # Creating a label for the second chart label_taxons = Label() label_taxons.setOrigin(180, 20) label_taxons.boxAnchor = 'ne' label_taxons.dx = 0 label_taxons.dy = -20 label_taxons.setText("Taxon Grouping Totals") # Adding label to a drawing draw_label_taxons = Drawing(0, 40) draw_label_taxons.add(label_taxons) # Creating drawing for the taxons chart draw_taxons = Drawing(0, 270) draw_taxons.add(self.getSpecificBarChart("Taxons", month, year)) # List of drawings in order of how to place them in the canvas drawlist = [ draw_title, draw_subtitle, draw_label_lga, draw_lga, draw_label_taxons, draw_taxons ] # Creating a canvas (pdf file) and saving it to a location canvas = Canvas(file) # Creating a frame to add flowables (drawings) to frame = Frame(inch, 0, 15.92 * cm, 29.7 * cm) # Adding flowables frame.addFromList(drawlist, canvas) # Saving the pdf canvas.save()
class Div(Flowable): def __init__(self, story, height=None, width=None, pos_x=None, pos_y=None, frame_attrs=freeze({}), attributes=freeze({}), pto_trailer=None, pto_header=None): Flowable.__init__(self) # get on story self.div_story = story # set frame style self.frame_attrs = { 'leftPadding': 0, 'bottomPadding': 0, 'rightPadding': 0, 'topPadding': 0, 'showBoundary': 0 } # PTO initialisation self.pto_trailer = pto_trailer self.pto_header = pto_header if frame_attrs is not None: self.frame_attrs.update(frame_attrs) for margin in ('topMargin', 'bottomMargin', 'leftMargin', 'rightMargin'): if margin in self.frame_attrs: del self.frame_attrs[margin] border = self.frame_attrs['showBoundary'] if isinstance(border, ShowBoundaryValue): border = border.width if border: for padding_attr in FRAME_PADDINGS_KEYS: self.frame_attrs[padding_attr] += border self.frame_width = width # Overflow # TODO to improve self.keep_in_frame = None style = attribute_style_to_dict(attributes.get((None, 'style'), '')) self.overflow = style.get('overflow-y', None) if self.overflow == 'hidden': self.overflow = 'truncate' else: self.overflow = None def draw(self): # set position for the frame self.pos_x, self.pos_y = self._get_current_position(self.canv) # XXX This is false, height=drawHeigh and drawHeight should take into # account the frame padding height = (self.drawHeight + self.frame_attrs['leftPadding'] + self.frame_attrs['rightPadding']) width = (self.drawWidth + self.frame_attrs['topPadding'] + self.frame_attrs['bottomPadding']) self.frame = Frame(self.pos_x, self.pos_y, width, height, **self.frame_attrs) if self.overflow: # Hack, We lie by setting the new created frame as default frame # of the doc template # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" _doctemplate = self.canv._doctemplate # save state current_frame = getattr(_doctemplate, 'frame', None) _doctemplate.frame = self.frame # Check if PTO is defined if self.pto_trailer or self.pto_header: ptocontainer = PTOContainer(self.div_story[:], self.pto_trailer, self.pto_header) ptocontainer.canv = self.canv pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight) # XXX Round the height to avoid problems with decimal if int(pto_size[1]) > int(self.drawHeight): pto_story = ptocontainer.split(self.drawWidth, self.drawHeight) self.frame.addFromList(pto_story, self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) # restore state if current_frame: _doctemplate.frame = current_frame else: self.frame.addFromList(self.div_story[:], self.canv) def wrap(self, availWidth, availHeight): canv = self.canv if self.overflow: if self.keep_in_frame is None: # FIXME if the availHeight is very small # We consider that there is no enough space # and we calculate the real size of the flowables if availHeight <= 0: width, height = self._get_real_size(availWidth) else: width, height = availWidth, availHeight # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height( availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) self.keep_in_frame = KeepInFrame(width, height, self.div_story[:], mode=self.overflow) else: width, height = availWidth, availHeight # FIXME Usefull ? # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height( availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) # Set the canva self.keep_in_frame.canv = canv # Hack, We remove the attribute _doctemplate of the canv # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" if hasattr(canv, '_doctemplate'): _doctemplate = canv._doctemplate # Remove _doctemplate canv._doctemplate = None w, h = self.keep_in_frame.wrap(width, height) if hasattr(canv, '_doctemplate'): # Restore _doctemplate canv._doctemplate = _doctemplate self.drawWidth, self.drawHeight = w, h else: width, height = self._get_real_size(availWidth) self.drawWidth, self.drawHeight = width, height return self.drawWidth, self.drawHeight def getSpaceBefore(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceBefore() # XXX default value return 0 def getSpaceAfter(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceAfter() # XXX default value return 0 def _get_real_size(self, availWidth, availHeight=10000000): """By default we use a fake height to calculate the real height of the flowables""" self.drawWidth = self.width or availWidth self.drawWidth -= self.frame_attrs['leftPadding'] self.drawWidth -= self.frame_attrs['rightPadding'] self.drawHeight = 0 at_top = True for element in self.div_story[:]: if at_top: at_top = False else: self.drawHeight += element.getSpaceBefore() flowHeight = element.wrap(availWidth, availHeight - self.drawHeight)[1] self.drawHeight += flowHeight self.drawHeight += element.getSpaceAfter() self.drawHeight += self.frame_attrs['topPadding'] self.drawHeight += self.frame_attrs['bottomPadding'] return (self.drawWidth, self.drawHeight) def _align_frame(self, available_width, hAlign): if hAlign == 'CENTER': self.pox_x = (available_width - self.frame_width) / 2 + self.pos_x elif hAlign == 'RIGHT': self.pos_x = available_width - self.frame_width + self.pox_x def _get_current_position(self, canv): return (canv._x, canv._y) def _get_current_absolute_position(self, canv): return canv.absolutePosition(canv._x, canv._y) def _get_main_frame_height(self, default, ratio=0.9): if self.canv is None: return default value = self.canv._doctemplate.main_frame_attr.get('height', default) return value * ratio
def beforePage(self): self.context.current_page += 1 if self.context.has_header(): # HEADER header = self.context.get_header() self.canv.saveState() # calculate height if self.platypus_header_calculate is False: element = header[0] height = element.wrap(self.width_available, self.pagesize[1])[1] height += self.frame_attr['topPadding'] height += self.frame_attr['bottomPadding'] self.platypus_header_height = height height = self.platypus_header_height # calculate coordinates x = self.leftMargin y = self.pagesize[1] - height # resize margin if the frame is too big if self.platypus_header_calculate is False: if self.topMargin < height: self.platypus_header_calculate = True self.topMargin = height # calculate self.width and self.height self._calc() # reset the main frame with new margin self.main_frame_attr['x1'] = self.leftMargin self.main_frame_attr['y1'] = self.bottomMargin self.main_frame_attr['width'] = self.width self.main_frame_attr['height'] = self.height self.main_frame.__init__(**self.main_frame_attr) else: # frame is centered in top margin y -= (self.topMargin - height) / 2 else: # frame is centered in top margin y -= (self.topMargin - height) / 2 # create a frame which will contain all platypus objects defined # in the footer fh = Frame(x, y, self.width_available, height, **self.frame_attr) fh.addFromList(self.context.get_header_copy(), self.canv) self.canv.restoreState() if self.context.has_footer(): # FOOTER footer = self.context.get_footer() self.canv.saveState() # calculate height element = footer[0] height = element.wrap(self.width_available, self.pagesize[1])[1] height += self.frame_attr['topPadding'] height += self.frame_attr['bottomPadding'] # calculate coordinates x = self.leftMargin y = 0 # resize margin if the frame is too big if self.bottomMargin < height: self.bottomMargin = height # calculate self.width and self.height self._calc() # reset the main frame with new margin self.main_frame_attr['x1'] = self.leftMargin self.main_frame_attr['y1'] = self.bottomMargin self.main_frame_attr['width'] = self.width self.main_frame_attr['height'] = self.height self.main_frame.__init__(**self.main_frame_attr) else: # frame is centered in bottom margin y = (self.bottomMargin - height) / 2 # create a frame which will contain all platypus objects defined # in the footer ff = Frame(x, y, self.width_available, height, **self.frame_attr) ff.addFromList(self.context.get_footer_copy(), self.canv) self.canv.restoreState()
def beforeDrawPage(self, canvas, doc): BaseInvoiceTemplate.beforeDrawPage(self, canvas, doc) self.rcptFrame.addFromList(self.rcpttext, canvas) with save_state(canvas): p = canvas.beginPath() to = canvas.beginText() to.setTextOrigin(20 * mm, self.height - 44 * mm) to.setFont('Helvetica', 8) to.textOut(_(u'Your reference')) to.setFont('Helvetica', 10) to.textOut(' ') to.textLine(self.buyerref) to.setFont('Helvetica', 8) to.textLine(_(u'Your notes')) paragraphs = [ Paragraph(line, self.styles['Normal']) for line in self.annotation ] self.annotationframe.addFromList(paragraphs, canvas) canvas.drawText(to) if self.pgnum and self.total != 0: ypos = self.height - 75 * mm - 5 to = canvas.beginText() to.setTextOrigin(20 * mm, ypos) to.setFont('Helvetica', 10) to.textLine('Betalas till') to.setFont('Helvetica-Bold', 12) to.textOut('Pg ' + formatters.pgnum(self.pgnum)) to.setTextOrigin(55 * mm, ypos) to.setFont('Helvetica', 10) to.textLine('OCR / referens') to.setFont('Helvetica-Bold', 12) to.textOut(self.ocr) to.setTextOrigin(85 * mm, ypos) to.setFont('Helvetica', 10) to.textLine('Att betala') to.setFont('Helvetica-Bold', 12) to.textLine(formatters.money(self.total, True)) ypos = to.getY() - 5 if self.expiryDate: to.setTextOrigin(20 * mm, ypos) to.setFont('Helvetica', 10) to.textLine(u'Förfallodatum') to.setFont('Helvetica-Bold', 12) to.textLine(formatters.date(self.expiryDate)) latestyle = ParagraphStyle('Late', fontName='Helvetica', fontSize=8, leading=9) lateframe = Frame(45 * mm, ypos - 15, 65 * mm, 22, id='latefee', leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=self.showBoundary) lateframe.addFromList([Paragraph(self.latefee, latestyle)], canvas) canvas.drawText(to) canvas.roundRect(17 * mm, ypos - 21, 100 * mm + 68, 68, 6) # Need to set ECI to UTF-8 # seee https://github.com/zxing/zxing/blob/3de3374dd25739bde952c788c1064cb17bc11ff8/core/src/main/java/com/google/zxing/qrcode/decoder/Mode.java # etc, update qrcode encoder... qd = Drawing() # No border, deal with quiet zone manually data = [QRECI(26), QR8bitByte(self.qrcode)] q = qr.QrCodeWidget(data, barLevel='L', barBorder=4.0, barWidth=68.0, barHeight=68.0) qd.add(q) renderPDF.draw(qd, canvas, 117 * mm, ypos - 21) qrstyle = ParagraphStyle('QR', fontName='Helvetica', fontSize=10, leading=12) qrinfoframe = Frame(145 * mm, ypos - 21, self.width - 160 * mm, 68, id='qrinfo', topPadding=0, leftPadding=0, bottomPadding=0, rightPadding=0, showBoundary=self.showBoundary) qrinfoframe.addFromList([ Paragraph( u'Om du betalar med bankapp kan du skanna QR-koden ' u'bredvid eller OCR-raden nedan. ' u'Läs mer om QR-koden på http://usingqr.se', qrstyle) ], canvas) # http://www.nordea.se/sitemod/upload/root/content/nordea_se/foretag/programleverantorer/filer/ocr_totalin.pdf to = canvas.beginText() to.setTextOrigin(10 * mm, self.height - 105 * mm) to.setFont('OCRB', 10) # 7777777777666666666655555555554444444444333333333322222222221111111111000000000 # 9876543210987654321098765432109876543210987654321098765432109876543210987654321 # '# 123456789012 #12345678 50 9 > 12345678 #14# ' # # ooooooooooooooooooooooooo #kkkkkkkk öö c > PpppppppP#tt# ocrformat = '# {ocr:>25} #{totalkr:>8} {totaldec:<02} {totalcheck:1} > {pgnum:>23} #14# ' totalkr = str(int(self.total)) # integer part of Decimal totaldec = str(int(self.total % 1 * 100)) # fraction part of Decimal totalcheck = luhn.luhn_checksum( str(self.total).replace('.', '') + '0') ocrkeys = { 'ocr': self.ocr, 'totalkr': totalkr, 'totaldec': totaldec, 'totalcheck': totalcheck, 'pgnum': self.pgnum } ocrline = ocrformat.format(**ocrkeys) assert len(ocrline) == 79 to.textLine(ocrline) canvas.drawText(to)
def draw(self): c = self.canv titlestyle = ParagraphStyle('Title', fontName='Helvetica', fontSize=36, leading=43) style = ParagraphStyle('Options', leftIndent=10 * mm, firstLineIndent=-10 * mm) text = [Paragraph(self.title, titlestyle)] for field, value in self.options: text.append( Paragraph(u'<b>{}:</b> <i>{}</i>'.format(field, value), style)) f = Frame( 10 * mm, 25 * mm, self.width - 53 * mm, 64 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=-5, # -5 font fudge factor showBoundary=0) f.addFromList(text, c) with save_state(c): c.translate(self.width - 40 * mm, self.height - 10 * mm) c.rotate(270) orgstyle = ParagraphStyle('OrgName', fontSize=11, leading=12) style = ParagraphStyle('OrgAddr', fontSize=8, leading=10) f = Frame(0, 0, self.height - 53 * mm, 30 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) l = [] if self.org.name: l.append(Paragraph(self.org.name[0], orgstyle)) if self.org.address: l.append( Paragraph('<br/>'.join(self.org.address[0].split('\n')), style)) if self.org.phone: l.append(Paragraph(self.org.phone[0], style)) f.addFromList(l, c) with save_state(c): c.translate(120 * mm, 15 * mm) c.setFont('Helvetica', 8) c.drawString(0, 0, u'Tickets by ') width = stringWidth(u'Tickets by ', 'Helvetica', 8) with save_state(c): # XXX Ideally, only load the logo once logo = PdfReader( os.path.join(os.path.dirname(__file__), 'eutaxia-logo.pdf')).pages[0] logo = pagexobj(logo) rl_obj = makerl(c, logo) scale = 9 / logo.BBox[3] c.translate(width, -1.5) c.scale(scale, scale) c.doForm(rl_obj) if False: p = c.beginPath() c.setDash(1) p.moveTo(0, 0) p.lineTo(logo.BBox[2], 0) p.lineTo(logo.BBox[2], logo.BBox[3]) p.lineTo(0, logo.BBox[3]) p.close() c.drawPath(p) width += logo.BBox[2] * scale c.drawString(0, -10, u'http://www.eutaxia.se/') width = max(width, stringWidth(u'http://www.eutaxia.se/', 'Helvetica', 8)) c.linkURL('http://www.eutaxia.se', (-1, -13, width, 10), relative=1) bar = code128.Code128(self.barcode, barWidth=0.3 * mm, humanReadable=1) bar.drawOn(c, 10 * mm, 10 * mm) qd = Drawing() # No border, deal with quiet zone manually q = qr.QrCodeWidget(self.qrcode, barLevel='M', barBorder=0, barWidth=30 * mm, barHeight=30 * mm) qd.add(q) renderPDF.draw(qd, c, self.width - q.barWidth - 10 * mm, 10 * mm) c.linkURL(self.qrcode, (self.width - q.barWidth - 10 * mm, 10 * mm, self.width - 10 * mm, 40 * mm), relative=1) p = c.beginPath() c.setDash(1, 2) p.moveTo(0, 0) p.lineTo(self.width, 0) c.drawPath(p) if False: p = c.beginPath() c.setDash(1) p.moveTo(0, 0) p.lineTo(self.width, 0) p.lineTo(self.width, self.height) p.lineTo(0, self.height) p.close() c.drawPath(p)
def build_pdf(self, response): cleaned_data = self.filterset.form.cleaned_data impresso = cleaned_data['impresso'] fs = int(impresso.fontsize) if cleaned_data['fontsize']: fs = int(cleaned_data['fontsize']) stylesheet = StyleSheet1() stylesheet.add(ParagraphStyle(name='pronome_style', fontName="Helvetica", fontSize=fs * 0.8, leading=fs)) stylesheet.add(ParagraphStyle(name='nome_style', fontName="Helvetica-Bold", fontSize=fs, leading=fs * 1.3)) stylesheet.add(ParagraphStyle(name='endereco_style', fontName="Helvetica", fontSize=fs * 0.9, leading=fs)) pagesize = (float(impresso.largura_pagina) * cm, float(impresso.altura_pagina) * cm) ms = pagesize[1] - float(impresso.margem_superior) * cm me = float(impresso.margem_esquerda) * cm ae = float(impresso.alturaetiqueta) * cm le = float(impresso.larguraetiqueta) * cm el = float(impresso.entre_linhas) * cm ec = float(impresso.entre_colunas) * cm col = float(impresso.colunasfolha) row = float(impresso.linhasfolha) cr = int(col * row) p = canvas.Canvas(response, pagesize=pagesize) if impresso.rotate: p.translate(pagesize[1], 0) p.rotate(90) i = -1 for contato in self.object_list.all(): i += 1 if i != 0 and i % cr == 0: p.showPage() if impresso.rotate: p.translate(pagesize[1], 0) p.rotate(90) q = floor(i / col) % row r = i % int(col) l = me + r * ec + r * le b = ms - (q + 1) * ae - q * el f = Frame(l, b, le, ae, leftPadding=fs / 3, bottomPadding=fs / 3, topPadding=fs / 3, rightPadding=fs / 3, showBoundary=0) # f.drawBoundary(p) f.addFromList(self.createParagraphs(contato, stylesheet), p) p.showPage() p.save()
def remake_pdf(page_layouts, output_path): page_width = page_layouts[0]['width'] page_height = page_layouts[0]['height'] # pdfmetrics.registerFont(cidfonts.UnicodeCIDFont("HeiseiMin-W3")) GEN_SHIN_GOTHIC_MEDIUM_TTF = "./fonts/GenShinGothic-Monospace-Medium.ttf" pdfmetrics.registerFont(TTFont('GenShinGoshic', GEN_SHIN_GOTHIC_MEDIUM_TTF)) show = 1 # 1:Frameの枠を表示, 0:表示しない doc = canvas.Canvas( output_path, pagesize=(page_width, page_height), ) page_num = 0 for page_layout in page_layouts: frame_id = 0 frames = [] for element in page_layout['texts']: x0 = element['x0'] x1 = element['x1'] y0 = element['y0'] y1 = element['y1'] width = element['width'] height = element['height'] text = element['text'] replace_strs = [b'\x00'] # byte文字列に変換 line_utf8 = text.encode('utf-8') #print(text.encode(encoding="utf-8", errors="strict")) #print(line_utf8) #print(line_utf8.isascii()) # ASCIIで以外が含まれているものを除外 if line_utf8.isascii() == False: continue # 余分な文字を除去する for replace_str in replace_strs: line_utf8 = line_utf8.replace(replace_str, b'') # strに戻す text = line_utf8.decode() text = translate(text) text = text.removeprefix("「") text = text.removesuffix("」") frame = Frame(x0, y0, width, height, showBoundary=show, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id=str(frame_id)) # フォントの大きさなど調整 style_dict = { "name": "normal", "fontName": "GenShinGoshic", "fontSize": 15, "leading": 10 } style = ParagraphStyle(**style_dict) # style_dict ={ # "name":"normal", # "fontName":"HeiseiMin-W3", # "fontSize":15, # "leading":10, # } # style = ParagraphStyle(**style_dict) # para = Paragraph(text) para = Paragraph(text, style) # 文字が領域内に入るかの判定 # とりあえず、収まりきらなかったらページ番号とidを出力 w, h = para.wrap(width, height) # find required space if w <= width and h <= height: frame.addFromList([para], doc) else: doc.rect(x0, y0, width, height, stroke=1, fill=0) print("Not enough space at p.", page_num, ", id:", frame_id) frame_id += 1 doc.showPage() page_num += 1 doc.save()
def run(): styles = getSampleStyleSheet() styleN = styles["Normal"] styleH = styles["Heading1"] story = [] # for codeNames in code story.append(Paragraph("I2of5", styleN)) story.append(I2of5(1234, barWidth=inch * 0.02, checksum=0)) story.append(Paragraph("MSI", styleN)) story.append(MSI(1234)) story.append(Paragraph("Codabar", styleN)) story.append(Codabar("A012345B", barWidth=inch * 0.02)) story.append(Paragraph("Code 11", styleN)) story.append(Code11("01234545634563")) story.append(Paragraph("Code 39", styleN)) story.append(Standard39("A012345B%R")) story.append(Paragraph("Extended Code 39", styleN)) story.append(Extended39("A012345B}")) story.append(Paragraph("Code93", styleN)) story.append(Standard93("CODE 93")) story.append(Paragraph("Extended Code93", styleN)) story.append(Extended93("L@@K! Code 93 :-)")) # , barWidth=0.005 * inch)) story.append(Paragraph("Code 128", styleN)) c = Code128("AB-12345678") # , barWidth=0.005 * inch) # print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch) # print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch) story.append(c) story.append(Paragraph("USPS FIM", styleN)) story.append(FIM("A")) story.append(Paragraph("USPS POSTNET", styleN)) story.append(POSTNET("78247-1043")) story.append(Paragraph("USPS 4 State", styleN)) story.append(USPS_4State("01234567094987654321", "01234567891")) from reportlab.graphics.barcode import createBarcodeDrawing story.append(Paragraph("EAN13", styleN)) bcd = createBarcodeDrawing("EAN13", value="123456789012") story.append(bcd) story.append(Paragraph("EAN8", styleN)) bcd = createBarcodeDrawing("EAN8", value="1234567") story.append(bcd) story.append(Paragraph("UPCA", styleN)) bcd = createBarcodeDrawing("UPCA", value="03600029145") story.append(bcd) story.append(Paragraph("USPS_4State", styleN)) bcd = createBarcodeDrawing("USPS_4State", value="01234567094987654321", routing="01234567891") story.append(bcd) story.append(Paragraph("Label Size", styleN)) story.append(XBox((2.0 + 5.0 / 8.0) * inch, 1 * inch, '1x2-5/8"')) story.append(Paragraph("Label Size", styleN)) story.append(XBox((1.75) * inch, 0.5 * inch, '1/2x1-3/4"')) c = Canvas("out.pdf") f = Frame(inch, inch, 6 * inch, 9 * inch, showBoundary=1) f.addFromList(story, c) c.save() print "saved out.pdf"