def toParagraphStyle(self, first, full=False): style = ParagraphStyle('default%d' % self.UID(), keepWithNext=first.keepWithNext) style.fontName = first.fontName style.fontSize = first.fontSize style.leading = max(first.leading, first.fontSize * 1.25) style.backColor = first.backColor style.spaceBefore = first.spaceBefore style.spaceAfter = first.spaceAfter style.leftIndent = first.leftIndent style.rightIndent = first.rightIndent style.firstLineIndent = first.firstLineIndent style.textColor = first.textColor style.alignment = first.alignment style.bulletFontName = first.bulletFontName or first.fontName style.bulletFontSize = first.fontSize style.bulletIndent = first.bulletIndent # Border handling for Paragraph style.borderWidth = 0 if getBorderStyle(first.borderTopStyle): style.borderWidth = max(first.borderLeftWidth, first.borderRightWidth, first.borderTopWidth, first.borderBottomWidth) style.borderPadding = first.borderPadding # + first.borderWidth style.borderColor = first.borderTopColor # If no border color is given, the text color is used (XXX Tables!) if (style.borderColor is None) and style.borderWidth: style.borderColor = first.textColor if full: style.fontName = tt2ps(first.fontName, first.bold, first.italic) return style
def legend_building(decimal_scores, justification_legend, content): p = ParagraphStyle('legend') p.textColor = 'grey' p.borderColor = 'grey' p.borderWidth = 1 p.alignment = TA_CENTER p.fontSize = 8 p.borderPadding = 5 legend_text = justification_legend legend_text += "<br/>%s" % (str(_('score_legend') % "0 - 20")) if decimal_scores: legend_text += "<br/><font color=red>%s</font>" % _( 'authorized_decimal_for_this_activity') else: legend_text += "<br/><font color=red>%s</font>" % _( 'unauthorized_decimal_for_this_activity') legend_text += '''<br/> %s : <a href="%s"><font color=blue><u>%s</u></font></a>''' \ % (_("in_accordance_to_regulation"), _("link_to_RGEE"), _("link_to_RGEE")) content.append( Paragraph( ''' <para> %s </para> ''' % legend_text, p))
def addPara(self, force=False): # Cleanup the trail for frag in reversed(self.fragList): frag.text = frag.text.rstrip() if frag.text: break if force or (self.text.strip() and self.fragList): # Strip trailing whitespaces # for f in self.fragList: # f.text = f.text.lstrip() # if f.text: # break # self.fragList[-1].lineBreak = self.fragList[-1].text.rstrip() # Update paragraph style by style of first fragment first = self.fragBlock style = ParagraphStyle("default%d" % self.UID(), keepWithNext=first.keepWithNext) style.fontName = first.fontName style.fontSize = first.fontSize style.leading = max(first.leading, first.fontSize * 1.25) style.backColor = first.backColor style.spaceBefore = first.spaceBefore style.spaceAfter = first.spaceAfter style.leftIndent = first.leftIndent style.rightIndent = first.rightIndent style.firstLineIndent = first.firstLineIndent style.alignment = first.alignment style.bulletFontName = first.fontName style.bulletFontSize = first.fontSize style.bulletIndent = first.bulletIndent style.borderWidth = max( first.borderLeftWidth, first.borderRightWidth, first.borderTopWidth, first.borderBottomWidth ) style.borderPadding = first.borderPadding # + first.borderWidth style.borderColor = first.borderTopColor # borderRadius: None, # print repr(self.text.strip()), style.leading, "".join([repr(x.text) for x in self.fragList]) # print first.leftIndent, first.listStyleType,repr(self.text) # Add paragraph to story para = PmlParagraph( self.text, style, frags=self.fragAnchor + self.fragList, bulletText=copy.copy(first.bulletText) ) para.outline = frag.outline para.outlineLevel = frag.outlineLevel para.outlineOpen = frag.outlineOpen self.addStory(para) self.fragAnchor = [] first.bulletText = None self.clearFrag()
def reporteDiarioCitas(request): global y,ca,contador,nuevo,reingreso,continuado especialidades = Especialidad.objects.all() fecha = datetime.today() fecha=fecha.strftime("%Y-%m-%d") width,height =A4 citas= Cita.objects.filter(fechaAtencion=fecha).order_by("especialidad","medico") if citas.count()!=0: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=ReporteDiarioCitas_'+fecha+'.pdf' buffer = BytesIO() ca = canvas.Canvas(buffer,pagesize=A4) p = ParagraphStyle('test') p.textColor = 'black' p.borderColor = 'black' p.alignment = TA_CENTER p.borderWidth = 0.5 p.fontSize = 10 y=800 crearCabeceraEspecialidad(str(citas[0].especialidad),fecha) crearCabeceraMedico(str(citas[0].medico.nombres+" "+citas[0].medico.apellido_paterno+" "+ citas[0].medico.apellido_materno)) crearEncabezados(p) for i in range(citas.count()): imprimir(p,citas[i]) if citas.count()!= i+1 : if str(citas[i].especialidad) != str(citas[i+1].especialidad): if contador!=0 or nuevo!=0 or reingreso !=0 or continuador!=0: y=y-10 contadorEstados(p) y=y-10 crearCabeceraEspecialidad(str(citas[i+1].especialidad),fecha) if str(citas[i].medico) != str(citas[i+1].medico): if contador!=0 or nuevo!=0 or reingreso !=0 or continuador!=0: y=y-10 contadorEstados(p) y=y-5 crearCabeceraMedico(str(citas[i+1].medico.nombres+" "+citas[i+1].medico.apellido_paterno+" "+ citas[i+1].medico.apellido_materno)) crearEncabezados(p) if citas.count()-1== i : y=y-10 contadorEstados(p) ca.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response else: return JsonResponse({'status':'FAIL'})
def _build_legend_block_style(): style = ParagraphStyle('legend') style.textColor = 'grey' style.borderColor = 'grey' style.borderWidth = 1 style.alignment = TA_CENTER style.fontSize = 8 style.borderPadding = 5 return style
def parag_style(): from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_LEFT style = ParagraphStyle('test') style.textColor = 'black' style.borderColor = 'black' style.borderWidth = 0 style.alignment = TA_LEFT style.fontSize = 9 return style
def label(pdf, gaceta_end, page): p = ParagraphStyle('test') p.textColor = 'black' p.alignment = TA_CENTER p.fontSize = 12 p.borderColor = 'black' p.borderWidth = 1 p.borderPadding = 4 para = Paragraph(LABEL[page], p) para.wrapOn(pdf, 150, 200) para.drawOn(pdf, 380, gaceta_end - 10 - para.height)
def legend_building(learning_unit_year, is_fac, content, styles): content.append(BIG_INTER_LINE) content.append(BIG_INTER_LINE) p = ParagraphStyle('legend') p.textColor = 'grey' p.borderColor = 'grey' p.borderWidth = 1 p.alignment = TA_CENTER p.fontSize =8 p.borderPadding = 5 legend_text = "%s : %s" % (_('Other score legend'), ExamEnrollment.justification_label_authorized(is_fac)) if not learning_unit_year.decimal_scores: legend_text += "<br/><font color=red>%s</font>" % _('UnAuthorized decimal for this activity') content.append(Paragraph(''' <para> %s </para> ''' % legend_text, p))
def cover(self): """ Display a cover. """ # Define a style for the cover cover = ParagraphStyle("Cover") cover.textColor = "black" cover.borderColor = "black" cover.borderPadding = 80 cover.borderWidth = 1 cover.alignment = TA_CENTER cover.fontSize = 30 cover.borderRadius = 20 cover.backColor = "gray" cover.leading = 40 pagesize = self.templates["OneCol"]["pagesize"] self.story.append(Cover(pagesize[0], pagesize[1] / 3, self.author, self.client, self.poweredby, self.project, self.timepoint, self.subject, self.date)) self.story.append(Spacer(0, pagesize[1] / 2)) self.story.append(Paragraph(self.title, cover))
def crearCabeceraEspecialidad(especialidad,fecha): global y,ca,contador #contador=0 p1 = ParagraphStyle('test') p1.textColor = 'black' p1.borderColor = 'white' p1.alignment = TA_CENTER p1.borderWidth = 1 p1.fontSize = 20 if (y<41): ca.showPage() y=800 especialidad = Paragraph(str(especialidad),p1) especialidad.wrapOn(ca,500,0) especialidad.drawOn(ca, 40, y) p1.fontSize = 12 fecha = Paragraph("Fecha:"+" "+str(fecha),p1) fecha.wrapOn(ca,500,0) fecha.drawOn(ca,40, y-25) y=y-40
def cover(self): """ Display a cover. """ # Define a style for the cover cover = ParagraphStyle("Cover") cover.textColor = "black" cover.borderColor = "black" cover.borderPadding = 80 cover.borderWidth = 1 cover.alignment = TA_CENTER cover.fontSize = 30 cover.borderRadius = 20 cover.backColor = "gray" cover.leading = 40 pagesize = self.templates["OneCol"]["pagesize"] self.story.append( Cover(pagesize[0], pagesize[1] / 3, self.author, self.client, self.poweredby, self.project, self.timepoint, self.subject, self.date)) self.story.append(Spacer(0, pagesize[1] / 2)) self.story.append(Paragraph(self.title, cover))
def update_paragraph_style(default_style: ParagraphStyle, bnml_style: Dict[str, Any]): """Replaces ReportLab ParagraphStyle attributes with Kassia bnml attributes. :param default_style: The default ParagraphStyle (a ReportLab class). :param bnml_style: A dictionary of styles read a Kassia bnml file. The bnml_style needs to have ben already run through fill_dict_attributes(). """ if 'font_family' in bnml_style and font_reader.is_registered_font( bnml_style['font_family']): default_style.fontName = bnml_style['font_family'] if 'font_size' in bnml_style: default_style.fontSize = bnml_style['font_size'] if 'color' in bnml_style: default_style.textColor = bnml_style['color'] if 'bgcolor' in bnml_style: default_style.backColor = bnml_style['bgcolor'] if 'align' in bnml_style: default_style.alignment = bnml_style['align'] if 'first_line_indent' in bnml_style: default_style.firstLineIndent = bnml_style['first_line_indent'] if 'auto_leading' in bnml_style: default_style.autoLeading = bnml_style['auto_leading'] if 'leading' in bnml_style: default_style.leading = bnml_style['leading'] if 'left_indent' in bnml_style: default_style.leftIndent = bnml_style['left_indent'] if 'right_indent' in bnml_style: default_style.rightIndent = bnml_style['right_indent'] if 'space_before' in bnml_style: default_style.spaceBefore = bnml_style['space_before'] if 'space_after' in bnml_style: default_style.spaceAfter = bnml_style['space_after'] if 'word_spacing' in bnml_style: default_style.wordSpace = bnml_style['word_spacing'] if 'border_width' in bnml_style: default_style.borderWidth = bnml_style['border_width'] if 'border_color' in bnml_style: default_style.borderColor = bnml_style['border_color'] return default_style
def build_pdf(image_file): filename = "%s.pdf" % _('scores_sheet') response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"' % filename buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=PAGE_SIZE, rightMargin=MARGIN_SIZE, leftMargin=MARGIN_SIZE, topMargin=TOP_MARGIN, bottomMargin=BOTTOM_MARGIN) image1 = get_image2(image_file) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) content = [image1] p = ParagraphStyle('legend') p.textColor = 'grey' p.borderColor = 'grey' p.borderWidth = 1 p.alignment = TA_CENTER p.fontSize = 8 p.borderPadding = 5 legend_text = 'justification_legend' legend_text += "<br/><font color=red>%s</font>" % 'fffff' content.append(Paragraph(''' <para> %s </para> ''' % legend_text, p)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def _test0(self): "This makes one long multi-page paragraph." # Build story. story = [] a = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet['Heading2'] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet['Heading3'] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet['BodyText'] a( Paragraph( """ Subsequent pages test pageBreakBefore, frameBreakBefore and keepTogether attributes. Generated at %s. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % (time.ctime(time.time()), len(story)), bt)) for i in xrange(10): a(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1)) for j in xrange(3): a( Paragraph( 'Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) a( Paragraph( 'Heading 2 always starts a new frame (%d)' % len(story), h2)) a( Paragraph( 'Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) for j in xrange(3): a( Paragraph( randomText(theme=PYTHON, sentences=2) + ' (%d)' % len(story), bt)) a( Paragraph( 'I should never be at the bottom of a frame (%d)' % len(story), h3)) a( Paragraph( randomText(theme=PYTHON, sentences=1) + ' (%d)' % len(story), bt)) a(Paragraph('Now we do <br/> tests', h1)) a(Paragraph('First off no br tags', h3)) a(Paragraph(_text1, bt)) a(Paragraph("<br/> after 'the' in line 4", h3)) a(Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1), bt)) a(Paragraph("2*<br/> after 'the' in line 4", h3)) a( Paragraph(_text1.replace('forms of the', 'forms of the<br/><br/>', 1), bt)) a(Paragraph("<br/> after 'I suggested ' in line 5", h3)) a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1), bt)) a(Paragraph("2*<br/> after 'I suggested ' in line 5", h3)) a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/><br/>', 1), bt)) a(Paragraph("<br/> at the end of the paragraph!", h3)) a(Paragraph("""text one<br/>text two<br/>""", bt)) a(Paragraph("Border with <nr/> at the end of the paragraph!", h3)) bt1 = ParagraphStyle('bodyText1', bt) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor('red') bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""", bt1)) a(Paragraph("Border no <nr/> at the end of the paragraph!", h3)) bt1 = ParagraphStyle('bodyText1', bt) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor('red') bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two""", bt1)) a(Paragraph("Different border style!", h3)) bt2 = ParagraphStyle('bodyText1', bt1) bt2.borderWidth = 1.5 bt2.borderColor = colors.toColor('blue') bt2.backColor = colors.gray bt2.borderRadius = 3 bt2.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""", bt2)) doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf')) doc.multiBuild(story)
def reporteTipoExamen(request, tipoExam): global y, ca, contador Examenes = ExamenLabCab.objects.filter( tipoExam__nombre=tipoExam).order_by("fecha") if Examenes.count() != 0: response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=Reporte' + tipoExam + '.pdf' buffer = BytesIO() ca = canvas.Canvas(buffer, pagesize=A4) p = ParagraphStyle('test') p.textColor = 'black' p.borderColor = 'black' p.alignment = TA_CENTER p.borderWidth = 1 p.fontSize = 10 contador = 0 y = 800 #Cabecera__________________________________________ ca.setLineWidth(.3) ca.setFont('Helvetica', 24) ca.drawString(195, 750, 'REPORTE TIPO') ca.setFont('Helvetica', 24) ca.drawString(230, 730, 'EXAMEN') ca.line(40, 695, 550, 695) fecha = datetime.now() fecha = fecha.strftime("%d-%m-%Y") ca.setFont('Helvetica', 13) ca.drawString(440, 697, 'Fecha:') ca.drawString(480, 697, str(fecha)) ca.drawImage("apps/Laboratorio/static/Unsa.png", 45, 700, width=85, height=110, mask='auto') width, height = A4 #Cabecera_____________________________________________ y = y - 120 #Cabecera TABLA_______________________________________ cont = Paragraph("N°", p) cont.wrapOn(ca, 15, 90) cont.drawOn(ca, 40, y) historia = Paragraph("DNI", p) historia.wrapOn(ca, 100, 90) historia.drawOn(ca, 55, y) nombre = Paragraph("NOMBRE", p) nombre.wrapOn(ca, 200, 90) nombre.drawOn(ca, 155, y) recibo = Paragraph("TIPO DE EXAMEN", p) recibo.wrapOn(ca, 100, 90) recibo.drawOn(ca, 355, y) condicion = Paragraph("FECHA", p) condicion.wrapOn(ca, 100, 90) condicion.drawOn(ca, 455, y) y = y - 11.5 for i in range(Examenes.count()): imprimir(p, Examenes[i]) #Funcion imprimir ca.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response else: return JsonResponse({'status': 'FAIL'})
def resultadoExamen(request, id): global c, y1, contador examenLabCab = ExamenLabCab.objects.filter(id=id) examenLabDet = ExamenLabDet.objects.filter(codigoExam=id) if examenLabCab.count() != 0: response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=ResultadoExamen.pdf' buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) p = ParagraphStyle('test') p.textColor = 'black' p.borderColor = 'black' p.alignment = TA_CENTER p.borderWidth = 1 p.fontSize = 10 contador = 0 #Cabecera__________________________________________ c.setLineWidth(.3) c.setFont('Helvetica', 20) c.drawString(185, 750, 'Resultado de Examen') c.drawString(415, 770, 'Examen N°') c.drawString(455, 725, examenLabCab[0].id.__str__()) c.drawImage("apps/Laboratorio/static/Unsa.png", 60, 700, width=85, height=110, mask='auto') c.line(40, 695, 550, 695) c.line(40, 820, 550, 820) c.line(40, 695, 40, 820) c.line(165, 695, 165, 820) c.line(395, 695, 395, 820) c.line(550, 695, 550, 820) c.line(395, 750, 550, 750) #Cabecera_____________________________________________ y = -10 c.setFont('Helvetica', 13) c.drawString(45, 675 + y, 'Nombre: ') c.drawString(100, 675 + y, examenLabCab[0].nombre.__str__()) c.drawString(400, 675 + y, 'DNI: ') c.drawString(440, 675 + y, examenLabCab[0].dni.__str__()) c.drawString(400, 655 + y, 'Fecha: ') c.drawString(440, 655 + y, examenLabCab[0].fecha.__str__()) c.drawString(45, 655 + y, 'Orden: ') c.drawString(100, 655 + y, examenLabCab[0].orden.__str__()) c.line(40, 690 + y, 550, 690 + y) c.line(40, 650 + y, 550, 650 + y) c.line(40, 650 + y, 40, 690 + y) c.line(395, 650 + y, 395, 690 + y) c.line(550, 650 + y, 550, 690 + y) c.drawString(40, 630 + y, 'Examen de: ') c.drawString(115, 630 + y, examenLabCab[0].tipoExam.__str__()) y1 = 600 #_______________Detalles______________________ cont = Paragraph("N°", p) cont.wrapOn(c, 15, 90) cont.drawOn(c, 40, y1) historia = Paragraph("DESCRIPCION", p) historia.wrapOn(c, 180, 90) historia.drawOn(c, 55, y1) nombre = Paragraph("RESULTADO", p) nombre.wrapOn(c, 80, 90) nombre.drawOn(c, 235, y1) recibo = Paragraph("UNIDADES", p) recibo.wrapOn(c, 80, 90) recibo.drawOn(c, 315, y1) condicion = Paragraph("RANGO DE REFERENCIA", p) condicion.wrapOn(c, 155, 90) condicion.drawOn(c, 395, y1) y1 = y1 - 11.5 for var in examenLabDet: imprimirDet(p, var) #Funcion imprimir if (y1 < 25): c.showPage() y1 = 800 c.drawString(40, y1 - 10, 'Observaciones :') c.setFont('Helvetica', 11) c.drawString(40, y1 - 20, examenLabCab[0].observaciones.__str__()) # Cierre PDF c.showPage() c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response else: return JsonResponse({'status': 'FAIL'})
def invoice_list_export(request): user = request.user def invoice_list_footer(canvas, doc): canvas.saveState() canvas.setFont("Times-Roman", 10) PAGE_WIDTH = defaultPageSize[0] footer_text = "%s %s - SIRET : %s - %s, %s %s" % ( user.first_name, user.last_name, user.get_profile().company_id, user.get_profile().address.street, user.get_profile().address.zipcode, user.get_profile().address.city, ) if user.get_profile().address.country: footer_text = footer_text + ", %s" % (user.get_profile().address.country) canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.5 * inch, footer_text) canvas.restoreState() year = int(request.GET.get("year")) invoices = Invoice.objects.filter(owner=user, state__gte=INVOICE_STATE_PAID, paid_date__year=year).order_by( "invoice_id" ) filename = ugettext("invoice_book_%(year)d.pdf") % {"year": year} response = HttpResponse(mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=%s" % (filename) doc = BaseDocTemplate(response, title=ugettext("Invoice book %(year)d") % {"year": year}) frameT = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id="normal") doc.addPageTemplates([PageTemplate(id="all", frames=frameT, onPage=invoice_list_footer)]) styleH = ParagraphStyle({}) styleH.fontSize = 14 styleH.borderColor = colors.black styleH.alignment = TA_CENTER p = Paragraph(ugettext("Invoice book %(year)d") % {"year": year}, styleH) spacer = Spacer(1 * inch, 0.5 * inch) data = [ [ ugettext("Date"), ugettext("Ref."), ugettext("Customer"), ugettext("Nature"), ugettext("Amount"), ugettext("Payment type"), ] ] for invoice in invoices: data.append( [ localize(invoice.paid_date), invoice.invoice_id, invoice.customer, invoice.getNature(), localize(invoice.amount), invoice.get_payment_type_display(), ] ) t = Table( data, [0.8 * inch, 0.4 * inch, 2.5 * inch, 1.2 * inch, 0.8 * inch, 1.2 * inch], (len(invoices) + 1) * [0.3 * inch], ) t.setStyle( TableStyle( [ ("ALIGN", (0, 0), (-1, 0), "CENTER"), ("ALIGN", (1, 0), (-1, -1), "CENTER"), ("ALIGN", (2, 1), (2, -1), "LEFT"), ("FONT", (0, 0), (-1, 0), "Times-Bold"), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ] ) ) story = [] story.append(p) story.append(spacer) story.append(t) doc.build(story, canvasmaker=NumberedCanvas) return response
def invoice_list_export(request): user = request.user def invoice_list_footer(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 10) PAGE_WIDTH = defaultPageSize[0] footer_text = "%s %s - SIRET : %s - %s, %s %s" % ( user.first_name, user.last_name, user.get_profile().company_id, user.get_profile().address.street, user.get_profile().address.zipcode, user.get_profile().address.city) if user.get_profile().address.country: footer_text = footer_text + ", %s" % ( user.get_profile().address.country) canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.5 * inch, footer_text) canvas.restoreState() year = int(request.GET.get('year')) invoices = Invoice.objects.filter( owner=user, state__gte=INVOICE_STATE_PAID, paid_date__year=year).order_by('invoice_id') filename = ugettext('invoice_book_%(year)d.pdf') % {'year': year} response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s' % (filename) doc = BaseDocTemplate(response, title=ugettext('Invoice book %(year)d') % {'year': year}) frameT = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') doc.addPageTemplates([ PageTemplate(id='all', frames=frameT, onPage=invoice_list_footer), ]) styleH = ParagraphStyle({}) styleH.fontSize = 14 styleH.borderColor = colors.black styleH.alignment = TA_CENTER p = Paragraph(ugettext('Invoice book %(year)d') % {'year': year}, styleH) spacer = Spacer(1 * inch, 0.5 * inch) data = [[ ugettext('Date'), ugettext('Ref.'), ugettext('Customer'), ugettext('Nature'), ugettext('Amount'), ugettext('Payment type') ]] for invoice in invoices: data.append([ localize(invoice.paid_date), invoice.invoice_id, invoice.customer, invoice.getNature(), localize(invoice.amount), invoice.get_payment_type_display() ]) t = Table(data, [ 0.8 * inch, 0.4 * inch, 2.5 * inch, 1.2 * inch, 0.8 * inch, 1.2 * inch ], (len(invoices) + 1) * [0.3 * inch]) t.setStyle( TableStyle([ ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN', (1, 0), (-1, -1), 'CENTER'), ('ALIGN', (2, 1), (2, -1), 'LEFT'), ('FONT', (0, 0), (-1, 0), 'Times-Bold'), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ])) story = [] story.append(p) story.append(spacer) story.append(t) doc.build(story, canvasmaker=NumberedCanvas) return response
def to_pdf(self, user, response): def invoice_footer(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 10) PAGE_WIDTH = defaultPageSize[0] footer_text = "%s %s - SIRET : %s - %s, %s %s" % (user.first_name, user.last_name, user.get_profile().company_id, user.get_profile().address.street.replace("\n", ", ").replace("\r", ""), user.get_profile().address.zipcode, user.get_profile().address.city) if user.get_profile().address.country: footer_text = footer_text + u", %s" % (user.get_profile().address.country) canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.5 * inch, footer_text) canvas.restoreState() filename = ugettext('invoice_%(invoice_id)d.pdf') % {'invoice_id': self.invoice_id} response['Content-Disposition'] = 'attachment; filename=%s' % (filename) doc = BaseDocTemplate(response, title=ugettext('Invoice #%(invoice_id)d') % {'invoice_id': self.invoice_id}, leftMargin=0.5 * inch, rightMargin=0.5 * inch) frameT = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height + 0.5 * inch, id='normal') doc.addPageTemplates([PageTemplate(id='all', frames=frameT, onPage=invoice_footer), ]) styleH = ParagraphStyle({}) styleH.fontSize = 14 styleH.leading = 16 styleH.borderPadding = (5,) * 4 styleTotal = ParagraphStyle({}) styleTotal.fontSize = 14 styleTotal.leading = 16 styleTotal.borderColor = colors.black styleTotal.borderWidth = 0.5 styleTotal.borderPadding = (5,) * 4 styleH2 = ParagraphStyle({}) styleH2.fontSize = 14 styleH2.leading = 16 styleTitle = ParagraphStyle({}) styleTitle.fontSize = 14 styleTitle.fontName = "Times-Bold" styleN = ParagraphStyle({}) styleN.fontSize = 12 styleN.leading = 14 styleNSmall = ParagraphStyle({}) styleNSmall.fontSize = 8 styleNSmall.leading = 14 styleF = ParagraphStyle({}) styleF.fontSize = 10 styleF.alignment = TA_CENTER styleLabel = ParagraphStyle({}) story = [] data = [] user_header_content = """ %s %s<br/> %s<br/> %s %s<br/> %s<br/> SIRET : %s<br/> """ % (user.first_name, user.last_name, user.get_profile().address.street.replace("\n", "<br/>"), user.get_profile().address.zipcode, user.get_profile().address.city, user.get_profile().address.country or '', user.get_profile().company_id) customer_header_content = """ %s<br/> %s<br/> %s %s<br/> %s<br/> """ if user.get_profile().logo_file: user_header = Image("%s%s" % (settings.FILE_UPLOAD_DIR, user.get_profile().logo_file)) else: user_header = Paragraph(user_header_content, styleH) customer_header = customer_header_content % (self.customer.name, self.customer.address.street.replace("\n", "<br/>"), self.customer.address.zipcode, self.customer.address.city, self.customer.address.country or '') if self.customer.contact_type == CONTACT_TYPE_COMPANY \ and self.customer.company_id: customer_header = "%sSIRET : %s<br/>" % (customer_header, self.customer.company_id) customer_header = Paragraph(customer_header, styleH) data.append([user_header, '', customer_header]) t1 = Table(data, [3.5 * inch, 0.3 * inch, 3.5 * inch], [1.9 * inch]) table_style = [('BOX', (0, 0), (0, 0), 0.25, colors.black), ('BOX', (2, 0), (2, 0), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ] if user.get_profile().logo_file: table_style.append(('TOPPADDING', (0, 0), (0, 0), 0)) table_style.append(('LEFTPADDING', (0, 0), (0, 0), 0)) t1.setStyle(TableStyle(table_style)) story.append(t1) spacer1 = Spacer(doc.width, 0.25 * inch) story.append(spacer1) data = [] msg = u"Dispensé d'immatriculation au registre du commerce et des sociétés (RCS) et au répertoire des métiers (RM)" data.append([Paragraph(msg, styleN), '', Paragraph(_("Date : %s") % (localize(self.edition_date)), styleH2)]) t2 = Table(data, [3.5 * inch, 0.3 * inch, 3.5 * inch], [0.7 * inch]) t2.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) story.append(t2) spacer2 = Spacer(doc.width, 0.25 * inch) story.append(spacer2) story.append(Paragraph(_("INVOICE #%d") % (self.invoice_id), styleTitle)) spacer3 = Spacer(doc.width, 0.1 * inch) story.append(spacer3) # invoice row list data = [[ugettext('Label'), ugettext('Quantity'), ugettext('Unit price'), ugettext('Total')]] rows = self.invoice_rows.all() extra_rows = 0 label_width = 4.5 * inch for row in rows: label = row.label if row.proposal.reference: label = u"%s - [%s]" % (label, row.proposal.reference) para = Paragraph(label, styleLabel) para.width = label_width splitted_para = para.breakLines(label_width) label = " ".join(splitted_para.lines[0][1]) quantity = row.quantity quantity = quantity.quantize(Decimal(1)) if quantity == quantity.to_integral() else quantity.normalize() unit_price = row.unit_price unit_price = unit_price.quantize(Decimal(1)) if unit_price == unit_price.to_integral() else unit_price.normalize() total = row.quantity * row.unit_price total = total.quantize(Decimal(1)) if total == total.to_integral() else total.normalize() data.append([label, localize(quantity), "%s %s" % (localize(unit_price), "€".decode('utf-8')), "%s %s" % (localize(total), "€".decode('utf-8'))]) for extra_row in splitted_para.lines[1:]: label = " ".join(extra_row[1]) data.append([label, '', '', '']) extra_rows = extra_rows + 1 row_count = len(rows) + extra_rows if row_count <= 16: max_row_count = 16 else: first_page_count = 21 normal_page_count = 33 last_page_count = 27 max_row_count = first_page_count + ((row_count - first_page_count) // normal_page_count * normal_page_count) + last_page_count if row_count - first_page_count - ((row_count - first_page_count) // normal_page_count * normal_page_count) > last_page_count: max_row_count = max_row_count + normal_page_count for i in range(max_row_count - row_count): data.append(['', '', '', '']) row_table = Table(data, [4.7 * inch, 0.8 * inch, 0.9 * inch, 0.8 * inch], (max_row_count + 1) * [0.3 * inch]) row_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN', (1, 0), (-1, -1), 'CENTER'), ('FONT', (0, 0), (-1, 0), 'Times-Bold'), ('BOX', (0, 0), (-1, 0), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, 0), 0.25, colors.black), ('BOX', (0, 1), (0, -1), 0.25, colors.black), ('BOX', (1, 1), (1, -1), 0.25, colors.black), ('BOX', (2, 1), (2, -1), 0.25, colors.black), ('BOX', (3, 1), (3, -1), 0.25, colors.black), ])) story.append(row_table) spacer4 = Spacer(doc.width, 0.35 * inch) story.append(spacer4) invoice_amount = self.amount invoice_amount = invoice_amount.quantize(Decimal(1)) if invoice_amount == invoice_amount.to_integral() else invoice_amount.normalize() left_block = [Paragraph(_("Payment date : %s") % (localize(self.payment_date)), styleN), Paragraph(_("Penalty begins on : %s") % (localize(self.penalty_date) or ''), styleN), Paragraph(_("Penalty rate : %s") % (localize(self.penalty_rate) or ''), styleN), Paragraph(_("Discount conditions : %s") % (self.discount_conditions or ''), styleN)] if self.owner.get_profile().iban_bban: left_block.append(Spacer(doc.width, 0.2 * inch)) left_block.append(Paragraph(_("IBAN/BBAN : %s") % (self.owner.get_profile().iban_bban), styleNSmall)) if self.owner.get_profile().bic: left_block.append(Paragraph(_("BIC/SWIFT : %s") % (self.owner.get_profile().bic), styleNSmall)) data = [[left_block, '', [Paragraph(_("TOTAL excl. VAT : %(amount)s %(currency)s") % {'amount': localize(invoice_amount), 'currency' : "€".decode('utf-8')}, styleTotal), Spacer(1, 0.25 * inch), Paragraph(u"TVA non applicable, art. 293 B du CGI", styleN)]], ] if self.execution_begin_date and self.execution_end_date: data[0][0].insert(1, Paragraph(_("Execution dates : %(begin_date)s to %(end_date)s") % {'begin_date': localize(self.execution_begin_date), 'end_date' : localize(self.execution_end_date)}, styleN)) footer_table = Table(data, [4.5 * inch, 0.3 * inch, 2.5 * inch], [1 * inch]) footer_table.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) story.append(footer_table) doc.build(story, canvasmaker=NumberedCanvas) return response
def createPDF(self): # ------------------------------------------------------------------------- # Define functions used internally # ------------------------------------------------------------------------- # Returns the plain (non-HTML) text for an item. Used at the lowest level # of the DOM tree because it doesn't preserve any HTML formatting def getItemText(item): if isinstance(item, Tag): return portal_transforms.convert('html_to_text', repr(item)).getData() elif isinstance(item, NavigableString): return str(item).strip() else: return str(item).strip() # Provides the limited subset of HTML content used by the PDF generator space_before_punctuation_re = re.compile(u"\s+([.;:,!?])", re.I|re.M) def getInlineContents(item): p_contents = [] for i in item.contents: if isinstance(i, Tag): item_type = i.name if item_type in ['b', 'strong', 'i', 'em', 'super', 'sub', 'a']: for a in ['class', 'title', 'rel']: if i.get(a): del i[a] if item_type == 'strong': i.name = 'b' elif item_type == 'em': i.name = 'i' elif item_type == 'a': i.name = 'link' if not (i['href'].startswith('http') or i['href'].startswith('mailto')): i['href'] = urljoin(self.context.absolute_url(), i['href']) # Wouldn't it be nice to underline the links? i['color'] = 'blue' if i.string: p_contents.append(repr(i)) else: p_contents.append(getInlineContents(i)) else: p_contents.append(getItemText(i)) elif isinstance(i, NavigableString): p_contents.append(str(i).strip()) contents = " ".join(p_contents) return space_before_punctuation_re.sub(r"\1", contents) # Returns structure containing table data when passed a BeautifulSoup # <table> element. def getTableData(item): def getCellSpan(cell): colspan = int(cell.get('colspan', 1)) rowspan = int(cell.get('rowspan', 1)) return (colspan, rowspan) th_bg = HexColor('#CCCCCC') th_text = HexColor('#000000') grid = HexColor('#999999') table_data = [] table_style = [] r_index = 0 for tr in item.findAll('tr'): c_index = 0 table_row = [] for i in tr.findAll('th'): table_row.append(Paragraph(getInlineContents(i), th_cell)) (colspan, rowspan) = getCellSpan(i) c_max = c_index + colspan - 1 r_max = r_index + rowspan - 1 table_style.extend([ ('FONTNAME', (c_index,r_index), (c_index,r_index), 'Times-Bold'), ('FONTSIZE', (c_index,r_index), (c_index,r_index), 9), ('BACKGROUND', (c_index,r_index), (c_index,r_index), th_bg), ('GRID', (c_index,r_index), (c_max,r_max), 0.5, grid), ('TEXTCOLOR', (c_index,r_index), (c_index,r_index), th_text), ('LEFTPADDING', (c_index,r_index), (c_index,r_index), 3), ('RIGHTPADDING', (c_index,r_index), (c_index,r_index), 3), ('SPAN', (c_index,r_index), (c_max,r_max)), ] ) c_index = c_index + 1 for i in tr.findAll('td'): td_align = i.get('align', 'LEFT').upper() if td_align == 'RIGHT': p = Paragraph(getInlineContents(i), td_cell_right) else: p = Paragraph(getInlineContents(i), td_cell) p.hAlign = td_align table_row.append(p) (colspan, rowspan) = getCellSpan(i) c_max = c_index + colspan - 1 r_max = r_index + rowspan - 1 table_style.extend([ ('GRID', (c_index,r_index), (c_max,r_max), 0.5, grid), ('FONTNAME', (c_index,r_index), (c_index,r_index), 'Times-Roman'), ('FONTSIZE', (c_index,r_index), (c_index,r_index), 9), ('LEFTPADDING', (c_index,r_index), (c_index,r_index), 3), ('RIGHTPADDING', (c_index,r_index), (c_index,r_index), 3), ('SPAN', (c_index,r_index), (c_max,r_max)), ('ALIGN', (c_index,r_index), (c_index,r_index), td_align), ] ) c_index = c_index + 1 table_data.append(table_row) r_index = r_index + 1 caption = item.find('caption') return (table_data, TableStyle(table_style), caption) # Provides the PDF entities for the corresponding HTML tags. def getContent(item, bump_headings=False): pdf = [] if isinstance(item, Tag): className=item.get('class', '').split() item_type = item.name if item_type in ['h2', 'h3', 'h4', 'h5', 'h6']: item_style = tag_to_style.get(item_type) h = Paragraph(getItemText(item), styles[item_style]) h.keepWithNext = True pdf.append(h) if item_type == 'h2' and not bump_headings: hr = HRFlowable(width='100%', thickness=0.25, spaceBefore=2, spaceAfter=4, color=styles[item_style].textColor) hr.keepWithNext = True pdf.append(hr) elif item_type in ['table']: (table_data, table_style, caption) = getTableData(item) table = Table(table_data) table.setStyle(table_style) table.hAlign = 'LEFT' table.spaceBefore = 10 table.spaceAfter = 10 if caption: caption_el = Paragraph(getInlineContents(caption), discreet) pdf.append(KeepTogether([table, caption_el])) else: pdf.append(table) elif item_type in ['ul']: for i in item.findAll('li'): pdf.append(Paragraph('<bullet>•</bullet>%s' % getInlineContents(i), bullet_list)) elif item_type in ['ol']: # Sequences were incrementing based on previous PDF generations. # Including explicit ID and reset li_uuid = uuid1().hex for i in item.findAll('li'): pdf.append(Paragraph('<seq id="%s" />. %s' % (li_uuid, getInlineContents(i)), bullet_list)) pdf.append(Paragraph('<seqReset id="%s" />' % li_uuid, styles['Normal'])) elif item_type in ['p'] or (item_type in ['div'] and 'captionedImage' in className or 'callout' in className or 'pullquote' in className): has_image = False # Pull images out of items and add before for img in item.findAll('img'): img.extract() src = img['src'].replace(self.site.absolute_url(), '') if src.startswith('/'): src = src.replace('/', '', 1) try: img_obj = self.site.restrictedTraverse(str(src)) except KeyError: continue has_image = True pdf_image = getImage(img_obj) pdf.append(pdf_image) # If we had an image, and the next paragraph has the # 'discreet' class (is a caption) then keep them together if has_image: s = item.findNextSiblings() if s and 'discreet' in s[0].get('class', ''): pdf[-1].keepWithNext = True # Get paragraph contents p_contents = getInlineContents(item) # Don't add anything if no contents. if not p_contents: pass elif 'callout' in className or 'pullquote' in className: pdf.append(Paragraph(p_contents, callout)) elif 'discreet' in className or 'captionedImage' in className: if len(pdf) and isinstance(pdf[-1], Image): pdf[-1].keepWithNext = True pdf.append(Paragraph(p_contents, discreet)) else: pdf.append(Paragraph(p_contents, styles["Normal"])) elif item_type in ['div']: for i in item.contents: pdf.extend(getContent(i)) elif item_type == 'blockquote': pdf.append(Paragraph(getItemText(item), blockquote)) else: pdf.append(Paragraph(getItemText(item), styles["Normal"])) elif isinstance(item, NavigableString): if item.strip(): pdf.append(Paragraph(item, styles["Normal"])) return pdf # ------------------------------------------------------------------------- # Main body of create PDF # ------------------------------------------------------------------------- # Get document attributes title = self.context.Title() desc = self.context.Description() text = self.context.getText() if isinstance(text, BaseUnit): if hasattr(text, 'raw'): text = text.raw else: text = '' # Number of columns column_count = 2 if hasattr(self.context, 'extension_publication_column_count'): column_count = getattr(self.context, 'extension_publication_column_count', '2') try: column_count = int(column_count) except: column_count = 2 # Grab the publication code publication_code = self.getPublicationCode() # Grab the publication series publication_series = self.getPublicationSeries() # Clean up text text = text.replace(' ', ' ') # Colors - Maybe have presets? #header_rgb = (0.42,0.56,0.07) #header_rgb = (0.12,0.18,0.30) # Blue #header_rgb = (0.33,0.57,0.31) # Green (too light) header_rgb = HexColor('#4B7D45') # Green (dark enough) # Callout Colors callout_background_rgb = HexColor('#F6F6F6') # Styles styles=getSampleStyleSheet() styles['Normal'].spaceBefore = 3 styles['Normal'].spaceAfter = 6 styles['Normal'].fontName = 'Times-Roman' # Series Heading styles.add(ParagraphStyle('SeriesHeading')) styles['SeriesHeading'].spaceBefore = 0 styles['SeriesHeading'].spaceAfter = 2 styles['SeriesHeading'].fontSize = 10 styles['SeriesHeading'].textColor = (0,0,0) styles['SeriesHeading'].leading = 13 styles['SeriesHeading'].fontName = 'Helvetica-Bold' styles['SeriesHeading'].textTransform = 'uppercase' styles['Heading1'].fontSize = 25 styles['Heading1'].fontName = 'Helvetica-Bold' styles['Heading1'].leading = 29 styles['Heading1'].spaceBefore = 2 styles['Heading1'].spaceAfter = 12 styles['Heading1'].textColor = header_rgb styles['Heading2'].allowWidows = 0 styles['Heading2'].fontName = 'Helvetica-Bold' styles['Heading2'].fontSize = 15 styles['Heading2'].leading = 18 styles['Heading2'].spaceAfter = 8 styles['Heading2'].spaceAfter = 2 styles['Heading2'].textColor = header_rgb styles['Heading3'].allowWidows = 0 styles['Heading3'].fontName = 'Helvetica-Bold' styles['Heading3'].fontSize = 12 styles['Heading3'].leading = 14 styles['Heading3'].spaceAfter = 4 styles['Heading3'].textColor = header_rgb styles['Heading4'].allowWidows = 0 styles['Heading4'].fontName = 'Helvetica-Bold' styles['Heading4'].fontSize = 10 styles['Heading4'].leading = 12 styles['Heading4'].spaceAfter = 6 styles['Heading4'].textColor = header_rgb th_cell = ParagraphStyle('TableHeading') th_cell.spaceBefore = 3 th_cell.spaceAfter = 6 th_cell.fontSize = 10 th_cell.fontName = 'Times-Bold' td_cell = ParagraphStyle('TableData') td_cell.spaceBefore = 3 td_cell.spaceAfter = 6 td_cell.fontSize = 10 td_cell.fontName = 'Times-Roman' td_cell_right = ParagraphStyle('TableDataRight') td_cell_right.spaceBefore = 3 td_cell_right.spaceAfter = 6 td_cell_right.fontSize = 10 td_cell_right.fontName = 'Times-Roman' td_cell_right.alignment = TA_RIGHT bullet_list = ParagraphStyle('BulletList') bullet_list.spaceBefore = 4 bullet_list.spaceAfter = 4 bullet_list.fontName = 'Times-Roman' bullet_list.bulletIndent = 5 bullet_list.leftIndent = 17 bullet_list.bulletFontSize = 12 blockquote = ParagraphStyle('Blockquote') blockquote.leftIndent = 12 blockquote.rightIndent = 8 blockquote.spaceAfter = 6 blockquote.fontName = 'Times-Roman' discreet = ParagraphStyle('Discreet') discreet.fontSize = 9 discreet.textColor = HexColor('#717171') discreet.spaceAfter = 12 discreet.spaceBefore = 1 callout = ParagraphStyle('Callout') callout.fontSize = 10 callout.textColor = header_rgb callout.spaceAfter = 20 callout.spaceBefore = 22 callout.backColor = callout_background_rgb callout.borderColor = header_rgb callout.borderWidth = 1 callout.borderPadding = (8, 12, 10, 12) callout.rightIndent = 15 callout.leftIndent = 15 statement = ParagraphStyle('Statement') statement.fontSize = 8 statement.fontName = 'Times-Roman' statement.spaceAfter = 5 statement.leading = 10 description = ParagraphStyle('Description') description.spaceBefore = 6 description.spaceAfter = 8 description.fontSize = 11 description.fontName = 'Helvetica-Bold' description.leading = 13 padded_image = ParagraphStyle('PaddedImage') padded_image.spaceBefore = 12 padded_image.spaceAfter = 12 single_line = ParagraphStyle('SingleLine') single_line.fontSize = 9 single_line.fontName = 'Times-Roman' single_line.spaceBefore = 0 single_line.spaceAfter = 0 single_line_cr = ParagraphStyle('SingleLineCR') single_line_cr.fontSize = 9 single_line_cr.fontName = 'Times-Roman' single_line_cr.spaceBefore = 0 single_line_cr.spaceAfter = 10 # Create document pdf_file = BytesIO() margin = 36 # Debug for formatting boundary showBoundary=0 doc = FactsheetDocTemplate(pdf_file,pagesize=letter, title=title, rightMargin=margin,leftMargin=margin, showBoundary=showBoundary, topMargin=margin,bottomMargin=margin) # Standard padding for document elements element_padding = 6 # Document image setttings max_image_width = doc.width/column_count-(3*element_padding) if column_count <= 1: max_image_width = doc.width/2-(3*element_padding) # Returns a reportlab image object based on a Plone image object def getImage(img_obj, scale=True, reader=False, width=max_image_width, style="", column_count=column_count, caption="", leadImage=False, hAlign=None, body_image=True): if not leadImage and body_image and column_count == 1: # Special case to make one column body images 66% of the page width = 1.33*width img_width = img_obj.width img_height = img_obj.height if scale and (img_width > width): img_height = (width/img_width)*img_height img_width = width if hasattr(img_obj, 'data'): if hasattr(img_obj.data, 'data'): img_data = BytesIO(img_obj.data.data) else: img_data = BytesIO(img_obj.data) elif hasattr(img_obj, '_data'): img_data = BytesIO(img_obj._data) else: img_data = BytesIO('') if reader: img = ImageReader(img_data) else: if caption or leadImage: img = ImageFigure(img_data, caption=caption, width=img_width, height=img_height, align="right", max_image_width=width, column_count=column_count) else: img = Image(img_data, width=img_width, height=img_height) if style: img.style = style if hAlign: img.hAlign = hAlign elif column_count == 1: img.hAlign = TA_LEFT else: img.hAlign = TA_CENTER return img #-------------- calculated coordinates/w/h extension_url_image = self.site.portal_skins.agcommon_images['extension-url.png'] extension_url_image_width = 0.5*max_image_width # Factsheet title title_lines = 3 publication_series_height = 0 if publication_series: # If series heading, only 2 title lines title_lines = 2 # One line for the series heading publication_series_height = styles['SeriesHeading'].spaceBefore + \ styles['SeriesHeading'].spaceAfter + \ styles['SeriesHeading'].leading title_height = styles['Heading1'].spaceBefore + \ styles['Heading1'].spaceAfter + \ (title_lines * styles['Heading1'].leading) + \ publication_series_height + element_padding # Penn State/Extension Footer Image footer_image_width = 222.0 # 72 points/inch * 3.125" footer_image = self.site.portal_skins.agcommon_images['extension-factsheet-footer.png'] footer_image_height = footer_image_width*(1.0*footer_image.height/footer_image.width) # Header and footer on first page def header_footer(canvas,doc): canvas.saveState() # Line under Title canvas.setStrokeColorRGB(0,0,0) line_y=doc.bottomMargin+doc.height-title_height canvas.line(doc.leftMargin+element_padding, line_y, doc.width+doc.leftMargin-element_padding, line_y) # Footer canvas.drawImage(getImage(footer_image, scale=False, reader=True), doc.leftMargin+element_padding, 72.0/2, width=footer_image_width, height=footer_image_height, preserveAspectRatio=True, mask='auto') canvas.restoreState() # Footer for pages 2 and after def footer(canvas,doc): canvas.saveState() canvas.setFont('Times-Roman',9) canvas.drawString(margin, 24, "Page %d" % doc.page) canvas.setFont('Times-Roman',9) canvas.drawRightString(doc.width+margin+element_padding, 24, title) canvas.restoreState() #Two Columns For First (title) page title_y = doc.bottomMargin + doc.height - title_height title_column_y = doc.bottomMargin+footer_image_height+element_padding title_column_height = title_y - title_column_y title_frame_title = Frame(doc.leftMargin, title_y, doc.width, title_height, id='title_title', showBoundary=showBoundary) title_frames = [title_frame_title] for i in range(0,column_count): lm = doc.leftMargin + i * (doc.width/column_count+element_padding) w = doc.width/column_count-element_padding title_frame = Frame(lm, title_column_y, w, title_column_height, id='title_col%d' % i, showBoundary=showBoundary) title_frames.append(title_frame) #Two Columns For remaining page other_frames = [] for i in range(0,column_count): lm = doc.leftMargin + i * (doc.width/column_count+element_padding) w = doc.width/column_count-element_padding other_frame = Frame(lm, doc.bottomMargin, w, doc.height, id='other_col%d' % i, showBoundary=showBoundary) other_frames.append(other_frame) title_template = PageTemplate(id="title_template", frames=title_frames,onPage=header_footer) other_template = PageTemplate(id="other_template", frames=other_frames,onPage=footer) doc.addPageTemplates([title_template,other_template]) doc.handle_nextPageTemplate("other_template") # --------------------------------------------------------------------- # Convert HTML to PDF (Magic goes here) # --------------------------------------------------------------------- # Soupify soup = BeautifulSoup(text) # This list holds the PDF elements pdf = [] # Series, page heading and description in top frame, then framebreak # into two columns. Optionally add the description to the body if the # flag is set. if publication_series: pdf.append(Paragraph(publication_series, styles['SeriesHeading'])) pdf.append(Paragraph(title, styles["Heading1"])) # Move to next frame pdf.append(FrameBreak()) if description: pdf.append(Paragraph(desc, description)) # If we're a news item, append the date if self.context.portal_type in ['News Item']: pdf.append(Paragraph('Posted: %s' % self.context.getEffectiveDate().strftime('%B %d, %Y'), discreet)) # Lead Image and caption as first elements. Not doing News Item image. (IMAGE_FIELD_NAME, IMAGE_CAPTION_FIELD_NAME) = getImageAndCaptionFieldNames(self.context) leadImage_field = self.context.getField(IMAGE_FIELD_NAME) leadImage_caption_field = self.context.getField(IMAGE_CAPTION_FIELD_NAME) show_leadimage = getattr(self.context, 'show_leadimage_context', True) if show_leadimage and leadImage_field and leadImage_caption_field: leadImage = leadImage_field.get(self.context) leadImage_caption = leadImage_caption_field.get(self.context) if leadImage and leadImage.get_size(): if column_count == 1: pdf.append(getImage(leadImage, caption=leadImage_caption, leadImage=True)) else: pdf.append(getImage(leadImage)) if leadImage_caption: pdf.append(Paragraph(leadImage_caption, discreet)) # portal_transforms will let us convert HTML into plain text portal_transforms = getToolByName(self.context, 'portal_transforms') # Equivalent PDF paragraph styles for HTML tag_to_style = { 'h2' : 'Heading2', 'h3' : 'Heading3', 'h4' : 'Heading4', 'h5' : 'Heading5', 'h6' : 'Heading6', 'p' : 'Normal' } # Push headings to the smallest level # If we have an h2, but not an h3 or h4, bump the heading styles down. attrs = ['allowWidows', 'fontName', 'fontSize', 'leading', 'spaceAfter', 'textColor', ] bump_headings = False if '<h2' in text and not '<h3' in text and not '<h4' in text: bump_headings = True heading_tags = sorted([x for x in tag_to_style.keys() if x.startswith('h')]) for i in range(0, len(heading_tags) - 1): from_style = tag_to_style[heading_tags[i]] to_style = tag_to_style[heading_tags[i+1]] for a in attrs: styles[from_style].__dict__[a] = styles[to_style].__dict__[a] # Loop through Soup contents for item in soup.contents: pdf.extend(getContent(item, bump_headings=bump_headings)) # Embed lead images in paragraphs if we're a single column if column_count == 1: for i in range(1,len(pdf)-1): if isinstance(pdf[i], ImageFigureBase): paragraphs = [] for j in range(i+1, len(pdf)-1): if isinstance(pdf[j], Paragraph) or isinstance(pdf[j], HRFlowable): paragraphs.append(pdf[j]) pdf[j] = None else: break if paragraphs: pdf[i].hAlign="RIGHT" img_paragraph = ImageAndFlowables(pdf[i], paragraphs,imageLeftPadding=element_padding) pdf[i] = img_paragraph while None in pdf: pdf.remove(None) # Contributors (as Contact Information) %%% contributors_viewlet = getMultiAdapter((self.context, self.request, self), name='agcommon.contributors') contributors_people = contributors_viewlet.people if contributors_people: # Adding h2 this way so as to take advantage of the underline and the # bump_headings parameter heading = Tag(BeautifulSoup(), 'h2') heading.insert(0, 'Contact Information') pdf.extend(getContent(heading, bump_headings=bump_headings)) for person in contributors_viewlet.people: if person.get('url'): person_name = Paragraph("""<b><a color="blue" href="%(url)s">%(name)s</a></b>""" % person, single_line) else: person_name = Paragraph("""<b>%(name)s</b>""" % person, single_line) person_name.keepWithNext = True person_title = Paragraph("""%(title)s""" % person, single_line) person_title.keepWithNext = True person_email = Paragraph("""<a color="blue" href="mailto:%(email)s">%(email)s</a>""" % person, single_line) person_email.keepWithNext = True person_phone = Paragraph("""%(phone)s""" % person, single_line_cr) pdf.append(person_name) pdf.append(person_title) pdf.append(person_email) pdf.append(person_phone) # All done with contents, appending line and statement pdf.append(HRFlowable(width='100%', spaceBefore=4, spaceAfter=4)) # Extension logo pdf.append(getImage(extension_url_image, scale=True, width=extension_url_image_width, style=padded_image, hAlign='LEFT', body_image=False)) # Choose which statement aa_statement = """Penn State is an equal opportunity, affirmative action employer, and is committed to providing employment opportunities to all qualified applicants without regard to race, color, religion, age, sex, sexual orientation, gender identity, national origin, disability or protected veteran status.""" statement_text = ("""Penn State College of Agricultural Sciences research and extension programs are funded in part by Pennsylvania counties, the Commonwealth of Pennsylvania, and the U.S. Department of Agriculture. Where trade names appear, no discrimination is intended, and no endorsement by Penn State Extension is implied. <b>This publication is available in alternative media on request.</b> %s © The Pennsylvania State University %d """ % (aa_statement, DateTime().year())).split("\n") # Append the publication code, if it exists if publication_code: statement_text.append("Code: %s" % publication_code) # Create paragraphs from the statement text for s in statement_text: if s.strip(): pdf.append(Paragraph(s, statement)) # Create PDF - multibuild instead of build for table of contents # functionality doc.multiBuild(pdf) #doc.build(pdf) # Pull PDF binary bits into variable, close file handle and return pdf_value = pdf_file.getvalue() pdf_file.close() return pdf_value
def _test0(self): "This makes one long multi-page paragraph." # Build story. story = [] a = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet["Heading1"] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet["Heading2"] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet["Heading3"] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet["BodyText"] a( Paragraph( """ Subsequent pages test pageBreakBefore, frameBreakBefore and keepTogether attributes. Generated at %s. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % (time.ctime(time.time()), len(story)), bt, ) ) for i in xrange(10): a(Paragraph("Heading 1 always starts a new page (%d)" % len(story), h1)) for j in xrange(3): a( Paragraph( "Heading1 paragraphs should always" "have a page break before. Heading 2 on the other hand" "should always have a FRAME break before (%d)" % len(story), bt, ) ) a(Paragraph("Heading 2 always starts a new frame (%d)" % len(story), h2)) a( Paragraph( "Heading1 paragraphs should always" "have a page break before. Heading 2 on the other hand" "should always have a FRAME break before (%d)" % len(story), bt, ) ) for j in xrange(3): a(Paragraph(randomText(theme=PYTHON, sentences=2) + " (%d)" % len(story), bt)) a(Paragraph("I should never be at the bottom of a frame (%d)" % len(story), h3)) a(Paragraph(randomText(theme=PYTHON, sentences=1) + " (%d)" % len(story), bt)) a(Paragraph("Now we do <br/> tests", h1)) a(Paragraph("First off no br tags", h3)) a(Paragraph(_text1, bt)) a(Paragraph("<br/> after 'the' in line 4", h3)) a(Paragraph(_text1.replace("forms of the", "forms of the<br/>", 1), bt)) a(Paragraph("2*<br/> after 'the' in line 4", h3)) a(Paragraph(_text1.replace("forms of the", "forms of the<br/><br/>", 1), bt)) a(Paragraph("<br/> after 'I suggested ' in line 5", h3)) a(Paragraph(_text1.replace("I suggested ", "I suggested<br/>", 1), bt)) a(Paragraph("2*<br/> after 'I suggested ' in line 5", h3)) a(Paragraph(_text1.replace("I suggested ", "I suggested<br/><br/>", 1), bt)) a(Paragraph("<br/> at the end of the paragraph!", h3)) a(Paragraph("""text one<br/>text two<br/>""", bt)) a(Paragraph("Border with <nr/> at the end of the paragraph!", h3)) bt1 = ParagraphStyle("bodyText1", bt) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor("red") bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""", bt1)) a(Paragraph("Border no <nr/> at the end of the paragraph!", h3)) bt1 = ParagraphStyle("bodyText1", bt) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor("red") bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two""", bt1)) a(Paragraph("Different border style!", h3)) bt2 = ParagraphStyle("bodyText1", bt1) bt2.borderWidth = 1.5 bt2.borderColor = colors.toColor("blue") bt2.backColor = colors.gray bt2.borderRadius = 3 bt2.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""", bt2)) doc = MyDocTemplate(outputfile("test_platypus_breaking.pdf")) doc.multiBuild(story)
def HistoriaPDF(request,dni): global c,dy historia=Historia.objects.filter(numeroHistoria=dni) width,height =A4 response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=Historial_'+""+historia[0].numeroHistoria.__str__()+""+'.pdf' buffer = BytesIO() c = canvas.Canvas(buffer,pagesize=A4) #Cabecera__________________________________________ c.setLineWidth(.3) c.setFont('Helvetica',20) c.drawString(185,750,'HISTORIA CLÍNICA') c.setFont('Helvetica',15) c.drawString(425, 765, 'N° HISTORIA') c.setFont('Helvetica',28) c.drawString(402,710,historia[0].numeroHistoria.__str__()) c.drawImage("apps/Laboratorio/static/Unsa.png",60,700,width=85, height=110, mask='auto') c.line(40,695,550,695) c.line(40,820,550,820) c.line(40,695,40,820) c.line(165,695,165,820) c.line(395,695,395,820) c.line(550,695,550,820) c.line(395,750,550,750) #Cabecera_____________________________________________ #nombre c.setFont('Helvetica', 13) c.drawString(60,650,'Apellidos y Nombres') c.setFont('Helvetica', 13) c.drawString(230,650,historia[0].nombres.__str__()+" "+historia[0].apellido_paterno.__str__()+" "+historia[0].apellido_materno.__str__()) c.line(40,665,550,665) c.line(40,645,550,645) c.line(220,645,220,665) c.line(40,645,40,665) c.line(550,645,550,665) #nombre #fecha c.drawString(70,610,'Fecha de Nacimiento') c.drawString(90,590,historia[0].fechaNac.__str__()) c.drawString(340,610,'Lugar de Nacimiento') c.drawString(350,590,historia[0].lugarNac.__str__()) c.line(40,625,550,625) c.line(40,605,550,605) c.line(40,585,550,585) c.line(40,585,40,625) c.line(265,585,265,625) c.line(550,585,550,625) #fecha #DNI c.drawString(125,550,'DNI') c.drawString(105,530,historia[0].dni.__str__()) c.drawString(270,550,'Edad') c.drawString(275,530,str(historia[0].edad())) c.drawString(425,550,'Distrito') c.drawString(410,530,historia[0].distrito.__str__()) c.line(40,565,550,565) c.line(40,545,550,545) c.line(40,525,550,525) c.line(40,525,40,565) c.line(220,525,220,565) c.line(350,525,350,565) c.line(550,525,550,565) #Direccion-Distrito c.drawString(250,490,'Dirección') c.drawString(50,470,historia[0].direccion.__str__()) c.line(40,505,550,505) c.line(40,485,550,485) c.line(40,465,550,465) c.line(40,465,40,505) c.line(550,465,550,505) c.setFont('Helvetica',12) #Sexo EstadoCivil Profesión/Ocupación Teléfono c.drawString(50,430,'Sexo') c.drawString(50,410,historia[0].sexo.__str__()) c.drawString(140,430,'Estado Civil') c.drawString(140,410,historia[0].estadoCivil.__str__()) c.drawString(260,430,'Profesión/Ocupación ') c.drawString(260,410,historia[0].ocupacion.__str__()) c.drawString(425,430,'Teléfono') if historia[0].celular == None: c.drawString(425,410,historia[0].telefono.__str__()) else : c.drawString(425,410,historia[0].celular.__str__()) c.line(40,445,550,445) c.line(40,425,550,425) c.line(40,405,550,405) c.line(40,405,40,445) c.line(135,405,135,445) c.line(255,405,255,445) c.line(415,405,415,445) c.line(550,405,550,445) #GRADO de institucion Procedencia c.drawString(70,370,'Grado de Instrucción') c.drawString(50,350,historia[0].gradoInstruccion.__str__()) c.drawString(350,370,'Procedencia') c.drawString(335,350,historia[0].procedencia.__str__()) c.line(40,385,550,385) c.line(40,365,550,365) c.line(40,345,550,345) c.line(40,345,40,385) c.line(265,345,265,385) c.line(550,345,550,385) #Edad y Fecha de Apertura c.drawString(250,310,'Fecha de Apertura') c.drawString(260,290,historia[0].fechaReg.__str__()) c.line(40,325,550,325) c.line(40,305,550,305) c.line(40,285,550,285) c.line(40,285,40,325) c.line(550,285,550,325) # Close the PDF object cleanly. c.showPage() cita = Cita.objects.filter(numeroHistoria=historia[0].id) p = ParagraphStyle('test') p.textColor = 'black' p.borderColor = 'white' p.alignment = TA_CENTER p.borderWidth = 1 p.fontSize = 9 dy=800 count=0 if (cita!=None): for citas in cita: triaje=Triaje.objects.filter(cita=citas.id) if triaje.count()>0: consulta=Consulta.objects.filter(pk=triaje[0].id.__str__())#Filtro de consultas por el id de triaje if triaje.count()>0 and consulta.count()>0: imprimirTriaje(p,triaje[0]) imprimirConsulta(p,consulta[0]) dibujarBorde() count=count+1 if count==4: c.showPage() dy=800 dy=dy-23 c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def pdf(comprobante, total, emisor, receptor, conceptos, timbrado, nomina): from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from reportlab.lib.units import cm from reportlab.platypus import Table, TableStyle, Spacer from reportlab.lib import colors from reportlab.platypus.flowables import Image from reportlab.lib.styles import ParagraphStyle from reportlab.platypus import Paragraph from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT from cStringIO import StringIO from reportlab.platypus import SimpleDocTemplate from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.shapes import Drawing from reportlab.lib.colors import Color from reportlab.lib.utils import ImageReader def AllPageSetup(canvas, doc): canvas.saveState() logo_marca_agua = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/logo_20_transparente.png') canvas.drawImage(logo_marca_agua, 130, 250, width=350, height=380, mask='auto') logo_header = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/inmegen_logo_color01.png') canvas.drawImage(logo_header, 30, 717, width=151, height=70, mask='auto') # canvas.setFillGray(gray) canvas.restoreState() def PrimerPaginaSetup(canvas, doc): diferencia = 45 extra = 15 logo_marca_agua = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/logo_20_transparente.png') canvas.drawImage(logo_marca_agua, 130, 250, width=350, height=380, mask='auto') logo_header = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/inmegen_logo_color01.png') canvas.drawImage(logo_header, 30, 717, width=151, height=70, mask='auto') canvas.saveState() canvas.drawString(370, 780-diferencia+extra, "Periodo de pago "+nomina["@FechaInicialPago"]+" "+nomina["@FechaFinalPago"]) canvas.drawString(30, 750-diferencia, emisor["@nombre"]) canvas.drawString(30, 735-diferencia, emisor["@rfc"]) canvas.drawString(445, 756-diferencia+extra, conceptos["cfdi:Concepto"]["@descripcion"]) canvas.drawString(435, 725-diferencia+extra, 'Total Neto:') canvas.drawString(500, 725-diferencia+extra, "${:,.2f}".format(float(total))) canvas.line(495, 723-diferencia+extra, 580, 723-diferencia+extra) canvas.drawString(30, 703-diferencia+extra, 'Nombre del empleado:') canvas.drawString(160, 703-diferencia+extra, receptor["@nombre"]) canvas.line(160, 700-diferencia+extra, 580, 700-diferencia+extra) canvas.drawString(30, 680-diferencia+extra, 'R.F.C:') canvas.drawString(160, 680-diferencia+extra, receptor["@rfc"]) canvas.line(160, 677-diferencia+extra, 270, 677-diferencia+extra) canvas.drawString(280, 680-diferencia+extra, 'C.U.R.P:') canvas.drawString(330, 680-diferencia+extra, nomina["@CURP"]) canvas.line(330, 677-diferencia+extra, 580, 677-diferencia+extra) canvas.drawString(30, 660-diferencia+extra, "CLABE:") canvas.drawString(160, 660-diferencia+extra, nomina.get("@CLABE", "SIN CLABE")) canvas.line(160, 657-diferencia+extra, 580, 657-diferencia+extra) canvas.drawString(30, 640-diferencia+extra, "Denominación del puesto:") canvas.drawString(170, 640-diferencia+extra, nomina["@Puesto"]) canvas.line(170, 637-diferencia+extra, 580, 637-diferencia+extra) canvas.drawString(30, 620-diferencia+extra, "Adscripción:") canvas.drawString(160, 620-diferencia+extra, nomina["@Departamento"]) canvas.line(160, 617-diferencia+extra, 580, 617-diferencia+extra) canvas.drawString(30, 600-diferencia+extra, "Folio Fiscal:") canvas.drawString(150, 600-diferencia+extra, timbrado["@UUID"]) canvas.line(150, 597-diferencia+extra, 390, 597-diferencia+extra) canvas.drawString(400, 600-diferencia+extra, "Timbrado:") canvas.drawString(460, 600-diferencia+extra, timbrado["@FechaTimbrado"]) canvas.line(455, 597-diferencia+extra, 580, 597-diferencia+extra) if False: canvas.drawString(30, 580-diferencia+extra, "Tipo de Contrato:") canvas.drawString(160, 580-diferencia+extra, nomina["@TipoContrato"]) canvas.line(160, 577-diferencia+extra, 390, 577-diferencia+extra) canvas.drawString(400, 580-diferencia+extra, u"Número de días pagados:") canvas.drawString(540, 580-diferencia+extra, "{:,d}".format(int(float(nomina["@NumDiasPagados"])))) canvas.line(540, 577-diferencia+extra, 580, 577-diferencia+extra) canvas.restoreState() class InfoCanvas(canvas.Canvas): def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self._saved_page_states = [] def showPage(self): self.basic_data() self._saved_page_states.append(dict(self.__dict__)) self._startPage() def basic_data(self): canvas = self canvas.setLineWidth(.3) canvas.setFont('Helvetica', 11) diferencia = 45 extra = 15 def save(self): """add page info to each page (page x of y)""" num_pages = len(self._saved_page_states) for state in self._saved_page_states: self.__dict__.update(state) #self.draw_page_number(num_pages) canvas.Canvas.showPage(self) canvas.Canvas.save(self) buffer_ = StringIO() doc = SimpleDocTemplate(buffer_, pagesize=letter) elements = [Spacer(0, 6.1*cm)]# esto baja o sube la tabla de percepciones y deducciones pg = ParagraphStyle('table_title') pg.alignment = TA_CENTER percepciones = nomina["nomina:Percepciones"] deducciones = nomina["nomina:Deducciones"] table = Table([[Paragraph("Percepciones", pg), Paragraph("Deducciones", pg)]], colWidths=275, rowHeights=15) table.setStyle(TableStyle([ ('INNERGRID', (0,0), (0,0), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), # ('BACKGROUND',(0,0),(-1,2), colors.white) ])) elements.append(table) p_text = ParagraphStyle('text') p_text.alignment = TA_LEFT p_text.fontSize = 7 p_text.borderColor = 'black' p_text.borderWidth = 0 p_text.textColor = 'black' p_money = ParagraphStyle('money') p_money.alignment = TA_RIGHT p_money.fontSize = 7 p_money.borderColor = 'black' p_money.borderWidth = 0 p_money.textColor = 'black' percepciones_data = [] if not isinstance(percepciones["nomina:Percepcion"], list): percepciones["nomina:Percepcion"] = [percepciones["nomina:Percepcion"]] #print(percepciones["nomina:Percepcion"]) for p in percepciones["nomina:Percepcion"]: percepciones_data.append([ Paragraph(p["@Clave"]+" "+p["@Concepto"], p_text), Paragraph("${:,.2f}".format(float(p["@ImporteGravado"])), p_money)]) deducciones_data = [] if not isinstance(deducciones["nomina:Deduccion"], list): deducciones["nomina:Deduccion"] = [deducciones["nomina:Deduccion"]] #print(deducciones["nomina:Deduccion"]) for p in deducciones["nomina:Deduccion"]: importe_exento = float(p["@ImporteExento"]) importe_gravado = float(p["@ImporteGravado"]) importe = importe_gravado if importe_gravado > 0 else importe_exento deducciones_data.append([ Paragraph(p["@Clave"]+" "+p["@Concepto"], p_text), Paragraph("${:,.2f}".format(importe), p_money)]) if len(percepciones_data) < len(deducciones_data): for e in range(len(deducciones_data) - len(percepciones_data)): percepciones_data.append([ Paragraph("", p_text), Paragraph("", p_text)]) elif len(deducciones_data) < len(percepciones_data): for e in range(len(percepciones_data) - len(deducciones_data)): deducciones_data.append([ Paragraph("", p_text), Paragraph("", p_text)]) data = [] total_deducciones_exento = float(deducciones["@TotalExento"]) total_deducciones_gravado = float(deducciones["@TotalGravado"]) total_importe_deducciones = total_deducciones_gravado\ if total_deducciones_gravado > 0 else total_deducciones_exento data.append([ Paragraph("Total:", p_text), Paragraph("<b>${:,.2f}</b>".format(float(percepciones["@TotalGravado"])), p_money), Paragraph("Total:", p_text), Paragraph("<b>${:,.2f}</b>".format(total_importe_deducciones), p_money)]) for row1, row2 in zip(percepciones_data, deducciones_data): data.append(row1 + row2) table = Table(data, colWidths=(220, 50, 220, 50), rowHeights=15) table.setStyle(TableStyle([ ('INNERGRID', (0,0), (0,0), 0.5, colors.white), # ('BOX', (0,0), (-1,-1), 0.5, colors.white), # ('BACKGROUND',(0,0),(-1,2), colors.white) ])) elements.append(Spacer(0, 0.5*cm)) elements.append(table) qr_data = "?re={rfc_emisor}&rr={rfc_receptor}&tt={total}&id={folio_fiscal}".format( rfc_emisor=emisor["@rfc"], rfc_receptor=receptor["@rfc"], total=total, folio_fiscal=timbrado["@UUID"] ) io = StringIO() qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=3, border=1, ) qr.add_data(qr_data) qr.make(fit=True) p_text_g = ParagraphStyle('text') p_text_g.alignment = TA_LEFT p_text_g.fontSize = 10 p_text_g.borderColor = 'black' p_text_g.borderWidth = 0 p_text_g.textColor = 'black' img = qr.make_image() img.save(io) data = [ [Paragraph("<b>Sello digital CFDI</b>", p_text_g), Image(io)], [Paragraph(timbrado["@selloCFD"], p_text_g)], [Paragraph("<b>Sello del SAT</b>", p_text_g)], [Paragraph(timbrado["@selloSAT"], p_text_g)]] table = Table(data, colWidths=(400, 150), rowHeights=(20, 50, 20, 80)) table.setStyle(TableStyle([ # ('INNERGRID', (0,0), (-1,-1), 0.5, colors.black), # ('BOX', (0,0), (-1,-1), 0.5, colors.black), ('SPAN',(1,0),(-1,-1)), # ('BACKGROUND',(0,0),(-1,2), colors.white), ('ALIGN', (1,0), (-1,-1), 'RIGHT') ])) elements.append(Spacer(0, .5*cm)) elements.append(table) data = [[Paragraph("<b>Metodo de pago</b>", p_text), Paragraph(comprobante["cfdi:Comprobante"]["@metodoDePago"], p_text), Paragraph("<b>Condiciones de pago</b>", p_text), Paragraph(comprobante["cfdi:Comprobante"]["@formaDePago"], p_text)]] table = Table(data)#, colWidths=550, rowHeights=40) table.setStyle(TableStyle([ ('VALIGN', (0,0), (-1,-1), 'TOP'), #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), #('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) elements.append(Spacer(0, .5*cm)) elements.append(table) #lab = Label() #lab.setOrigin(300, 400) #lab.boxAnchor = 'ne' #lab.angle = 45 #lab.dx = 0 #lab.dy = -20 #lab.fontSize = 60 #lab.fillColor = Color(red=0, green=0, blue=0, alpha=.5) #lab.setText(u'Este recibo está\nen proceso de revisión') #d = Drawing(200, 10) #d.add(lab) #elements.append(d) doc.build(elements, canvasmaker=InfoCanvas, onFirstPage=PrimerPaginaSetup, onLaterPages=AllPageSetup) pdf = buffer_.getvalue() buffer_.close() return pdf
def makeStory(): story = [] a = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet['Heading2'] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet['Heading3'] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet['BodyText'] btj = ParagraphStyle('bodyText1j', parent=bt, alignment=TA_JUSTIFY) btr = ParagraphStyle('bodyText1r', parent=bt, alignment=TA_RIGHT) btc = ParagraphStyle('bodyText1c', parent=bt, alignment=TA_CENTER) from reportlab.lib.utils import TimeStamp ts = TimeStamp() a( Paragraph( """ <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and keepTogether attributes. Generated at %s. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % (ts.asctime, len(story)), bt)) for i in range(10): a( Paragraph( 'Heading 1 always starts a new page (%d)' % len(story), h1)) for j in range(3): a( Paragraph( 'Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) a( Paragraph( 'Heading 2 always starts a new frame (%d)' % len(story), h2)) a( Paragraph( 'Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) for j in range(3): a( Paragraph( RT((i, j, 0), theme=PYTHON, sentences=2) + ' (%d)' % len(story), bt)) a( Paragraph( 'I should never be at the bottom of a frame (%d)' % len(story), h3)) a( Paragraph( RT((i, j, 1), theme=PYTHON, sentences=1) + ' (%d)' % len(story), bt)) for align, bts in [('left', bt), ('JUSTIFIED', btj), ('RIGHT', btr), ('CENTER', btc)]: a(Paragraph('Now we do <br/> tests(align=%s)' % align, h1)) a(Paragraph('First off no br tags', h3)) a(Paragraph(_text1, bts)) a(Paragraph("<br/> after 'the' in line 4", h3)) a( Paragraph( _text1.replace('forms of the', 'forms of the<br/>', 1), bts)) a(Paragraph("2*<br/> after 'the' in line 4", h3)) a( Paragraph( _text1.replace('forms of the', 'forms of the<br/><br/>', 1), bts)) a(Paragraph("<br/> after 'I suggested ' in line 5", h3)) a( Paragraph( _text1.replace('I suggested ', 'I suggested<br/>', 1), bts)) a(Paragraph("2*<br/> after 'I suggested ' in line 5", h3)) a( Paragraph( _text1.replace('I suggested ', 'I suggested<br/><br/>', 1), bts)) a(Paragraph("<br/> at the end of the paragraph!", h3)) a(Paragraph("""text one<br/>text two<br/>""", bts)) a( Paragraph( "Border with <br/> at the end of the paragraph!", h3)) bt1 = ParagraphStyle('bodyText1', bts) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor('red') bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""", bt1)) a( Paragraph("Border no <br/> at the end of the paragraph!", h3)) bt1 = ParagraphStyle('bodyText1', bts) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor('red') bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two""", bt1)) a(Paragraph("Different border style!", h3)) bt2 = ParagraphStyle('bodyText1', bt1) bt2.borderWidth = 1.5 bt2.borderColor = colors.toColor('blue') bt2.backColor = colors.gray bt2.borderRadius = 3 bt2.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""", bt2)) for i in 0, 1, 2: P = Paragraph( """This is a paragraph with <font color='blue'><a href='#top'>with an incredibly long and boring link in side of it that contains lots and lots of stupidly boring and worthless information. So that we can split the link and see if we get problems like Dinu's. I hope we don't, but you never do Know.</a></font>""", bt) a(P) return story
self.xoffset = xoffset def wrap(self, *args): return (self.xoffset, 0) def draw(self): canvas = self.canv canvas.drawImage("centre2_8000_rotated.jpg", -10,-260, width=400,height=280) # Create the styles for the document logoStyle = ParagraphStyle('normal') logoStyle.fontSize=16 logoStyle.leading=15 logoStyle.rightindent=5 logoStyle.backColor='grey' #logoStyle.textColor='white' logoStyle.borderWidth=5 logoStyle.borderColor='grey' rightStyle = ParagraphStyle('normal') rightStyle.alignment = TA_RIGHT rightStyle.spaceBefore = 10 paraStyle = ParagraphStyle('normal') paraStyle.spaceAfter = 10 paraStyle.alignment = TA_JUSTIFY medStyle = ParagraphStyle('normal') medStyle.fontSize = 8 medStyle.leading = 8 medStyle.spaceAfter = 10 medStyle.alignment = TA_JUSTIFY
def _test0(self): "This makes one long multi-page paragraph." # Build story. story = [] a = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet['Heading2'] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet['Heading3'] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet['BodyText'] btj = ParagraphStyle('bodyText1j',parent=bt,alignment=TA_JUSTIFY) btr = ParagraphStyle('bodyText1r',parent=bt,alignment=TA_RIGHT) btc = ParagraphStyle('bodyText1c',parent=bt,alignment=TA_CENTER) a(Paragraph(""" <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and keepTogether attributes. Generated at %s. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % ( time.ctime(time.time()), len(story)), bt)) for i in range(10): a(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1)) for j in range(3): a(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) a(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2)) a(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) for j in range(3): a(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt)) a(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3)) a(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt)) for align,bts in [('left',bt),('JUSTIFIED',btj),('RIGHT',btr),('CENTER',btc)]: a(Paragraph('Now we do <br/> tests(align=%s)' % align, h1)) a(Paragraph('First off no br tags',h3)) a(Paragraph(_text1,bts)) a(Paragraph("<br/> after 'the' in line 4",h3)) a(Paragraph(_text1.replace('forms of the','forms of the<br/>',1),bts)) a(Paragraph("2*<br/> after 'the' in line 4",h3)) a(Paragraph(_text1.replace('forms of the','forms of the<br/><br/>',1),bts)) a(Paragraph("<br/> after 'I suggested ' in line 5",h3)) a(Paragraph(_text1.replace('I suggested ','I suggested<br/>',1),bts)) a(Paragraph("2*<br/> after 'I suggested ' in line 5",h3)) a(Paragraph(_text1.replace('I suggested ','I suggested<br/><br/>',1),bts)) a(Paragraph("<br/> at the end of the paragraph!",h3)) a(Paragraph("""text one<br/>text two<br/>""",bts)) a(Paragraph("Border with <br/> at the end of the paragraph!",h3)) bt1 = ParagraphStyle('bodyText1',bts) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor('red') bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""",bt1)) a(Paragraph("Border no <br/> at the end of the paragraph!",h3)) bt1 = ParagraphStyle('bodyText1',bts) bt1.borderWidth = 0.5 bt1.borderColor = colors.toColor('red') bt1.backColor = colors.pink bt1.borderRadius = 2 bt1.borderPadding = 3 a(Paragraph("""text one<br/>text two""",bt1)) a(Paragraph("Different border style!",h3)) bt2 = ParagraphStyle('bodyText1',bt1) bt2.borderWidth = 1.5 bt2.borderColor = colors.toColor('blue') bt2.backColor = colors.gray bt2.borderRadius = 3 bt2.borderPadding = 3 a(Paragraph("""text one<br/>text two<br/>""",bt2)) for i in 0, 1, 2: P = Paragraph("""This is a paragraph with <font color='blue'><a href='#top'>with an incredibly long and boring link in side of it that contains lots and lots of stupidly boring and worthless information. So that we can split the link and see if we get problems like Dinu's. I hope we don't, but you never do Know.</a></font>""",bt) a(P) doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf')) doc.multiBuild(story)
def addPara(self, force=False): # Cleanup the trail for frag in reversed(self.fragList): frag.text = frag.text.rstrip() if frag.text: break if force or (self.text.strip() and self.fragList): # Strip trailing whitespaces #for f in self.fragList: # f.text = f.text.lstrip() # if f.text: # break #self.fragList[-1].lineBreak = self.fragList[-1].text.rstrip() # Update paragraph style by style of first fragment first = self.fragBlock style = ParagraphStyle('default%d' % self.UID(), keepWithNext=first.keepWithNext) style.fontName = first.fontName style.fontSize = first.fontSize style.leading = max(first.leading, first.fontSize * 1.25) style.backColor = first.backColor style.spaceBefore = first.spaceBefore style.spaceAfter = first.spaceAfter style.leftIndent = first.leftIndent style.rightIndent = first.rightIndent style.firstLineIndent = first.firstLineIndent style.alignment = first.alignment style.bulletFontName = first.fontName style.bulletFontSize = first.fontSize style.bulletIndent = first.bulletIndent style.borderWidth = max(first.borderLeftWidth, first.borderRightWidth, first.borderTopWidth, first.borderBottomWidth) style.borderPadding = first.borderPadding # + first.borderWidth style.borderColor = first.borderTopColor # borderRadius: None, # print repr(self.text.strip()), style.leading, "".join([repr(x.text) for x in self.fragList]) # print first.leftIndent, first.listStyleType,repr(self.text) # Add paragraph to story para = PmlParagraph(self.text, style, frags=self.fragAnchor + self.fragList, bulletText=copy.copy(first.bulletText)) para.outline = frag.outline para.outlineLevel = frag.outlineLevel para.outlineOpen = frag.outlineOpen self.addStory(para) self.fragAnchor = [] first.bulletText = None self.clearFrag()