def print_cards(): #LETTER = (8.5, 11) LETTER = (11, 8.5) DPI = 72 # Set print margins MARGIN = 0.5 x_offset = int(MARGIN * DPI) y_offset = int(MARGIN * DPI) CARDSIZE = (int(2.49 * DPI), int(3.48 * DPI)) #scale = CARDSIZE[0] / 375.0 # Default cardsize in px cards = convert_to_cards(session['cardtext']) byte_io = BytesIO() from reportlab.pdfgen import canvas canvas = canvas.Canvas(byte_io, pagesize=landscape(letter)) WIDTH, HEIGHT = landscape(letter) #draw = ImageDraw.Draw(sheet) for card in cards: image = create_card_img(card,session["do_google"]) image_reader = ImageReader(image) canvas.drawImage(image_reader, x_offset, y_offset, width=CARDSIZE[0], height=CARDSIZE[1]) x_offset += CARDSIZE[0] + 5 # 5 px border around cards if x_offset + CARDSIZE[0] > LETTER[0] * DPI: x_offset = int(MARGIN * DPI) y_offset += CARDSIZE[1] + 5 if y_offset + CARDSIZE[1] > LETTER[1] * DPI: x_offset = int(MARGIN * DPI) y_offset = int(MARGIN * DPI) canvas.showPage() canvas.save() byte_io.seek(0) return send_file(byte_io, mimetype='application/pdf')
def __init__(self, buffer, pagesize): self.buffer = buffer if pagesize == 'A4': self.pagesize = landscape(A4) elif pagesize == 'Letter': self.pagesize = landscape(letter) self.width, self.height = self.pagesize
def drawCalendarPage(c, year, month): width = landscape(A4)[0] - 20*mm height = landscape(A4)[1] - 20*mm # leave 1cm margin on page drawable_h = height - titlesize - 5*mm c.translate(10*mm, 10*mm) # draw rounded background rect c.saveState() c.setStrokeColor(framefgcolor) c.setFillColor(framebgcolor) c.roundRect(0, 0, width, drawable_h, 5*mm, fill=1) c.restoreState() # place header 5mm from the left/right border sides c.saveState() c.translate(5*mm, height - titlesize) drawHeader(c, year, month, width - 10*mm, titlesize) c.restoreState() # draw grid with a 5mm margin to the border c.saveState() c.translate(5*mm, 5*mm) drawGrid(c, year, month, width - 10*mm, drawable_h - 10*mm) c.restoreState() # show the page c.showPage() return
def conpdf(f_jpg): f_pdf = filename+'.pdf' (w, h) = landscape(A4) c = canvas.Canvas(f_pdf, pagesize = landscape(A4)) c.drawImage(f, 0, 0, w, h) c.save() print "okkkkkkkk."
def __init__(self, doc=None, story=None, pagesize = 'A4', printLandscape=False, title=None): if doc: self._doc = doc else: #create a new document #As the constructor of SimpleDocTemplate can take only a filename or a file object, #to keep the PDF data not in a file, we use a dummy file object which save the data in a string self._fileDummy = FileDummy() if printLandscape: self._doc = SimpleDocTemplate(self._fileDummy, pagesize = landscape(PDFSizes().PDFpagesizes[pagesize])) else: self._doc = SimpleDocTemplate(self._fileDummy, pagesize = PDFSizes().PDFpagesizes[pagesize]) if title is not None: self._doc.title = title if story is not None: self._story = story else: #create a new story with a spacer which take all the first page #then the first page is only drawing by the firstPage method self._story = [PageBreak()] if printLandscape: self._PAGE_HEIGHT = landscape(PDFSizes().PDFpagesizes[pagesize])[1] self._PAGE_WIDTH = landscape(PDFSizes().PDFpagesizes[pagesize])[0] else: self._PAGE_HEIGHT = PDFSizes().PDFpagesizes[pagesize][1] self._PAGE_WIDTH = PDFSizes().PDFpagesizes[pagesize][0] self._canv = Canvas setTTFonts()
def bmp2pdf(): """ bmp -> pdf """ c = canvas.Canvas('bmp2pdf.pdf', pagesize=landscape(A4)) (w, h) = landscape(A4) width, height = letter #c.drawImage(filename, inch, height - 2 * inch) # Who needs consistency? c.drawImage('bmp2pdf.bmp', 0, 0, w, h) c.showPage() c.save()
def drawCoverPage(c, filename): width = landscape(A4)[0] - 20*mm height = landscape(A4)[1] - 20*mm # leave 1cm margin on page drawable_h = height - titlesize - 5*mm # draw image c.drawImage(filename, 10*mm, 10*mm, width=width, height=height, preserveAspectRatio=True) # show the page c.showPage()
def get_frame(self, debug, side='Left'): # or Right x1 = 0 if side == 'Right': x1 = landscape(letter)[0]/2 return Frame(x1=x1, y1=0, width=landscape(letter)[0]/2, height=landscape(letter)[1], leftPadding=self.left_padding, bottomPadding=DEFAULT_PADDING, rightPadding=self.right_padding, topPadding=DEFAULT_PADDING, showBoundary=debug)
def StringIO2pdf(): """ bmp -> StringIO -> ImageReader -> pdf """ with open('bmp2pdf.bmp', 'rb') as f: buf = StringIO.StringIO(f.read()) ir = ImageReader(buf) c = canvas.Canvas('StringIO2pdf.pdf', pagesize=landscape(A4)) (w, h) = landscape(A4) width, height = letter #c.drawImage(filename, inch, height - 2 * inch) # Who needs consistency? c.drawImage(ir, 0, 0, w, h) c.showPage() c.save()
def func(request): elements = [] doc = SimpleDocTemplate("fun.pdf", pagesize=landscape(A4)) elements = basic_info("prabha", "prabha", elements) # ,pagesize) elements = other_info(elements, "prabha", "prabha") doc.build(elements, onFirstPage=myfirstpage, onLaterPages=mylaterpages) return render(request, 'app1/prakhar.html', {}) # %s%s"%(tes,fun))
def buildTable(data): doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [] #Configure style and word wrap s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' pdf_data = [["Requirement", "Description", "Test Case(s)"]] #TODO: Need a numerical sort here keys = sorted(data.keys()) for key in keys: data[key][2] = '\n'.join(data[key][2]) pdf_data.append([Paragraph(cell, s) for cell in data[key]]) # Build the Table and Style Information tableThatSplitsOverPages = Table(pdf_data, repeatRows=1) tableThatSplitsOverPages.hAlign = 'LEFT' tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('LINEBELOW',(0,0),(-1,-1),1,colors.black), ('INNERGRID', (0,0), (-1,-1),1,colors.black), ('BOX',(0,0),(-1,-1),1,colors.black), ('BOX',(0,0),(0,-1),1,colors.black)]) tblStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue) tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white) tableThatSplitsOverPages.setStyle(tblStyle) elements.append(tableThatSplitsOverPages) doc.build(elements)
def __init__(self,filename): self.filename = r"%s" % filename self.myold = oldpdf(self.filename) self.canvas_obj = canvas.Canvas(self.filename,pagesize=pagesizes.landscape(letter)) self.canvas_obj.grid(self.make_listx(),self.make_listy()) self.canvas_obj.setFont("Times-Roman", self.fontsize_to_fit) self.label_axes()
def get(self, request, *args, **kwargs): self.doc = SolarisDocTemplate(request, pagesize=landscape(A4), report_name=self.get_report_name()) report = MechsReportSection(self.stableweek) self.doc.build(report.as_story()) return self.doc.get_response()
def main(): for infile in glob.glob (os.path.join("","*")): if infile.find(".py") == -1 and infile.find(".txt") == -1 and infile.find(".pdf") == -1 and os.path.isdir(infile)==False and infile.find("Xoma")==-1: fn = infile.replace(" ","_") os.rename(infile,fn) tag = fn.split('_')[0].split(barcode+'-')[1] if filelist.has_key(tag): filelist[tag].append(fn) else: filelist[tag] = [barcode+'-'+tag] clones = filelist.keys() clones.sort() c = canvas.Canvas(barcode+".pdf") c.setPageSize(landscape(letter)) c.setFont("Helvetica", 18) for cid in clones: fn = filelist[cid][0]+filetype['filmstrip'] cmd = "convert -crop 764x664 "+ fn+" tiles_%d.jpg" print fn subprocess.call(["convert","-crop","764x644",fn,cid+"_tiles_%d.jpg"]) #sleep(3) drawPDF(c,cid) for jpg in glob.glob (os.path.join("","*")): if jpg.find(".py") == -1 and jpg.find(".txt") == -1 and jpg.find(".pdf") == -1 and os.path.isdir(jpg)==False: if jpg.find("tiles") != -1: os.remove(jpg) c.save()
def myLaterPages(canvas, doc): PAGE_HEIGHT,PAGE_WIDTH = letter canvas.saveState() canvas.setPageSize(landscape(letter)) canvas.drawImage(frunt_pag2, 0,0, PAGE_WIDTH,PAGE_HEIGHT ) canvas.setStrokeColorRGB(0,1,1,alpha=0.1) ficha_no = doc.page-1 #canvas.setStrokeColorRGB(0.7,0.7,0.7) canvas.setFillColorRGB(0,0,0) SHOW_GRID = False if SHOW_GRID: n = 5 s = 200 canvas.setFillColorRGB(0,0,1) canvas.setFont('Helvetica',1) for x in range(s): for y in range(s): canvas.rect(x*n,y*n, width=n, height=n, stroke=1) canvas.drawString(x*n,y*n,"%s,%s" % ((x*n),(y*n)) ) # for i in range(s): # x= i*n # y=x # canvas.drawString(x,0,"%s" % (x)) #horizontal # canvas.drawString(0,y+1,"%s" % (x)) # vertical # canvas.drawString(x,600,"%s" % (x)) #horizontal # canvas.drawString(990,y,"%s" % (x)) # vertical # # canvas.setStrokeColorRGB(0,0,1,alpha=0.7) # canvas.setFont('Helvetica',1) # for i in range(610): # #canvas.rect(35,i*2, width=0.5, height=0.5, stroke=1) # canvas.drawString(35,i,"%s -" % (i,) ) canvas.setFont('Helvetica',7) LINE_1 = 508 #fecha_elaboracion = doc.fecha_elaboracion #if not fecha_elaboracion: # fecha_elaboracion = datetime.today() canvas.drawCentredString(137,LINE_1,str(fecha_elaboracion.year)) canvas.drawCentredString(162,LINE_1,str(fecha_elaboracion.month)) canvas.drawCentredString(180,LINE_1,str(fecha_elaboracion.day)) canvas.drawCentredString(290,LINE_1,"VALLE DEL CAUCA") canvas.drawCentredString(740,LINE_1,"Ficha No. %s" % (int(ficha_no)+int(no_ficha_inicial)-1)) canvas.setFont('Helvetica',5) canvas.drawString(75,115, "Elaboro: %s" % elaboro) canvas.drawString(215,115, "Reviso: %s" % reviso) canvas.restoreState()
def reporte_proveedores(request): print ("Genero el PDF"); response = HttpResponse(content_type='application/pdf') pdf_name = "proveedores.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=landscape(legal), rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) proveedores = [] styles = getSampleStyleSheet() header = Paragraph("Listado de Proveedores", styles['Heading1']) proveedores.append(header) headings = ('No. Proveedor','Nombre','RFC','Giro','Direccion','Ciudad','Estado','Pais','Telefono','Correo','Comentario') allproveedores = [(p.num_proveedor, p.nombre, p.RFC ,p.giro ,p.direccion ,p.ciudad ,p.estado ,p.pais ,p.telefono ,p.correo ,p.comentario) for p in Proveedor.objects.all()] print (allproveedores); t = Table([headings] + allproveedores) t.setStyle(TableStyle( [ ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) proveedores.append(t) doc.build(proveedores) response.write(buff.getvalue()) buff.close() return response
def generateNumberedPages(numPages, pageSize, orientation, bgColor, outPath): "Generate a 10 page document with one big number per page." if orientation == "landscape": pageSize = landscape(pageSize) canv = Canvas(outPath, pagesize=pageSize) for i in range(numPages): canv.setFont("Helvetica", 500) text = u"%s" % i if i % 2 == 0: canv.setStrokeColor(bgColor) canv.setFillColor(bgColor) canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True) canv.setFillColor(black) elif i % 2 == 1: canv.setStrokeColor(black) canv.setFillColor(black) canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True) canv.setFillColor(bgColor) if orientation == "portrait": canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.3, u"%s" % i) elif orientation == "landscape": canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.21, u"%s" % i) canv.showPage() canv.save()
def __init__(self, filename, title_left, title_right, portrait=True): if portrait is True: page_size = A4 column_width = 8*cm else: page_size = landscape(A4) column_width = 13*cm SimpleDocTemplate.__init__(self, filename, pagesize=page_size, topMargin=0*cm, leftMargin=2 * cm, rightMargin=2 * cm, bottomMargin=0.5 * cm, ) self.fileName = filename im1 = Image(settings.MEDIA_ROOT + 'logo_EPC.png', width=170, height=80, hAlign=TA_LEFT) data = list() data.append([im1, '']) data.append([Spacer(0, 0.5*cm)]) data.append([title_left, title_right]) t = Table(data, colWidths=[column_width]*2, hAlign=TA_LEFT) t.setStyle( TableStyle( [ ('SIZE', (0, 0), (-1, -1), 9), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (0, 0), 'LEFT'), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ('LINEABOVE', (0, 0), (-1, -1), 0.5, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 0.5, colors.black), ] ) ) self.flowable.append(t)
def createPDF(pdf, texts): page = pagesizes.landscape(pagesizes.A4) pdf.setFillColorRGB(0.0, 0.0, 0.0) pdf.setPageSize(page) for text in texts: centerString(pdf, page, text) pdf.showPage()
def pre_save_enrollment(signal, sender, instance, **kwargs): images_path = os.path.join(settings.PROJECT_DIR, 'static_files', 'img') signature_path = os.path.join(images_path, 'signature.jpg') logo_path = os.path.join(images_path, 'cert_logo.png') context = { 'enrollment': instance, 'domain': Site.objects.get_current().domain, 'signature_path': signature_path, 'logo_path': logo_path, } certificate_txt = render_to_string('certificates/certificate.txt', context) elements = [] styles = getSampleStyleSheet() styles.add( ParagraphStyle( name='Justify', alignment=TA_JUSTIFY, fontSize=16, leading=22 ) ) elements.append(Spacer(1, 16)) paragraphs = certificate_txt.split("\n") for p in paragraphs: if p.strip(): elements.append(Paragraph(p, styles['Justify'])) elements.append(Spacer(1, 16)) output = StringIO.StringIO() doc = SimpleDocTemplate(output, topMargin=3 * cm, bottomMargin=0) doc.pagesize = landscape(A4) doc.build(elements) filename = u'{0}.pdf'.format(instance.name) pdf = output.getvalue() instance.certificate.save(filename, ContentFile(pdf), save=False)
def generate_sertificate(first_name, last_name, employment, pdf_file_name): attendee_name = first_name + ' ' + last_name c = canvas.Canvas(pdf_file_name, pagesize=landscape(letter)) # header text c.setFont('Helvetica', 48, leading=None) c.drawCentredString(415, 500, 'Employee Certificate') c.setFont('Helvetica', 24, leading=None) c.drawCentredString(415, 450, 'This certificate is presented to:') # attendee name c.setFont('Helvetica-Bold', 34, leading=None) c.drawCentredString(415, 395, attendee_name) # for completing the... c.setFont('Helvetica', 24, leading=None) c.drawCentredString(415, 350, 'who holds the position in the IT company of:') # employment c.setFont('Helvetica', 20, leading=None) c.drawCentredString(415, 310, employment) # image of seal seal = 'certificate.ico' c.drawImage(seal, 350, 150, width=100, height=100) c.showPage() c.save()
def render(self): resp = HttpResponse(content_type='application/pdf') registerFont(TTFont('DejaVu Serif', "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf")) pagesize = self.orientation=='portrait' and A4 or landscape(A4) doc = SimpleDocTemplate(resp, pagesize=pagesize) story = [] story.append(Paragraph(self.title, getSampleStyleSheet()['title'])) tbldata = [self.headers] tbldata.extend(self.rows) t = Table(tbldata, splitByRow=1, repeatRows=1) style = [ ("FONTNAME", (0, 0), (-1, -1), "DejaVu Serif"), ] if self.borders: style.extend([ ('GRID', (0,0), (-1, -1), 1, colors.black), ('BACKGROUND', (0,0), (-1,0), colors.lightgrey), ]) t.setStyle(TableStyle(style)) story.append(t) doc.build(story) return resp
def render(self): elements = [] self.styles['Title'].alignment = TA_LEFT self.styles['Title'].fontName = self.styles['Heading2'].fontName = "Helvetica" self.styles["Normal"].fontName = "Helvetica" self.styles["Normal"].fontSize = 10 self.styles["Normal"].fontWeight = "BOLD" filename = self.filename + datetime.now().strftime("%Y%m%d%H%M%S") + ".pdf" doc = SimpleDocTemplate(filename) elements.append(Paragraph(self.title, self.styles['Title'])) clinics = Provider.objects.values('clinic').distinct() for data in self.data: elements.append(data) #elements.append(Paragraph("Created: %s" % datetime.now().strftime("%d/%m/%Y"), styles["Normal"])) if self.landscape is True: doc.pagesize = landscape(A4) doc.build(elements, onFirstPage=self.myFirstPage, onLaterPages=self.myLaterPages) response = HttpResponse(mimetype='application/pdf') response['Cache-Control'] = "" response['Content-Disposition'] = "attachment; filename=%s" % filename response.write(open(filename).read()) os.remove(filename) return response
def preview_recorder( page_rec, frame_title ='', pagesize =A4, landscape =False, parent =None): printData = wx.PrintData() printData.SetPaperId( wx.PAPER_A4) printData.SetPrintMode( wx.PRINT_MODE_PRINTER) if landscape: pagesize = pagesizes.landscape( pagesize) printData.SetOrientation( 2) data = wx.PrintDialogData( printData) from reporter.engine.rl2wx.printout import MyPrintout as Printout printout = Printout( page_rec) printout2 = Printout( page_rec) preview = wx.PrintPreview( printout, printout2, data) preview.SetZoom( 100 or 200) if not preview.Ok(): print 'No printer is installed...\n' return pfrm = wx.PreviewFrame( preview, parent, frame_title) pfrm.Initialize() #controlbar = CustomizedPreviewControlBar( preview, 0, pfrm) #pfrm.SetControlBar( controlbar) #controlbar.CreateButtons() #pfrm.SetPosition( frame.GetPosition()) pfrm.SetSize( (1024,768)) pfrm.MakeModal(True) pfrm.Show(True)
def run(self): """ Run the report """ def make_landscape(canvas,doc): canvas.setPageSize(landscape(A4)) # file initialization in buffer !!!! self.doc = BaseDocTemplate(self.buffer, showBoundary=1, # margines pagesize=landscape(A4)) # create the frames. Here you can adjust the margins frame = Frame(self.doc.leftMargin-65, self.doc.bottomMargin - 50, self.doc.width + 125, self.doc.height + 110, id='first_frame') # add the PageTempaltes to the BaseDocTemplate. # You can also modify those to adjust the margin if you need more control over the Frames. self.doc.addPageTemplates(PageTemplate(id='first_page', frames=frame, onPage=make_landscape)) self.create_text() self.create_table() self.create_footer() self.doc.build(self.story)
def write_string_to_pdf(self, participants_name): outputfiletemp = 'output/testoutput.pdf' pdf1File = open('templates/participants.pdf', 'rb') pdf1Reader = PyPDF2.PdfFileReader(pdf1File) pdfWriter = PyPDF2.PdfFileWriter() packet = StringIO.StringIO() cv=canvas.Canvas(packet, pagesize=letter) cv.setPageSize(landscape(letter)) #create a string cv.drawString(350, 300, participants_name) #save to string cv.save() #write to a file with open(outputfiletemp,'wb') as fp: fp.write(packet.getvalue()) certFirstPage = pdf1Reader.getPage(0) pdfWatermarkReader = PyPDF2.PdfFileReader(open(outputfiletemp, 'rb')) certFirstPage.mergePage(pdfWatermarkReader.getPage(0)) pdfWriter.addPage(certFirstPage) pdfOutputFile = open('output/pyconph2015_certificate_' + participants_name + '.pdf', 'wb') pdfWriter.write(pdfOutputFile) pdfOutputFile.close() pdf1File.close()
def print_big_list(data): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="RECAP.pdf"' doc = SimpleDocTemplate(response, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=20) doc.pagesize = landscape(A4) elements = [] t = Table(data, colWidths=(None, None, 300, 60)) # Styling the titles and the grid style = TableStyle([('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.grey), ('BOX', (0, 0), (-1, -1), 0.25, colors.grey), ]) t.setStyle(style) # we color lines alternatively for each in range(len(data)): if each % 2 == 0: bg_color = colors.white else: bg_color = colors.lightblue t.setStyle(TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) # Send the data and build the file elements.append(t) doc.build(elements) return response
def generatePdfReport(data): """ Function to generate report in PDF format. Input:- Details of aliens Output:- Details of aliens in PDF file. """ doc = SimpleDocTemplate("aliens.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [] # Style of table, imported from reportlab lib. # user styling, can be anything you want. style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), ('TEXTCOLOR',(1,1),(-2,-2),colors.red), ('VALIGN',(0,0),(0,-1),'TOP'), ('TEXTCOLOR',(0,0),(0,-1),colors.blue), ('ALIGN',(0,-1),(-1,-1),'CENTER'), ('VALIGN',(0,-1),(-1,-1),'MIDDLE'), ('TEXTCOLOR',(0,-1),(-1,-1),colors.green), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) #Configure style and word wrap s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' # to fit text in the cell, otherwise cross the margin data2 = [[Paragraph(cell, s) for cell in row] for row in data] t=Table(data2) t.setStyle(style) #Send the data and build the file elements.append(t) doc.build(elements)
def make_pdf(filename, parameter): parameter = read_result(parameter) doc = SimpleDocTemplate(filename, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [['Number', 'Value']] write_data(parameter, data) style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), ('TEXTCOLOR',(1,1),(-2,-2),colors.red), ('VALIGN',(0,0),(0,-1),'TOP'), ('TEXTCOLOR',(0,0),(0,-1),colors.blue), ('ALIGN',(0,-1),(-1,-1),'CENTER'), ('VALIGN',(0,-1),(-1,-1),'MIDDLE'), ('TEXTCOLOR',(0,-1),(-1,-1),colors.green), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t = Table(data2) t.setStyle(style) elements.append(t) doc.build(elements)
def __to_pdf(tempFile, breakdown, building, begin_ts, end_ts): doc = SimpleDocTemplate(tempFile, pagesize=landscape(A4), leftMargin=MARGIN, rightMargin=MARGIN, topMargin=MARGIN, bottomMargin=MARGIN, title=u'Lista de întreținere %s' % building.name, author='www.habitam.ro') flowables = [] sc_title_style = ParagraphStyle(name='staircase_title', alignment=TA_CENTER) for sc in building.apartment_groups(): if sc == building: continue sc_title = Paragraph(u'Lista de întreținere scara %s' % sc.name, sc_title_style) data = __list_data(sc, breakdown, building.services()) table = Table(data, repeatRows=1) table.setStyle(TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('FONTSIZE', (0, 0), (-1, -1), __FONT_SIZE__), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black) ])) flowables.extend([Spacer(1, .5 * cm), sc_title, Spacer(1, cm), table, Spacer(1, .5 * cm), signatures(__FONT_SIZE__), PageBreak()]) doc.habitam_building = building doc.habitam_month = begin_ts.strftime('%B %Y') doc.habitam_display = date.today().strftime('%d %B %Y') doc.build(flowables, onFirstPage=__list_format, onLaterPages=__list_format)
def atPage(self, name, pseudopage, declarations): c = self.c data = {} name = name or "body" pageBorder = None if declarations: result = self.ruleset([self.selector('*')], declarations) if declarations: data = result[0].values()[0] pageBorder = data.get("-pdf-frame-border", None) if name in c.templateList: log.warn( self.c.warning("template '%s' has already been defined", name)) if "-pdf-page-size" in data: c.pageSize = xhtml2pdf.default.PML_PAGESIZES.get( str(data["-pdf-page-size"]).lower(), c.pageSize) isLandscape = False if "size" in data: size = data["size"] if type(size) is not types.ListType: size = [size] sizeList = [] for value in size: valueStr = str(value).lower() if type(value) is types.TupleType: sizeList.append(getSize(value)) elif valueStr == "landscape": isLandscape = True elif valueStr in xhtml2pdf.default.PML_PAGESIZES: c.pageSize = xhtml2pdf.default.PML_PAGESIZES[valueStr] else: log.warn(c.warning("Unknown size value for @page")) if len(sizeList) == 2: c.pageSize = tuple(sizeList) if isLandscape: c.pageSize = landscape(c.pageSize) padding_top = self._getFromData(data, 'padding-top', 0, getSize) padding_left = self._getFromData(data, 'padding-left', 0, getSize) padding_right = self._getFromData(data, 'padding-right', 0, getSize) padding_bottom = self._getFromData(data, 'padding-bottom', 0, getSize) border_color = self._getFromData(data, ('border-top-color', 'border-bottom-color',\ 'border-left-color', 'border-right-color'), None, getColor) border_width = self._getFromData(data, ('border-top-width', 'border-bottom-width',\ 'border-left-width', 'border-right-width'), 0, getSize) for prop in ("margin-top", "margin-left", "margin-right", "margin-bottom", "top", "left", "right", "bottom", "width", "height"): if prop in data: c.frameList.append( self._pisaAddFrame(name, data, first=True, border=pageBorder, size=c.pageSize)) break # Frames have to be calculated after we know the pagesize frameList = [] staticList = [] for fname, static, border, x, y, w, h, fdata in c.frameList: fpadding_top = self._getFromData(fdata, 'padding-top', padding_top, getSize) fpadding_left = self._getFromData(fdata, 'padding-left', padding_left, getSize) fpadding_right = self._getFromData(fdata, 'padding-right', padding_right, getSize) fpadding_bottom = self._getFromData(fdata, 'padding-bottom', padding_bottom, getSize) fborder_color = self._getFromData(fdata, ('border-top-color', 'border-bottom-color',\ 'border-left-color', 'border-right-color'), border_color, getColor) fborder_width = self._getFromData(fdata, ('border-top-width', 'border-bottom-width',\ 'border-left-width', 'border-right-width'), border_width, getSize) if border or pageBorder: frame_border = ShowBoundaryValue() else: frame_border = ShowBoundaryValue(color=fborder_color, width=fborder_width) #fix frame sizing problem. if static: x, y, w, h = getFrameDimensions(fdata, c.pageSize[0], c.pageSize[1]) x, y, w, h = getCoords(x, y, w, h, c.pageSize) if w <= 0 or h <= 0: log.warn( self.c.warning( "Negative width or height of frame. Check @frame definitions." )) frame = Frame(x, y, w, h, id=fname, leftPadding=fpadding_left, rightPadding=fpadding_right, bottomPadding=fpadding_bottom, topPadding=fpadding_top, showBoundary=frame_border) if static: frame.pisaStaticStory = [] c.frameStatic[static] = [frame] + c.frameStatic.get(static, []) staticList.append(frame) else: frameList.append(frame) background = data.get("background-image", None) if background: #should be relative to the css file background = self.c.getFile(background, relative=self.c.cssParser.rootPath) if not frameList: log.warn( c.warning( "missing explicit frame definition for content or just static frames" )) fname, static, border, x, y, w, h, data = self._pisaAddFrame( name, data, first=True, border=pageBorder, size=c.pageSize) x, y, w, h = getCoords(x, y, w, h, c.pageSize) if w <= 0 or h <= 0: log.warn( c.warning( "Negative width or height of frame. Check @page definitions." )) if border or pageBorder: frame_border = ShowBoundaryValue() else: frame_border = ShowBoundaryValue(color=border_color, width=border_width) frameList.append( Frame(x, y, w, h, id=fname, leftPadding=padding_left, rightPadding=padding_right, bottomPadding=padding_bottom, topPadding=padding_top, showBoundary=frame_border)) pt = PmlPageTemplate( id=name, frames=frameList, pagesize=c.pageSize, ) pt.pisaStaticList = staticList pt.pisaBackground = background pt.pisaBackgroundList = c.pisaBackgroundList if isLandscape: pt.pageorientation = pt.LANDSCAPE c.templateList[name] = pt c.template = None c.frameList = [] c.frameStaticList = [] return {}, {}
def __init__(self, fname, fund_name, logo_path=0): self.width, self.height = landscape(letter) self.logo_path = logo_path self.c = canvas.Canvas(fname) self.fund_name = fund_name
from reportlab.pdfgen.canvas import Canvas from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Paragraph, Frame, KeepInFrame from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch c = Canvas('foo.pdf', pagesize=landscape(letter)) frame1 = Frame(0.25 * inch, 0.25 * inch, 4 * inch, 4 * inch, showBoundary=1) styles = getSampleStyleSheet() s = "foo bar " * 100 story = [Paragraph(s, styles['Normal'])] frame1.addFromList([story], c) c.save()
from PyPDF2 import PdfFileReader, PdfFileWriter import os import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter, landscape out_folder = "C:\\Users\\DanFang\\Desktop" os.chdir(out_folder) original_doc = PdfFileReader(open('hwccopy1.pdf', 'rb')) output = PdfFileWriter() packet = io.BytesIO() new_canvas = canvas.Canvas(packet, pagesize=landscape(letter)) for page in range(37, 47): new_canvas.setFont('Helvetica', 10) string = '09180' + str(page).zfill(2) new_canvas.drawString(290, 18, str(string)) new_canvas.showPage() new_canvas.save() packet.seek(0) new_pdf = PdfFileReader(packet) for i in range(0, 10): page = original_doc.getPage(i) #page = new_pdf.getPage(i) page.mergePage(new_pdf.getPage(i)) output.addPage(page)
def _parseAtPage(self, src): """page : PAGE_SYM S* IDENT? pseudo_page? S* '{' S* declaration [ ';' S* declaration ]* '}' S* ; """ data = {} pageBorder = None isLandscape = False ctxsrc = src src = src[len('@page'):].lstrip() page, src = self._getIdent(src) if src[:1] == ':': pseudopage, src = self._getIdent(src[1:]) page = page + '_' + pseudopage else: pseudopage = None # src, properties = self._parseDeclarationGroup(src.lstrip()) # Containing @ where not found and parsed stylesheetElements = [] src = src.lstrip() properties = [] # XXX Extended for PDF use if not src.startswith('{'): raise self.ParseError('Ruleset opening \'{\' not found', src, ctxsrc) else: src = src[1:].lstrip() while src and not src.startswith('}'): if src.startswith('@'): # @media, @page, @font-face src, atResults = self._parseAtKeyword(src) if atResults is not None: stylesheetElements.extend(atResults) else: src, nproperties = self._parseDeclarationGroup(src.lstrip(), braces=False) properties += nproperties # Set pagesize, orientation (landscape, portrait) data = {} pageBorder = None if properties: result = self.cssBuilder.ruleset( [self.cssBuilder.selector('*')], properties) try: data = result[0].values()[0] except Exception: data = result[0].popitem()[1] pageBorder = data.get("-pdf-frame-border", None) if "-pdf-page-size" in data: self.c.pageSize = xhtml2pdf.default.PML_PAGESIZES.get( str(data["-pdf-page-size"]).lower(), self.c.pageSize) isLandscape = False if "size" in data: size = data["size"] if not isinstance(size, list): size = [size] sizeList = [] for value in size: valueStr = str(value).lower() if isinstance(value, tuple): sizeList.append(getSize(value)) elif valueStr == "landscape": isLandscape = True elif valueStr == "portrait": isLandscape = False elif valueStr in xhtml2pdf.default.PML_PAGESIZES: self.c.pageSize = xhtml2pdf.default.PML_PAGESIZES[ valueStr] else: raise RuntimeError("Unknown size value for @page") if len(sizeList) == 2: self.c.pageSize = tuple(sizeList) if isLandscape: self.c.pageSize = landscape(self.c.pageSize) src = src.lstrip() result = [ self.cssBuilder.atPage(page, pseudopage, data, isLandscape, pageBorder) ] return src[1:].lstrip(), result
from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, landscape from reportlab.lib.units import cm, inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, Table, TableStyle from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER from reportlab.lib import colors #get the size of the paper width, height = landscape(A4) #generate styles styles = getSampleStyleSheet() #wraps text styleN = styles["BodyText"] #aligns text to left styleN.alignment = TA_LEFT #normal text wrap styleBH = styles["Normal"] #aligns text to center styleBH.alignment = TA_CENTER # Headers h_one = Paragraph('''<b>Project #</b>''', styleN) h_two = Paragraph('''<b>Project Details</b>''', styleN) h_three = Paragraph('''<b>Unit of measurement</b>''', styleN) h_four = Paragraph('''<b>Financial Requirements</b>''', styleN) h_five = Paragraph('''<b>Physical Requirements</b>''', styleN) # Texts
def pagesize(self): from reportlab.lib import pagesizes return pagesizes.landscape(pagesizes.A4)
def createProgressReport(contracts,user): """ Basic Setup for Report Lab """ pdf_buffer = BytesIO() doc = SimpleDocTemplate(pdf_buffer) doc.pagesize =landscape(A4) flowables = []#overall flowables structural_summary=[]#for structural summary contract_summary=[] sample_style_sheet = getSampleStyleSheet() #sample_style_sheet.list() """Creating Style for Paragraph """ custom_body_style = sample_style_sheet['Heading5'] #custom_body_style.listAttrs() custom_body_style.spaceAfter=0 custom_body_style.spaceBefore=0 for contract in contracts: structures=Contract_Intervention.objects.filter(contract_id=contract) """Variable for Holding Total progress in structure """ #mylist = ['', '', '', '', "Overall Progress",'','', '', '', '', '', ''] contract_data=[] item_progress="itemized"+chr(10)+"progress" contract_heading=['sl','name','weight','progress',item_progress] contract_data.append(contract_heading) contract_sl=1 contract_sum=0 myheading2 = "Contract Name : " + contract.package_short_name myparagraph2 = Paragraph(myheading2, custom_body_style) myparagraph2.hAlign = 'LEFT' contract_summary.append(myparagraph2) for structure in structures: """ Structurl Progress Rreport """ contractName="" contract_row=[contract_sl,prepareMultiline(structure.dpp_intervention_id.name,25),structure.physical_weight,0,0] contract_sl +=1 """ Adding Header Section For Report """ myheading1 = "Haor Name : " + structure.dpp_intervention_id.haor_id.name myparagraph1 = Paragraph(myheading1, custom_body_style) myparagraph1.hAlign = 'LEFT' myheading3="Structure Name : "+structure.dpp_intervention_id.name myheading4="Reproting Date : "+"24/3/2019" # Latter A Proper Date Will be Created #mystr=contract.package_short_name+"/"+structure.dpp_intervention_id.name flowables.append(myparagraph1) flowables.append(myparagraph2) myparagraph3 = Paragraph(myheading3, custom_body_style) myparagraph1.hAlign = 'LEFT' flowables.append(myparagraph3) myparagraph4 = Paragraph(myheading4, custom_body_style) myparagraph1.hAlign = 'LEFT' flowables.append(myparagraph4) flowables.append(Spacer(1, 0.25 * cm)) """ Table Section of the report """ pitems=ProgressItem.objects.filter(intervention_id=structure) mydata=[] iprog="item"+chr(10)+ "progress" qua_exe="Quan"+chr(10)+"Executed"+chr(10)+"RPeriod" tableHeading=['Sl','Pre_date','curr_date','duration','Item Name','Unit','Est_Qua','weight','Prev_Qua','Qua_Curr', qua_exe,iprog] mydata.append(tableHeading) sl=1 sum=0.0 total_structural = ['', '', '', '', "Overall Progress", '', '', '', '', '', '', ''] for pitem in pitems: iname=prepareMultiline(pitem.item_name,25) mylist=[sl,'','','',iname, pitem.unit,pitem.quantity,pitem.weight,'','','',0] mylist=calculateProgressQuantity(pitem,user,mylist) mydata.append(mylist) sl+=1 sum+=float(mylist[11]) print("total for={}".format(mylist[11])) total_structural[11]=sum mydata.append(total_structural) colwidth=[1.0*cm,1.8*cm,1.8*cm,1.8*cm,4.9*cm,2.0*cm,2.2*cm,2.2*cm,2.2*cm,2.0*cm,2.0*cm,2.0*cm] t = Table(mydata,repeatRows=1,colWidths=colwidth) t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),('BOX', (0,0), (-1,-1), 0.25, colors.black),])) t.hAlign = 'LEFT' #t.wrapOn() flowables.append(t) flowables.append(Spacer(1, 0.5* cm)) contract_row[3]= total_structural[11] contract_row[4]=float(contract_row[3])*float(contract_row[2]) contract_sum +=contract_row[4] contract_data.append(contract_row) total_contract=['',prepareMultiline('Overall physical Progress',60),'','',contract_sum ] contract_data.append(total_contract) contract_colwidth=[1.0*cm,12*cm,3*cm,3*cm,4*cm] t_contract=Table(contract_data,repeatRows=1,colWidths=contract_colwidth) t_contract.setStyle(TableStyle( [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) t_contract.hAlign='LEFT' contract_summary.append(t_contract) signature_table_data=[] #myheading1 = "This is a test paragraph" #myparagraph1 = Paragraph(myheading1, custom_body_style) for item in reversed(contract_summary): flowables.insert(0,item) #custom_body_style.listAttrs() #sample_style_sheet.list() """ item_name = models.CharField(max_length=200, default="EW") unit = models.CharField(max_length=10) quantity = models.DecimalField(null=True, blank=True, decimal_places=3, max_digits=13) weight = models.DecimalField(null=True, blank=True, decimal_places=3, max_digits=13) startdate = models.DateField(default=timezone.now) finishdate = models.DateField(default=timezone.now) styles = getSampleStyleSheet() Story = [Spacer(1, 2 * inch)] style = styles["Normal"] for i in range(100): bogustext = ("This is Paragraph number %s. " % i) * 20 p = Paragraph(bogustext, style) Story.append(p) Story.append(Spacer(1, 0.2 * inch)) """ doc.build(flowables) pdf_value = pdf_buffer.getvalue() pdf_buffer.close() return pdf_value
from os import path from django.core.files.temp import NamedTemporaryFile from django.utils import translation static_dir = path.join(path.dirname(__file__), 'assets') fonts = { 'sahlnaskh-regular.ttf': 'Sahl Naskh Regular', 'sahlnaskh-bold.ttf': 'Sahl Naskh Bold', } for font_file, font_name in fonts.iteritems(): font_path = path.join(static_dir, font_file) pdfmetrics.registerFont(TTFont(font_name, font_path, validate=True)) SIZE = landscape(A4) def get_organization_logo(organization, course_id): organization = organization.lower() if organization == 'mitx' or organization == 'harvardx' or organization == 'qrf': return 'edx.png' elif organization == u'bayt.com': return 'bayt-logo2-en.png' elif organization == u'qrta': return 'qrta_logo.jpg' elif organization == 'aub': return 'Full-AUB-Seal.jpg' elif organization == "csbe": return 'csbe.png' elif organization == "hcac":
def print_mass_pay(request, year): """ This function contains the required methods to create a PDF report. It will be merged with the salary app some time later. """ def sch(c): try: return c.permanent and c.permanent.organization_serving() except: return c.organization_serving() payment_codes = PaymentCode.objects.all() category_titles = PaymentCategoryTitle.objects.all() emp = Employee.objects.get(id=request.session['matched_employee_id']) try: emptype = Permanent.objects.get(parent_id=emp.id) except Permanent.DoesNotExist: try: emptype = NonPermanent.objects.get(parent_id=emp.id) except NonPermanent.DoesNotExist: try: emptype = Administrative.objects.get(parent_id=emp.id) except Administrative.DoesNotExist: emptype = 0 except: raise emp_payments = rprts_from_user(emp.id, year, '11,12,21') u = set([x['employee_id'] for x in emp_payments]) y = {x['employee_id']: x['year'] for x in emp_payments} dict_emp = { c.id: [ c.lastname, c.firstname, c.vat_number, c.fathername, c.address, c.tax_office, u'%s' % c.profession, u'%s' % c.profession.description, c.telephone_number1, sch(c) ] for c in Employee.objects.filter(id__in=u) } elements = [] reports = [] for empx in u: r_list = calc_reports( filter(lambda s: s['employee_id'] == empx, emp_payments)) hd = r_list[0] ft = [r_list[-2]] + [r_list[-1]] dt = r_list del dt[0] del dt[-2] del dt[-1] newlist = [] output = dict() for sublist in dt: try: output[sublist[0]] = map(operator.add, output[sublist[0]], sublist[1:]) except KeyError: output[sublist[0]] = sublist[1:] for key in output.keys(): newlist.append([key] + output[key]) newlist.sort(key=lambda x: x[0], reverse=True) r_list = [hd] + newlist + ft report = {} report['report_type'] = '1' report['type'] = '' report['year'] = y[empx] report['emp_type'] = 0 report['vat_number'] = dict_emp[empx][2] report['lastname'] = dict_emp[empx][0] report['firstname'] = dict_emp[empx][1] report['fathername'] = dict_emp[empx][3] report['address'] = dict_emp[empx][4] report['tax_office'] = dict_emp[empx][5] report['profession'] = ' '.join([dict_emp[empx][6], dict_emp[empx][7]]) report['telephone_number1'] = dict_emp[empx][8] report['rank'] = None report['net_amount1'] = '' report['net_amount2'] = '' report['organization_serving'] = dict_emp[empx][9] report['payment_categories'] = r_list reports.append(report) response = HttpResponse(mimetype='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=pay_report_%s.pdf' % year registerFont( TTFont('DroidSans', os.path.join(settings.MEDIA_ROOT, 'DroidSans.ttf'))) registerFont( TTFont('DroidSans-Bold', os.path.join(settings.MEDIA_ROOT, 'DroidSans-Bold.ttf'))) doc = SimpleDocTemplate(response, pagesize=A4) doc.topMargin = 0.5 * cm doc.bottomMargin = 0.5 * cm doc.leftMargin = 1.5 * cm doc.rightMargin = 1.5 * cm doc.pagesize = landscape(A4) if year == '2012': style = getSampleStyleSheet() style.add( ParagraphStyle(name='Center', alignment=TA_CENTER, fontName='DroidSans', fontSize=12)) elements = [ Paragraph( u'ΠΑΡΑΚΑΛΟΥΜΕ ΑΠΕΥΘΥΝΘΕΙΤΕ ΣΤΗΝ ΥΠΗΡΕΣΙΑ ΓΙΑ ΤΗΝ ΜΙΣΘΟΛΟΓΙΚΗ ΚΑΤΑΣΤΑΣΗ ΤΟΥ 2012', style['Center']) ] else: elements = generate_pdf_landscape_structure(reports) doc.build(elements) return response
from tempfile import NamedTemporaryFile from PIL import Image from reportlab.lib.pagesizes import A2 from reportlab.lib.pagesizes import landscape from reportlab.platypus import SimpleDocTemplate from reportlab.platypus import Image as PDFImage def merge(image_paths): layers = iter(image_paths) with Image.open(next(layers)) as overlay: for image_source in layers: with Image.open(image_source) as image: overlay.paste(image, (0, 0), image) return overlay if __name__ == '__main__': images = [ '0-background.png', '1-sun.png', '2-clouds.png', '3-trees.png', '4-birds.png', '5-copyright.png' ] merged = merge(images) doc = SimpleDocTemplate('landscape.pdf', pagesize=landscape(A2)) with NamedTemporaryFile(suffix='.png') as f: merged.save(f.name) image = PDFImage(f.name, 1024, 768) doc.build([image])
def Plantilla(img_1, trab, img_2, bl4_dat, bl5_dat, bl6_dat): style1 = ParagraphStyle(name='hola', fontName='Helvetica', fontSize=11, leading=13, alignment=1, spaceAfter=1) style2 = ParagraphStyle(name='hello', fontName='Helvetica', fontSize=8, leading=14.5, alignment=0, spaceAfter=1) style3 = ParagraphStyle(name='hi', fontName='Helvetica', fontSize=8, leading=0, alignment=0, leftIndent=2) style4bot = ParagraphStyle(name='hello', fontName='Helvetica', fontSize=7, leading=9.5, alignment=0, spaceAfter=1) sheet_from = (421.6, 298.1) sheet_to = landscape(A3) c = canvas.Canvas("h.pdf", pagesize=sheet_to) ############ # OUTERBOX # ############ outerbox = rect_data(sheet_from, ratio=True, w_l=24, w_r=9.5, h_b=14.2, h_t=21.6) draw_box(c, outerbox, sheet_to) ############ # TOPBOXES # ############ #****************************************************** dim = (25.1, 11.4, 22.2, 21.4 ) # x_l, x_r, y_t, y_c (same units as sheet_from) topb_lengths = (70.2, 90.2, 62, 65.9, 37.2, 59.6 ) #(same units as sheet_from) horz_sp = 00 #(same units as sheet_from) #****************************************************** topboxes = [] tot_length = sheet_from[0] - dim[0] - dim[1] - (len(topb_lengths) - 1) * horz_sp x_st = dim[0] for length, a in zip(topb_lengths, range(len(topb_lengths))): l = length / sum(topb_lengths) * tot_length topboxes.append( rect_data(sheet_from, ratio=True, w_l=x_st, w_c=l, h_t=dim[2], h_c=dim[3])) draw_box(c, topboxes[a], sheet_to) x_st += l + horz_sp #******************* # Topbox 1 Content # #******************* box_ID = 0 img = img_1 #Text #****** spacings = (4, 50) # dw, dh pixel points #****** draw_text(c, topboxes[box_ID], sheet_to, 'CLIENTE:', 9, spac=spacings) #Image #****** draw_image(c, topboxes[box_ID], sheet_to, img, l_pad=5, r_pad=5, b_pad=5, t_pad=15) #******************* # Topbox 2 Content # #******************* box_ID = 1 #Text #****** spacings = (4, 50) # dw, dh pixel points #****** draw_text(c, topboxes[box_ID], sheet_to, 'TRABAJO:', 9, spac=spacings) #Paragraph texto = trab #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style1, l_pad=29, r_pad=29, b_pad=5, t_pad=15) #******************* # Topbox 3 Content # #******************* box_ID = 2 img = img_2 #Text #****** spacings = (4, 50) # dw, dh pixel points #****** draw_text(c, topboxes[box_ID], sheet_to, 'EMPRESA CONSULTORA:', 9, spac=spacings) #Image #****** draw_image(c, topboxes[box_ID], sheet_to, img, l_pad=5, r_pad=10, b_pad=5, t_pad=15) #******************* # Topbox 4 Content # #******************* box_ID = 3 #Paragraph texto = '<b>Supervisor:</b><br/><b>Empresa:</b><br/><b>Sondista:</b><br/><b>Equipo:</b>' #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style2, l_pad=3, t_pad=2) #Paragraph texto = '' for x in range(len(bl4_dat)): texto += bl4_dat[x] if x < (len(bl4_dat) - 1): texto += '<br/>' #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style2, l_pad=60, t_pad=2) #******************* # Topbox 5 Content # #******************* box_ID = 4 #Paragraph texto = '<b>P.K.:</b><br/><b>X UTM:</b><br/><b>Y UTM:</b><br/><b>Z UTM:</b>' #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style2, l_pad=3, t_pad=2) #Paragraph texto = '' for x in range(len(bl5_dat)): texto += bl5_dat[x] if x < (len(bl5_dat) - 1): texto += '<br/>' #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style2, l_pad=35, t_pad=2) #******************* # Topbox 6 Content # #******************* box_ID = 5 #Paragraph texto = '<b>SONDEO:</b><br/><b>Hoja:</b><br/><b>F. de inicio:</b><br/><b>F. finalización:</b>' #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style2, l_pad=3, t_pad=2) #Paragraph texto = '' for x in range(1, len(bl5_dat)): texto += '<br/>' texto += bl6_dat[x] #****** draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style2, l_pad=70, t_pad=2) #Paragraph texto = '<b>' + bl6_dat[0] + '</b>' draw_paragraph(c, topboxes[box_ID], sheet_to, texto, style3, l_pad=68, r_pad=10, t_pad=2, b_pad=47, bbox=1) ############# # BODYBOXES # ############# #****************************************************** dim = (25.1, 11.1, 27, 44.5 ) # x_l, x_r, y_b, y_t (same units as sheet_from) bodyb_lengths = (26.5, 114, 4.5, 16.4, 10.7, 11.9, 19.5, 16.3, 35.1, 129.1 ) #(same units as sheet_from) horz_sp = 0.5 #(same units as sheet_from) #****************************************************** bodyboxes = [] tot_length = sheet_from[0] - dim[0] - dim[1] - (len(bodyb_lengths) - 1) * horz_sp x_st = dim[0] for length, a in zip(bodyb_lengths, range(len(bodyb_lengths))): l = length / sum(bodyb_lengths) * tot_length bodyboxes.append( rect_data(sheet_from, ratio=True, w_l=x_st, w_c=l, h_b=dim[2], h_t=dim[3])) # draw_box(c, bodyboxes[a], sheet_to) x_st += l + horz_sp for x in range(len(bodyboxes)): img = 'bloque' + str(x + 1) + '.svg' if x < len(bodyboxes) - 2: draw_image_svg(c, bodyboxes[x], sheet_to, img, l_pad=0.1, r_pad=0, b_pad=0, t_pad=0) ############### # BOTTOMBOXES # ############### #****************************************************** dim = (24.6, 10.8, 15.8, 10.5 ) # x_l, x_r, y_b, y_c (same units as sheet_from) botb_lengths = (166.8, 219.2) #(same units as sheet_from) horz_sp = 0.5 #(same units as sheet_from) #****************************************************** bottomboxes = [] tot_length = sheet_from[0] - dim[0] - dim[1] - (len(botb_lengths) - 1) * horz_sp x_st = dim[0] for length, a in zip(botb_lengths, range(len(botb_lengths))): l = length / sum(botb_lengths) * tot_length bottomboxes.append( rect_data(sheet_from, ratio=True, w_l=x_st, w_c=l, h_b=dim[2], h_c=dim[3])) draw_box(c, bottomboxes[a], sheet_to) x_st += l + horz_sp #********************** # Bottombox 2 Content # #********************** box_ID = 1 #Paragraph texto = 'MI: MUESTRA INALTERADA<br/>LF: ENSAYO LEFRANC<br/>Ox: ÓXIDO' #****** draw_paragraph(c, bottomboxes[box_ID], sheet_to, texto, style4bot, l_pad=3, r_pad=0, b_pad=0, t_pad=1) #Paragraph texto = 'MA: MUESTRA ALTERADA<br/>LG: ENSAYO LUGEON<br/>Q: CUARZO' #****** draw_paragraph(c, bottomboxes[box_ID], sheet_to, texto, style4bot, l_pad=125, r_pad=0, b_pad=0, t_pad=1) #Paragraph texto = 'SPT: PENETRÓMETRO<br/>MB: MUESTRA EN BOTE<br/>Ar: ARCILLA' #****** draw_paragraph(c, bottomboxes[box_ID], sheet_to, texto, style4bot, l_pad=250, r_pad=0, b_pad=0, t_pad=1) #Paragraph texto = 'TP: TESTIGO PARAFINADO<br/><br/>PR: ENSAYO PRESIOMÉTRICO' #****** draw_paragraph(c, bottomboxes[box_ID], sheet_to, texto, style4bot, l_pad=375, r_pad=0, b_pad=0, t_pad=1) #Paragraph texto = 'MW: MUESTRA DE AGUA<br/><br/>DL: ENSAYO DILATOMÉTRICO' #****** draw_paragraph(c, bottomboxes[box_ID], sheet_to, texto, style4bot, l_pad=500, r_pad=0, b_pad=0, t_pad=1) c.showPage() c.save()
from reportlab.pdfgen import canvas from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.rl_config import defaultPageSize from reportlab.lib.colors import HexColor from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.pagesizes import letter from reportlab.lib.pagesizes import landscape pdfmetrics.registerFont(TTFont('Bold', 'Raleway-Bold.ttf')) pdfmetrics.registerFont(TTFont('Light', 'Raleway-Light.ttf')) pdfmetrics.registerFont(TTFont('Extra', 'Raleway-Extrabold.ttf')) c = canvas.Canvas("sample23.pdf", pagesize=landscape(letter)) # cloud en c.drawImage("cloud.png", 500, 400, width=1.52 * 300, height=.87 * 300, mask=None) # cloud es # cloud wm c.drawImage("image01.png", 260, 40, width=1.52 * 200, height=.87 * 250, mask=None) c.drawImage("cloud.png",
__author__ = "Dinu Gherman" USE_HYPHENATION = True if USE_HYPHENATION: try: import wordaxe.rl.styles from wordaxe.rl.paragraph import Paragraph from wordaxe.DCWHyphenator import DCWHyphenator wordaxe.hyphRegistry['DE'] = DCWHyphenator('DE', 5) except SyntaxError: print("could not import hyphenation - try to continue WITHOUT hyphenation!") PAGESIZE = pagesizes.landscape(pagesizes.A4) class TwoColumnDocTemplate(BaseDocTemplate): "Define a simple, two column document." def __init__(self, filename, **kw): m = 2*cm cw, ch = (PAGESIZE[0]-2*m)/2., (PAGESIZE[1]-2*m) ch -= 14*cm f1 = Frame(m, m+10.5*cm, cw-0.75*cm, ch-9*cm, id='F1', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0, showBoundary=True ) f2 = Frame(m, m+0.5*cm, cw-0.75*cm, ch-1*cm, id='F2', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0,
def create_pdf(self): body = [] textAdjust = 6.5 if not self.filename: exit() styles = getSampleStyleSheet() spacer = Spacer(0, 0.25 * inch) ptext = '<font size=14>%s</font>' % self.ttl body.append(Paragraph(ptext, styles["Heading2"])) line = LineDrw(500) body.append(line) body.append(spacer) colwidths = [] for i in self.colwdths: colwidths.append(i * textAdjust) m = 0 new_data = [] for lin in list(self.rptdata): lin = list(lin) n = 0 for item in lin: if type(item) == str: if len(item) >= 10: item = Paragraph(item, styles['Normal']) styles['Normal'].alignment = 1 lin[n] = item n += 1 new_data.append(lin) m += 1 tblstyle = TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('LEFTPADDING', (0, 0), (-1, -1), 5), ('RIGHTPADDING', (0, 0), (-1, -1), 5), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]) tbl = Table(new_data, colWidths=colwidths, repeatRows=1) tbl.setStyle(tblstyle) body.append(tbl) doc = SimpleDocTemplate('tmp_rot_file.pdf', pagesize=landscape(letter), rightMargin=.5 * inch, leftMargin=.5 * inch, topMargin=.75 * inch, bottomMargin=.5 * inch) doc.build(body) pdf_old = open('tmp_rot_file.pdf', 'rb') pdf_reader = PyPDF4.PdfFileReader(pdf_old) pdf_writer = PyPDF4.PdfFileWriter() for pagenum in range(pdf_reader.numPages): page = pdf_reader.getPage(pagenum) page.rotateCounterClockwise(90) pdf_writer.addPage(page) pdf_out = open(self.filename, 'wb') pdf_writer.write(pdf_out) pdf_out.close() pdf_old.close() os.remove('tmp_rot_file.pdf')
def main(): args = parseArgs() inbam = args.bam infasta = args.fasta invcf = args.vcf numsites = args.numsites output = args.output rows = args.rows SNPs, INDELs = get_vcf(invcf) vcfSNPs = len(SNPs) print 'Identified %s putative SNPs' % vcfSNPs #print 'Identified %s putative INDEL bases' % len(INDELs) # enable explicitly given positions (e.g., -p '89,3969181,44,123456') to investigate if args.positions: posList = [int(n) for n in args.positions.split(',')] listWantSitesVCF = [] for i in posList: if any(i in x for x in SNPs): for SNP in SNPs: if SNP[1] == i: listWantSitesVCF.append(SNP) else: sys.exit('ERROR: specified position %s not a SNP' % i) quantityWantSites = len(listWantSitesVCF) listWantSitesVCF.reverse() # randomly select SNP sites if positions (-p) unspecified else: quantityWantSites = int(numsites) if quantityWantSites > vcfSNPs: print 'Number of requested SNP sites to investigate exceeds number of identified SNPs' print 'Selecting all %s putative SNP sites to print...' % vcfSNPs quantityWantSites = vcfSNPs randSitesUnsorted = random.sample( SNPs, quantityWantSites) #randomly selected sites to investigate listWantSitesVCF = sorted(randSitesUnsorted, key=itemgetter(1), reverse=True) #calculate page and frames doc = Platypus.BaseDocTemplate(output, topMargin=0, bottomMargin=0, leftMargin=10, rightMargin=0) doc.pagesize = landscape(A4) #ISO Code A4 # A4 Dimensions: 297 mm x 210 mm ; 11.69 in x 8.27 in ; 842 pt x 595 pt frameCount = 2 #(numsites + (-numsites%6)) // 6 frameWidth = doc.height / frameCount frameHeight = doc.width - .05 * inch frames = [] #construct a frame for each column for frame in range(frameCount): leftMargin = doc.leftMargin + frame * frameWidth column = Platypus.Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight) frames.append(column) template = Platypus.PageTemplate(frames=frames) doc.addPageTemplates(template) PAGE_HEIGHT = defaultPageSize[0] #size in points PAGE_WIDTH = defaultPageSize[1] styles = getSampleStyleSheet() style = styles['Normal'] style.fontName = 'Courier' style.fontSize = 6.5 Title = ('Report containing ' + str(quantityWantSites) + ' of ' + str(vcfSNPs) + ' putative SNPs for ' + os.path.basename(invcf)) report = [Paragraph(Title, styles['Heading2'])] while quantityWantSites > 0: posMinusFitty = (listWantSitesVCF[quantityWantSites - 1][1] - 50) centeredPos = max( posMinusFitty, 0) #handles SNP sites at beginning of chrom (<50 bases in) pileup = Platypus.Preformatted( get_ttview(inbam, infasta, listWantSitesVCF[quantityWantSites - 1][0], centeredPos, rows), style) pos = str(listWantSitesVCF[quantityWantSites - 1][1]) QUAL = str(listWantSitesVCF[quantityWantSites - 1][2]) DP = str(listWantSitesVCF[quantityWantSites - 1][3]) MQ = str(listWantSitesVCF[quantityWantSites - 1][4]) SNP = str(listWantSitesVCF[quantityWantSites - 1][5]) header = Paragraph( SNP + ' at position ' + pos + ' with a QUAL of ' + QUAL + ', MQ of ' + MQ + ', and raw read depth (DP) of ' + DP, styles['Heading6']) gap = Platypus.Spacer(0.25, 0.05 * inch) report.append(Platypus.KeepTogether([gap, header, pileup])) quantityWantSites -= 1 doc.build(report)
"azzeertytui", "jkjlkjlkjlllllllllll", "abbbbbbddddkkffffffffffffffffflllllllllllgggggggggggggggggggllll" ] for line in lyrics: textobject.setHorizScale(horizontalscale) textobject.textLine("%s: %s" % (horizontalscale, line)) horizontalscale += 10 textobject.setFillColorCMYK(0.0, 0.4, 0.4, 0.2) textobject.textLines(''' With many apologies to the Beach Boys and anyone else who finds this objectionable ''') canvas.drawText(textobject) c = canvas.Canvas("hello.pdf", landscape(A4)) # move the origin up and to the left c.translate(cm, cm) # define a large font size = 14 c.setFont("Helvetica", size) hello(c) c.showPage() c.setFillColorRGB(0, 0, 0.77) tw = c.stringWidth("COUCOU", "Helvetica", size) c.rect(9.8 * cm, 9.8 * cm, tw, size + 0.2 * cm, fill=1) c.setFillColorRGB(1, 0, 1) c.drawString(10 * cm, 10 * cm, "COUCOU") c.showPage()
def generate(location, watt_averages, breakdown, kwh_and_emissions, func_info, \ comparison_values, default_emissions, default_location): # TODO: remove state_emission and just use location """ Generates the entire pdf report Parameters: location (str): user's location, locations=["Romania", "Brazil"] watt_averages (list): list of baseline, total, process wattage, process duration breakdown (list): [% coal, % oil/petroleum, % natural gas, % low carbon] kwh_and_emissions (list): [kwh used, emission in kg CO2, state emission > 0 for US states] func_info (list): [user func name, user func args (0 or more)] """ Elements = [] kwh, emission, state_emission = kwh_and_emissions baseline_average, process_average, difference_average, process_duration = watt_averages # Initializing document doc = SimpleDocTemplate("energy-usage-report.pdf",pagesize=landscape(letter), topMargin=.3*inch) title("Energy Usage Report", Elements) # Handling header with function name and arguments func_name, *func_args = func_info info_text = " for the function " + func_name if len(func_args) > 0: if len(func_args) == 1: info_text += " with the input " + str(func_args[0]) + "." else: info_text += " with the inputs " for arg in func_args: info_text += arg + "," info_text = info_text[len(info_text)-1] + "." else: info_text += "." subtitle("Energy usage and carbon emissions" + info_text, Elements, spaceBefore=True) # Energy Usage Readings and Energy Mix Data readings_data = [['Energy Usage Readings', ''], ['Average baseline wattage:', "{:.2f} watts".format(baseline_average)], ['Average total wattage:', "{:.2f} watts".format(process_average)], ['Average process wattage:', "{:.2f} watts".format(difference_average)], ['Process duration:', process_duration], ['','']] #hack for the alignment if state_emission: coal, oil, natural_gas, low_carbon = breakdown mix_data = [['Energy Mix Data', ''], ['Coal', "{:.2f}%".format(coal)], ['Oil', "{:.2f}%".format(oil)], ['Natural gas', "{:.2f}%".format(natural_gas)], ['Low carbon', "{:.2f}%".format(low_carbon)]] else: coal, petroleum, natural_gas, low_carbon = breakdown mix_data = [['Energy Mix Data', ''], ['Coal', "{:.2f}%".format(coal)], ['Petroleum', "{:.2f}%".format(petroleum)], ['Natural gas', "{:.2f}%".format(natural_gas)], ['Low carbon', "{:.2f}%".format(low_carbon)]] readings_and_mix_table(readings_data, mix_data, breakdown, state_emission, location, Elements) report_header(kwh, emission, Elements) report_equivalents(emission, state_emission, Elements) comparison_graphs(comparison_values, location, emission, default_emissions, default_location, Elements) doc.build(Elements)
def __init__(self,fi,program,title='This is the title',logo=None,site='',auth='',docid='',worklist=''): # site and auth self.site = site self.auth = auth self.docid = docid self.worklist = worklist self.program = program # get document self.doc = BaseDocTemplate(fi, rightMargin=rightMargin, leftMargin=leftMargin, topMargin=topMargin, bottomMargin=bottomMargin, leftPadding = 0, rightPadding = 0, topPadding = 0, bottomPadding = 0, showBoundary=0) # style sheets self.styles = getSampleStyleSheet() self.styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) self.styles.add(ParagraphStyle(name='Warning', backColor = '#FFFF00', borderColor = "#000000")) self.styles.add(ParagraphStyle(name='tiny', fontSize=4, leading=4, alignment=TA_CENTER)) self.styles.add(ParagraphStyle(name='small', fontSize=6, leading=6)) self.styles.add(ParagraphStyle(name='normal', fontSize=8, leading=6)) self.styles.add(ParagraphStyle(name='big', fontSize=10, leading=6)) self.styles.add(ParagraphStyle(name='huge', fontSize=12, leading=6)) # add Page templates frame1 = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height) frame2 = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.height, self.doc.width) ptemplate = PageTemplate(id='portrait',frames =[frame1], onPage=lambda canvas, doc: canvas.setPageSize(A4)) ltemplate = PageTemplate(id='landscape',frames =[frame2], onPage=lambda canvas, doc: canvas.setPageSize(landscape(A4))) self.doc.addPageTemplates([ptemplate, ltemplate]) # flowable elements self.elements = [] # Header logo = Image(os.path.join(imageDir,logo),width=1.32*inch,height=0.7*inch) if logo else Paragraph('LOGO', self.styles["Heading1"]) titl = Paragraph('%s' % title, self.styles["Heading2"]) date = Paragraph('<font size=10>Generated on %s</font>' % time.ctime(), self.styles["Normal"]) self.elements.append(Table([[logo,titl],['',date]], colWidths=[1.5*inch,4.5*inch], style=[ ('SPAN',(0,0),(0,1)), ('VALIGN',(0,0),(-1,-1),'BOTTOM'), ('VALIGN',(1,1),(-1,-1),'TOP'), ('ALIGN',(1,0),(-1,-1),'LEFT') ])) self.elements.append(Spacer(1, 12)) # header fields TABLE_STYLE = TableStyle([ ('ALIGN',(0,0),(-1,-1),'RIGHT'), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('FONTSIZE',(0,1),(-1,-1),8), ('INNERGRID', (0,0), (1,0), 0.25, colors.black), ('BOX', (0,0), (1,0), 1, colors.black), ('BACKGROUND', (0,0), (0,0), colors.cyan), ('INNERGRID', (3,0), (4,0), 0.25, colors.black), ('BOX', (3,0), (4,0), 1, colors.black), ('BACKGROUND', (3,0), (3,0), colors.cyan), ('INNERGRID', (6,0), (7,0), 0.25, colors.black), ('BOX', (6,0), (7,0), 1, colors.black), ('BACKGROUND', (6,0), (6,0), colors.cyan) ]) self.elements.append(Spacer(1, 2)) data = [[ 'Date','','','Operator','','','Worklist',self.worklist]] t = Table(data, \ colWidths=[2.3*cm, 2.3*cm, 0.7*cm, 2.3*cm, 2.3*cm, 0.7*cm, 2.3*cm, 3.0*cm], rowHeights=0.6*cm) t.setStyle(TABLE_STYLE) self.elements.append(t) self.elements.append(Spacer(1, 12))
def myLandscapePage(canvas, doc): canvas.saveState() canvas.setPageSize(landscape(letter)) canvas.setFont('Times-Roman', 9) canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, "")) canvas.restoreState()
from datetime import date from datetime import timedelta import time from reportlab.lib import colors from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter,landscape,inch from reportlab.platypus import Table, TableStyle operaciones = {0:'ANTES DE APLICAR INSULINA 8PM', 1: 'A LAS 3AM', 2:'AYUNAS', 3:'2 HORAS DESPUES DEL ALMUERZO'} weekday = {0:'LUNES', 1:'MARTES', 2:'MIERCOLES', 3:'JUEVES', 4:'VIERNES', 5:'SABADO', 6:'DOMINGO'} months = {1:'ENERO', 2:'FEBRERO', 3:'MARZO', 4:'ABRIL', 5:'MAYO', 6:'JUNIO', 7:'JULIO', 8:'AGOSTO', 9: 'SEPTIEMBRE', 10:'OCTUBRE', 11:'NOVIEMBRE', 12:'DICIEMBRE'} myCanvas = canvas.Canvas("glucosa.pdf", pagesize=landscape(letter)) def getInfo(): global operaciones print ("Que año desea empezar:") anio = input() print ("Que mes desea empezar:") mes = input() print ("Que día desea empezar:") dia = input() print ("Seleccione en que momento desea iniciar (número): ") print (operaciones) start = int(input()) fecha = date(int(anio), int(mes), int(dia)) # start = 2 print ("Cuántos meses desea generar en total?")
def __init__(self, sessions): PDFBase.__init__(self, story=[]) self.sessions = sessions self.PAGE_WIDTH, self.PAGE_HEIGHT = landscape(A4)
def simple_table(tables_1, tables_2, fk, tblViews): # print(fk) canv = canvas.Canvas("example.pdf", pagesize=landscape(A4)) coords = ([50, 450], [200, 450], [50, 300], [200, 300], [50, 150], [200, 150], [350, 450], [500, 450], [350, 300], [500, 300], [350, 150], [500, 150]) def drawTable(table, cX, cY, targetcell, tblViews): data = [[str(table[0]) + "/" + str(table[1])]] y = 2 for x in table[2:]: try: data.append([table[y]]) y += 1 except (IndexError): break # print(data) idx = data.index([targetcell]) t = Table(data, int(len(data[0])) * [1.3 * inch], 13) t.setStyle( TableStyle([ ('BACKGROUND', (0, 0), (0, 0), colors.gray), ('BACKGROUND', (0, idx), (0, idx), colors.yellow), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) t.setStyle( TableStyle([('BACKGROUND', (0, idx), (0, idx), colors.yellow)])) t.wrap(0, 0) t.drawOn(canv, cX, cY) canv.setFont("Helvetica", 8) for x in tblViews: if table[0] == x[2] and table[1] == x[3]: canv.drawString(cX, cY - 15, "Used in view " + str(x[0]) + "/" + str(x[1])) def getTable(arg1, arg2): for x in tables_1: if arg1 == x[0] and arg2 == x[1]: return x def getTable2(arg1, arg2): for x in tables_2: if arg1 == x[0] and arg2 == x[1]: return x toDraw = [] for i in fk: toDraw.append(getTable(i[0], i[1])) toDraw.append(getTable2(i[3], i[4])) # print(tblViews) targetCells = [] g = 0 for x in fk: targetCells.append(fk[g][2]) targetCells.append(fk[g][5]) g += 1 # print(targetCells) z = 0 for x in toDraw: # print(x) drawTable(x, coords[z][0], coords[z][1], targetCells[z], tblViews) z += 1 canv.save()
def build_pdf(self, response): CONTATO = 0 TELEFONES_PREFERENCIAL = 1 CIDADE = 0 ENDERECO = 1 BAIRRO = 2 NUMERO = 3 GRUPO = 4 ID = 5 NOME = 6 self.set_headings() self.set_styles() self.set_cabec(self.h5) estilo = self.h_style corpo_relatorio = [] self.add_relat_title(corpo_relatorio) registros = self.get_data() for dados in registros: endereco = ','.join(dados[CONTATO][ENDERECO:NUMERO]) item = [ Paragraph(dados[CONTATO][CIDADE], estilo), Paragraph(dados[CONTATO][GRUPO], estilo), Paragraph(dados[CONTATO][NOME], estilo), Paragraph(endereco, estilo), Paragraph(dados[TELEFONES_PREFERENCIAL], estilo), ] corpo_relatorio.append(item) style = TableStyle([ ('FONTSIZE', (0, 0), (-1, -1), 8), ('LEADING', (0, 0), (-1, -1), 7), ('GRID', (0, 0), (-1, -1), 0.1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (-1, -1), 3), ('RIGHTPADDING', (0, 0), (-1, -1), 3), ]) style.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE') for i, value in enumerate(corpo_relatorio): if len(value) <= 1: style.add('SPAN', (0, i), (-1, i)) if len(value) == 0: style.add('INNERGRID', (0, i), (-1, i), 0, colors.black), style.add('GRID', (0, i), (-1, i), -1, colors.white) style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) if len(value) == 1: style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) rowHeights = 20 t = LongTable(corpo_relatorio, rowHeights=rowHeights, splitByRow=True) t.setStyle(style) if len(t._argW) == 5: t._argW[0] = 1.8 * cm t._argW[1] = 6 * cm t._argW[2] = 6.5 * cm t._argW[3] = 9.5 * cm t._argW[4] = 2.4 * cm elif len(t._argW) == 4: t._argW[0] = 2 * cm t._argW[1] = 10 * cm t._argW[2] = 11.5 * cm t._argW[3] = 3 * cm for i, value in enumerate(corpo_relatorio): if len(value) == 0: t._argH[i] = 7 continue for cell in value: if isinstance(cell, list): t._argH[i] = (rowHeights) * (len(cell) - (0 if len(cell) > 1 else 0)) break elements = [t] doc = SimpleDocTemplate(response, pagesize=landscape(A4), rightMargin=1.25 * cm, leftMargin=1.25 * cm, topMargin=1.1 * cm, bottomMargin=0.8 * cm) doc.build(elements)
def __init__(self, flist, font_path=None, style_path=None, def_dpi=300): log.info('Using stylesheets: %s' % ','.join(flist)) # find base path if hasattr(sys, 'frozen'): self.PATH = os.path.abspath(os.path.dirname(sys.executable)) else: self.PATH = os.path.abspath(os.path.dirname(__file__)) # flist is a list of stylesheet filenames. # They will be loaded and merged in order. # but the two default stylesheets will always # be loaded first flist = [ os.path.join(self.PATH, 'styles', 'styles.style'), os.path.join(self.PATH, 'styles', 'default.style'), ] + flist self.def_dpi = def_dpi if font_path is None: font_path = [] font_path += ['.', os.path.join(self.PATH, 'fonts')] self.FontSearchPath = list(map(os.path.expanduser, font_path)) if style_path is None: style_path = [] style_path += [ '.', os.path.join(self.PATH, 'styles'), '~/.rst2pdf/styles', ] self.StyleSearchPath = list(map(os.path.expanduser, style_path)) # Remove duplicates but preserve order. Not very efficient, but these are short lists self.FontSearchPath = [ x for (i, x) in enumerate(self.FontSearchPath) if self.FontSearchPath.index(x) == i ] self.StyleSearchPath = [ x for (i, x) in enumerate(self.StyleSearchPath) if self.StyleSearchPath.index(x) == i ] log.info('FontPath:%s' % self.FontSearchPath) log.info('StylePath:%s' % self.StyleSearchPath) findfonts.flist = self.FontSearchPath # Page width, height self.pw = 0 self.ph = 0 # Page size [w,h] self.ps = None # Margins (top,bottom,left,right,gutter) self.tm = 0 self.bm = 0 self.lm = 0 self.rm = 0 self.gm = 0 # text width self.tw = 0 # Default emsize, later it will be the fontSize of the base style self.emsize = 10 self.languages = [] ssdata = self.readSheets(flist) # Get pageSetup data from all stylessheets in order: self.ps = pagesizes.A4 self.page = {} for data, ssname in ssdata: page = data.get('pageSetup', {}) if page: self.page.update(page) pgs = page.get('size', None) if pgs: # A standard size pgs = pgs.upper() if pgs in pagesizes.__dict__: self.ps = list(pagesizes.__dict__[pgs]) self.psname = pgs if 'width' in self.page: del self.page['width'] if 'height' in self.page: del self.page['height'] elif pgs.endswith('-LANDSCAPE'): self.psname = pgs.split('-')[0] self.ps = list( pagesizes.landscape( pagesizes.__dict__[self.psname])) if 'width' in self.page: del self.page['width'] if 'height' in self.page: del self.page['height'] else: log.critical('Unknown page size %s in stylesheet %s' % (page['size'], ssname)) continue else: # A custom size if 'size' in self.page: del self.page['size'] # The sizes are expressed in some unit. # For example, 2cm is 2 centimeters, and we need # to do 2*cm (cm comes from reportlab.lib.units) if 'width' in page: self.ps[0] = self.adjustUnits(page['width']) if 'height' in page: self.ps[1] = self.adjustUnits(page['height']) self.pw, self.ph = self.ps if 'margin-left' in page: self.lm = self.adjustUnits(page['margin-left']) if 'margin-right' in page: self.rm = self.adjustUnits(page['margin-right']) if 'margin-top' in page: self.tm = self.adjustUnits(page['margin-top']) if 'margin-bottom' in page: self.bm = self.adjustUnits(page['margin-bottom']) if 'margin-gutter' in page: self.gm = self.adjustUnits(page['margin-gutter']) if 'spacing-header' in page: self.ts = self.adjustUnits(page['spacing-header']) if 'spacing-footer' in page: self.bs = self.adjustUnits(page['spacing-footer']) if 'firstTemplate' in page: self.firstTemplate = page['firstTemplate'] # tw is the text width. # We need it to calculate header-footer height # and compress literal blocks. self.tw = self.pw - self.lm - self.rm - self.gm # Get page templates from all stylesheets self.pageTemplates = {} for data, ssname in ssdata: templates = data.get('pageTemplates', {}) # templates is a dictionary of pageTemplates for key in templates: template = templates[key] # template is a dict. # template[´frames'] is a list of frames if key in self.pageTemplates: self.pageTemplates[key].update(template) else: self.pageTemplates[key] = template # Get font aliases from all stylesheets in order self.fontsAlias = {} for data, ssname in ssdata: self.fontsAlias.update(data.get('fontsAlias', {})) embedded_fontnames = [] self.embedded = [] # Embed all fonts indicated in all stylesheets for data, ssname in ssdata: embedded = data.get('embeddedFonts', []) for font in embedded: try: # Just a font name, try to embed it if isinstance(font, str): # See if we can find the font fname, pos = findfonts.guessFont(font) if font in embedded_fontnames: pass else: fontList = findfonts.autoEmbed(font) if fontList: embedded_fontnames.append(font) if not fontList: if (fname, pos) in embedded_fontnames: fontList = None else: fontList = findfonts.autoEmbed(fname) if fontList is not None: self.embedded += fontList # Maybe the font we got is not called # the same as the one we gave # so check that out suff = ["", "-Oblique", "-Bold", "-BoldOblique"] if not fontList[0].startswith(font): # We need to create font aliases, and use them for fname, aliasname in zip( fontList, [font + suffix for suffix in suff], ): self.fontsAlias[aliasname] = fname continue # Each "font" is a list of four files, which will be # used for regular / bold / italic / bold+italic # versions of the font. # If your font doesn't have one of them, just repeat # the regular font. # Example, using the Tuffy font from # http://tulrich.com/fonts/ # "embeddedFonts" : [ # ["Tuffy.ttf", # "Tuffy_Bold.ttf", # "Tuffy_Italic.ttf", # "Tuffy_Bold_Italic.ttf"] # ], # The fonts will be registered with the file name, # minus the extension. if font[0].lower().endswith('.ttf'): # A True Type font for variant in font: location = self.findFont(variant) pdfmetrics.registerFont( TTFont(str(variant.split('.')[0]), location)) log.info('Registering font: %s from %s' % (str(variant.split('.')[0]), location)) self.embedded.append(str(variant.split('.')[0])) # And map them all together regular, bold, italic, bolditalic = [ variant.split('.')[0] for variant in font ] addMapping(regular, 0, 0, regular) addMapping(regular, 0, 1, italic) addMapping(regular, 1, 0, bold) addMapping(regular, 1, 1, bolditalic) else: # A Type 1 font # For type 1 fonts we require # [FontName,regular,italic,bold,bolditalic] # where each variant is a (pfbfile,afmfile) pair. # For example, for the URW palladio from TeX: # ["Palatino",("uplr8a.pfb","uplr8a.afm"), # ("uplri8a.pfb","uplri8a.afm"), # ("uplb8a.pfb","uplb8a.afm"), # ("uplbi8a.pfb","uplbi8a.afm")] regular = pdfmetrics.EmbeddedType1Face(*font[1]) italic = pdfmetrics.EmbeddedType1Face(*font[2]) bold = pdfmetrics.EmbeddedType1Face(*font[3]) bolditalic = pdfmetrics.EmbeddedType1Face(*font[4]) except Exception as e: try: if isinstance(font, list): fname = font[0] else: fname = font log.error( "Error processing font %s: %s", os.path.splitext(fname)[0], str(e), ) log.error("Registering %s as Helvetica alias", fname) self.fontsAlias[fname] = 'Helvetica' except Exception as e: log.critical("Error processing font %s: %s", fname, str(e)) continue # Go though all styles in all stylesheets and find all fontNames. # Then decide what to do with them for data, ssname in ssdata: for [skey, style] in self.stylepairs(data): for key in style: if key == 'fontName' or key.endswith('FontName'): # It's an alias, replace it if style[key] in self.fontsAlias: style[key] = self.fontsAlias[style[key]] # Embedded already, nothing to do if style[key] in self.embedded: continue # Standard font, nothing to do if style[key] in ( "Courier", "Courier-Bold", "Courier-BoldOblique", "Courier-Oblique", "Helvetica", "Helvetica-Bold", "Helvetica-BoldOblique", "Helvetica-Oblique", "Symbol", "Times-Bold", "Times-BoldItalic", "Times-Italic", "Times-Roman", "ZapfDingbats", ): continue # Now we need to do something # See if we can find the font fname, pos = findfonts.guessFont(style[key]) fontList = findfonts.autoEmbed(style[key]) if style[key] not in embedded_fontnames and fontList: embedded_fontnames.append(style[key]) if not fontList: if (fname, pos) in embedded_fontnames: fontList = None else: fontList = findfonts.autoEmbed(fname) if fontList: embedded_fontnames.append((fname, pos)) if fontList: self.embedded += fontList # Maybe the font we got is not called # the same as the one we gave so check that out suff = ["", "-Bold", "-Oblique", "-BoldOblique"] if not fontList[0].startswith(style[key]): # We need to create font aliases, and use them basefname = style[key].split('-')[0] for fname, aliasname in zip( fontList, [basefname + suffix for suffix in suff], ): self.fontsAlias[aliasname] = fname style[key] = self.fontsAlias[basefname + suff[pos]] else: log.error( "Unknown font: \"%s\"," "replacing with Helvetica", style[key], ) style[key] = "Helvetica" # Get styles from all stylesheets in order self.stylesheet = {} self.styles = [] self.linkColor = 'navy' # FIXME: linkColor should probably not be a global # style, and tocColor should probably not # be a special case, but for now I'm going # with the flow... self.tocColor = None for data, ssname in ssdata: self.linkColor = data.get('linkColor') or self.linkColor self.tocColor = data.get('tocColor') or self.tocColor for [skey, style] in self.stylepairs(data): sdict = {} # FIXME: this is done completely backwards for key in style: # Handle color references by name if key == 'color' or key.endswith('Color') and style[key]: style[key] = formatColor(style[key]) elif key == 'commands': style[key] = validateCommands(style[key]) # Handle alignment constants elif key == 'alignment': style[key] = dict( TA_LEFT=0, LEFT=0, TA_CENTER=1, CENTER=1, TA_CENTRE=1, CENTRE=1, TA_RIGHT=2, RIGHT=2, TA_JUSTIFY=4, JUSTIFY=4, DECIMAL=8, )[style[key].upper()] elif key == 'language': if not style[key] in self.languages: self.languages.append(style[key]) sdict[key] = style[key] sdict['name'] = skey # If the style already exists, update it if skey in self.stylesheet: self.stylesheet[skey].update(sdict) else: # New style self.stylesheet[skey] = sdict self.styles.append(sdict) # If the stylesheet has a style name docutils won't reach # make a copy with a sanitized name. # This may make name collisions possible but that should be # rare (who would have custom_name and custom-name in the # same stylesheet? ;-) # Issue 339 styles2 = [] for s in self.styles: if not re.match("^[a-z](-?[a-z0-9]+)*$", s['name']): s2 = copy(s) s2['name'] = docutils.nodes.make_id(s['name']) log.warning( '%s is an invalid docutils class name, adding alias %s' % (s['name'], s2['name'])) styles2.append(s2) self.styles.extend(styles2) # And create reportlabs stylesheet self.StyleSheet = StyleSheet1() dirty = True while dirty: dirty = False for s in self.styles: if s['name'] in self.StyleSheet: continue try: if 'parent' in s: if s['parent'] is None: if s['name'] != 'base': s['parent'] = self.StyleSheet['base'] else: del s['parent'] else: s['parent'] = self.StyleSheet[s['parent']] else: if s['name'] != 'base': s['parent'] = self.StyleSheet['base'] except KeyError: dirty = True continue # If the style has no bulletFontName but it has a fontName, set it if ('bulletFontName' not in s) and ('fontName' in s): s['bulletFontName'] = s['fontName'] hasFS = True # Adjust fontsize units if 'fontSize' not in s: s['fontSize'] = s['parent'].fontSize s['trueFontSize'] = None hasFS = False elif 'parent' in s: # This means you can set the fontSize to # "2cm" or to "150%" which will be calculated # relative to the parent style s['fontSize'] = self.adjustUnits(s['fontSize'], s['parent'].fontSize) s['trueFontSize'] = s['fontSize'] else: # If s has no parent, it's base, which has # an explicit point size by default and % # makes no sense, but guess it as % of 10pt s['fontSize'] = self.adjustUnits(s['fontSize'], 10) # If the leading is not set, but the size is, set it if 'leading' not in s and hasFS: s['leading'] = 1.2 * s['fontSize'] # If the bullet font size is not set, set it as fontSize if ('bulletFontSize' not in s) and ('fontSize' in s): s['bulletFontSize'] = s['fontSize'] if 'spaceBefore' in s: if isinstance(s['spaceBefore'], str) and s['spaceBefore'].startswith('-'): log.warning('A negative spaceBefore is the same as 0') s['spaceBefore'] = self.adjustUnits(s['spaceBefore']) if 'spaceAfter' in s: if isinstance(s['spaceAfter'], str) and s['spaceAfter'].startswith('-'): log.warning('A negative spaceAfter is the same as 0') s['spaceAfter'] = self.adjustUnits(s['spaceAfter']) self.StyleSheet.add(ParagraphStyle(**s)) self.emsize = self['base'].fontSize # Make stdFont the basefont, for Issue 65 reportlab.rl_config.canvas_basefontname = self['base'].fontName # Make stdFont the default font for table cell styles (Issue 65) reportlab.platypus.tables.CellStyle.fontname = self['base'].fontName
def create_pdf(self): body = [] styles = getSampleStyleSheet() spacer1 = Spacer(0, 0.25 * inch) spacer2 = Spacer(0, 0.5 * inch) tblstyle = TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('LEFTPADDING', (0, 0), (-1, -1), 5), ('RIGHTPADDING', (0, 0), (-1, -1), 5), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]) for s in range(len(self.datatable)): if self.rptdata[s] is not None: if self.datatable[s].find("_") != -1: title = (self.datatable[s].replace("_", " ")) else: title = (' '.join( re.findall('([A-Z][a-z]*)', self.datatable[s]))) # provide the table name for the page header ptext = '<font size=14>%s</font>' % title + self.ttl body.append(Paragraph(ptext, styles["Heading2"])) line = LineDrw(500) body.append(line) body.append(spacer2) for pg in range(0, len(self.rptdata[s]), 3): n = 0 for i in self.columnames[s][0]: # add the requirement process type and notes ptxt = ("<b>{0}:</b> {1}<br/>".format( i, self.rptdata[s][pg][n])) body.append(Paragraph(ptxt, styles["Normal"])) body.append(spacer1) n += 1 if self.datatable[s] == 'Piping': txt = 'Pipe Material' else: txt = 'Tube Material' ptext = '<font size=14>%s</font>' % txt body.append(Paragraph(ptext, styles["Heading3"])) line = LineDrw(100) body.append(line) body.append(spacer1) # this populates the upper table tbldata = [] tbldata.append(self.columnames[s][1]) rowdata = self.rptdata[s][pg + 1] if rowdata != []: for seg in rowdata: m = 0 seg = list(seg) for item in seg: # wrap any text which is longer than # 10 characters if type(item) == str: if len(item) >= 10: item = Paragraph( item, styles['Normal']) seg[m] = item m += 1 tbldata.append(tuple(seg)) colwdth1 = [] for i in self.colms[s][1]: colwdth1.append(i * self.textAdjust) tbl1 = Table(tbldata, colWidths=colwdth1) tbl1.setStyle(tblstyle) body.append(tbl1) body.append(spacer2) if self.datatable[s] == 'Piping': txt = 'Pipe Nipples' else: txt = 'Tube Valves' ptext = '<font size=14>%s</font>' % txt body.append(Paragraph(ptext, styles["Heading3"])) line = LineDrw(100) body.append(line) body.append(spacer1) # this populates the lower table tbldata = [] tbldata.append(self.columnames[s][2]) rowdata = self.rptdata[s][pg + 2] if rowdata != []: for seg in rowdata: if seg is None: continue m = 0 seg = list(seg) for item in seg: # wrap any text which is longer than # 10 characters if type(item) == str: if len(item) >= 10: item = Paragraph( item, styles['Normal']) seg[m] = item m += 1 tbldata.append(tuple(seg)) colwdth1 = [] for i in self.colms[s][2]: colwdth1.append(i * self.textAdjust) tbl1 = Table(tbldata, colWidths=colwdth1) tbl1.setStyle(tblstyle) body.append(tbl1) body.append(PageBreak()) w, h = tbl1.wrap(15, 15) else: if self.datatable[s].find("_") != -1: title = (self.datatable[s].replace("_", " ")) else: title = (' '.join( re.findall('([A-Z][a-z]*)', self.datatable[s]))) # provide the table name for the page header ptext = '<font size=14>%s</font>' % title + self.ttl body.append(Paragraph(ptext, styles["Heading2"])) line = LineDrw(500) body.append(line) txt = 'Not Data Set Up for this Item' ptext = '<font size=12>%s</font>' % txt body.append(Paragraph(ptext, styles["Heading2"])) doc = SimpleDocTemplate('tmp_rot_file.pdf', pagesize=landscape(letter), rightMargin=.5 * inch, leftMargin=.5 * inch, topMargin=.75 * inch, bottomMargin=.5 * inch) doc.build(body) pdf_old = open('tmp_rot_file.pdf', 'rb') pdf_reader = PyPDF4.PdfFileReader(pdf_old) pdf_writer = PyPDF4.PdfFileWriter() for pagenum in range(pdf_reader.numPages): page = pdf_reader.getPage(pagenum) page.rotateCounterClockwise(90) pdf_writer.addPage(page) pdf_out = open(self.filename, 'wb') pdf_writer.write(pdf_out) pdf_out.close() pdf_old.close() os.remove('tmp_rot_file.pdf')
for a in pessoa: a = re.sub("\n", "", a) a = a.replace('\n', '') print(pessoa) try: nome = pessoa[0] + " " + pessoa[1] except: nome = pessoa print("Contruindo certificado de " + nome) #gera nome do certificado, gera o arquivo do certificado e o título do arquivo filename = os.path.join(titulo, nome + ' - Certificado ' + titulo + '.pdf') c = canvas.Canvas(filename, pagesize=landscape(A4)) c.setTitle(nome + " - Certificado" + titulo) #poe o background no fundo do certificado cW, cH = c._pagesize c.drawInlineImage(background, 0, 0, width=cW, height=cH) #coloca texto, linha por linha no documento, alinhados à posição (400, 380) if (PouM == 1): dec = [ 'Declaramos para os devidos fins que o/a discente ' + str(nome), 'participou do minicurso de ', str(titulo) + ' no dia ' + DataTexto(data), 'no evento "Ada Lovelace Week", realizado pelo Centro Acadêmico', '"Ada Lovelace" da UNESP Bauru, com duração de 1 hora.', 'Bauru, ' + DataTexto(datetime.now().strftime('%d/%m/%Y'))
def ver_reporte_input_fechas(request, id): docente = get_object_or_404(Docente, user_ptr=request.user) asignatura = get_object_or_404(Asignatura, codigo=id) periodo = get_object_or_404(Periodo, estado=True) asignaturas = DocenteAsignaturaPeriodo.objects.filter(asignatura=asignatura, periodo=periodo, docente=docente) estiloHoja = getSampleStyleSheet() cabecera = estiloHoja['Heading4'] cabecera.pageBreakBefore = 0 cabecera.keepWithNext = 0 story = [] estilo = estiloHoja['BodyText'] fichero_imagen = "elviajedelnavegante_png.png" imagen_logo = Image("logo.png", width=400, height=100) story.append(imagen_logo) story.append(Spacer(0, 10)) parrafo = Paragraph("Docente: " + docente.get_full_name() + " - " + docente.cedula, estilo) story.append(parrafo) story.append(Spacer(0, 10)) estilo = estiloHoja['BodyText'] # asigestudiante = DocenteAsignaturaPeriodoEstudiante.objects.filter(docenteasignatura__in=asigperiodo, estudiante = estudiante) #horario = Horario.objects.filter(asignatura__in=asigperiodo) if request.method == 'POST': form = FechasReporte(request.POST) if form.is_valid(): inicio = form['inicio'].value() fin = form['fin'].value() for i in asignaturas: datos = [] horario = Horario.objects.filter(asignatura=i) temas = Tema.objects.filter(horario__in=horario, fecha__range=(inicio, fin)) if temas.exists(): parrafo = Paragraph(i.asignatura.descripcion, cabecera) fila_inicial = ['Tema', 'Fecha', 'Hora', 'Estado'] story.append(parrafo) datos.append(fila_inicial) for t in temas: fila = [t.nombre, t.fecha, t.horario.get_inicio_display(), t.get_estado_display()] datos.append(fila) tabla = Table(datos) tabla.normalizeData(datos) tabla.setStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) tabla.setStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black)]) story.append(tabla) story.append(Spacer(0, 20)) ahora = time.strftime("%x %X") parrafo = Paragraph("Generado por: " + docente.get_full_name(), cabecera) story.append(parrafo) story.append(Spacer(0, 10)) parrafo = Paragraph(ahora, cabecera) story.append(parrafo) doc = SimpleDocTemplate(docente.cedula + "-"+asignatura.codigo+".pdf", pagesize=landscape(A4), showBoundary=0) doc.build(story) output = open(docente.cedula + "-"+asignatura.codigo+".pdf") response = HttpResponse(output, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=' +docente.cedula + "-"+asignatura.codigo+".pdf" return response else: form = FechasReporte() return render(request, 'estudiante/form_reporte.html', {'form': form}, context_instance=RequestContext(request))
def build_pdf(self, response): cleaned_data = self.filterset.form.cleaned_data agrupamento = cleaned_data['agrupamento'] elements = [] #print('data ini', datetime.now()) data = self.get_data() #print('data fim', datetime.now()) style = TableStyle([ ('FONTSIZE', (0, 0), (-1, -1), 8), ('LEADING', (0, 0), (-1, -1), 7), ('GRID', (0, 0), (-1, -1), 0.1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (-1, -1), 3), ('RIGHTPADDING', (0, 0), (-1, -1), 3), ]) style.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE') #print('enumerate ini', datetime.now()) for i, value in enumerate(data): if len(value) <= 1: style.add('SPAN', (0, i), (-1, i)) if len(value) == 0: style.add('INNERGRID', (0, i), (-1, i), 0, colors.black), style.add('GRID', (0, i), (-1, i), -1, colors.white) style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) if len(value) == 1: style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) #print('enumerate fim', datetime.now()) # if not agrupamento or agrupamento == 'sem_agrupamento': # style.add('ALIGN', (0, 0), (0, -1), 'CENTER') #print('table ini', datetime.now()) rowHeights = 20 t = LongTable(data, rowHeights=rowHeights, splitByRow=True) t.setStyle(style) if len(t._argW) == 5: t._argW[0] = 1.8 * cm t._argW[1] = 6 * cm t._argW[2] = 6.5 * cm t._argW[3] = 9.5 * cm t._argW[4] = 2.4 * cm elif len(t._argW) == 4: t._argW[0] = 2 * cm t._argW[1] = 10 * cm t._argW[2] = 11.5 * cm t._argW[3] = 3 * cm for i, value in enumerate(data): if len(value) == 0: t._argH[i] = 7 continue for cell in value: if isinstance(cell, list): t._argH[i] = (rowHeights) * (len(cell) - (0 if len(cell) > 1 else 0)) break elements.append(t) #print('table fim', datetime.now()) #print('build ini', datetime.now()) doc = SimpleDocTemplate(response, pagesize=landscape(A4), rightMargin=1.25 * cm, leftMargin=1.25 * cm, topMargin=1.1 * cm, bottomMargin=0.8 * cm) doc.build(elements)
def generate_pdf(self): buffer = self.buffer doc = BaseDocTemplate( buffer, rightMargin=0.3 * inch, leftMargin=0.3 * inch, topMargin=0.3 * inch, bottomMargin=inch / 4, ) land_frame = Frame(0, 0, self.height, self.width, id='LFrame') land_frame._topPadding = 22 land_frame._leftPadding = 11 land_frame._bottomPadding = 22 port_frame = Frame(0, 0, self.width, self.height, id='PFrame') port_frame._topPadding = 22 port_frame._leftPadding = 11 port_frame._bottomPadding = 22 landscape_temp = PageTemplate(id='landscape_temp', frames=[ land_frame, ], pagesize=landscape(self.pagesize)) portrait_temp = PageTemplate(id='portrait_temp', frames=[ port_frame, ], pagesize=self.pagesize) # Our container for 'Flowable' objects elements = [] # A large collection of style sheets pre-made for us styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. template_list = [] for result in self.results: # image = 'http://127.0.0.1:8000' + result.image.url image = self.path_relative_to_file(__file__, '..' + result.image.url) # image = result.image.url im = self.scale_image(image) im.hAlign = 'CENTER' im.vAlign = 'MIDDLE' img = utils.ImageReader(image) width, height = img.getSize() if width > height: next_page = NextPageTemplate('landscape_temp') next_page.hAlign = 'CENTER' next_page.vAlign = 'MIDDLE' next_page.height = self.width next_page.width = self.height template_list.append(landscape_temp) elements.append(next_page) else: next_page = NextPageTemplate('portrait_temp') next_page.hAlign = 'CENTER' next_page.vAlign = 'MIDDLE' next_page.height = self.height next_page.width = self.width template_list.append(portrait_temp) elements.append(next_page) elements.append(im) #elements.append(PageBreak()) doc.addPageTemplates(template_list) doc.build(elements) # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() return pdf