def create_doc(ori='l', file=''): """ Creates document element for reportlab usage :param file: pdf file name (with .pdf extenstion) :param ori: orientation 'l' indicates landscape(default) if portrait specify p size is A4 :return: document object where we can add elements and build it to create pdf. """ if '\\' in file or '/' in file: doc = SimpleDocTemplate(file, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) else: doc = SimpleDocTemplate(getcwd() + '\\' + str(file), pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) if ori == 'l': doc.pagesize = landscape(A4) else: doc.pagesize = A4 return doc
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 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 write_pdf(data, file_name): """Method to write pdf given data.""" try: pdf_name = '%s/%s.pdf' % (MEDIA_ROOT, file_name) doc = SimpleDocTemplate( pdf_name, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] # TODO: Get this line right instead of just copying it from the # docs style = TableStyle( [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)]) # Configure style and word wrap 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) # Send the data and build the file elements.append(t) doc.build(elements, onFirstPage=draw_page, onLaterPages=draw_page) except Exception, e: raise e
def PrintPdf(projectNo, probeInf, holelist, index=None): import os from config import basedir cptPath = os.path.join(basedir, 'app', 'static', 'download') if not os.path.exists(cptPath): os.makedirs(cptPath) doc = SimpleDocTemplate(cptPath, pagesize=A4, rightMargin=10, leftMargin=20, topMargin=30, bottomMargin=20) doc.pagesize = portrait(A4) filename = '' elements = [] for i in range(len(holelist)): if index is not None: i = index filename = projectNo + '__' + holelist[i].holeName + '.pdf' # Attenion:where elments.extend must be used,but not elements.append elements.extend(Cpt2Pdf(holelist[i], probeInf)) break else: filename = projectNo + '__' + 'all.pdf' # Attenion:where elments.extend must be used,but not elements.append elements.extend(Cpt2Pdf(holelist[i], probeInf)) doc.filename = os.path.join(cptPath, filename) print("dd" + doc.filename) doc.build(elements) # url='/'.join(['download',projectNo,filename]) # os.path.join('download',projectNo,filename)将返回download\projectNo\filename,浏览器无法识别 return doc.filename
def generate_pdf(table_header, datas): """ 生成pdf :return: """ path = "test.pdf" data = list() # 添加table table = table_model(table_header, datas) data.append(table) data.append(PageBreak()) # 分页标识 # 设置生成pdf的名字和编剧 pdf = SimpleDocTemplate(path, rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0) # 设置pdf每页的大小 pdf.pagesize = (20 * inch, 16 * inch) pdf.multiBuild(data) # buff.seek(0) # return buff return path
def generate_pdf(data): output = BytesIO() doc = SimpleDocTemplate(output, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] 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) return output
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 generate_week_report(self, cr, uid): user_ids = self._get_user(cr, uid, group1=True) if user_ids: for user in user_ids: res = self._query_report(cr, uid, user_id=user.id) if res: email = user.email if self.validate_email(user.email) else None # CONTENT styles = getSampleStyleSheet() elements = [] title = u'Reporte Semanal de Cobranza' style_h_one = styles['Heading1'] elements.append(Paragraph(title, style_h_one)) elements.append(Spacer(1, 0.25 * inch)) # PDF pdfreport_fd, pdfreport_path = tempfile.mkstemp(suffix='.pdf', prefix='reporte.cobranza.') body_html = 'Hola <b>%s</b>, <p>Se adjunta el reporte de cobranza de la semana.</p>' % user.name doc = SimpleDocTemplate(pdfreport_path, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) doc.build(self._report_table(cr, uid, res, elements)) attachments = [[title, pdfreport_path]] # EMAIL self.send_mail(cr, uid, attachments=attachments, email_to=email, subject=title, html=body_html, force_send=True) return True
def generate_consolidated_week_report(self, cr, uid): parent_user_ids = self._get_user(cr, uid, group2=True) if parent_user_ids: for manager in parent_user_ids: email = manager.email if self.validate_email(manager.email) else None # CONTENIDO DE REPORTE styles = getSampleStyleSheet() elements = [] title = u'Reporte Semanal de Cobranza Consolidado' style_h_one = styles['Heading1'] elements.append(Paragraph(title, style_h_one)) elements.append(Spacer(1, 0.25 * inch)) # facturas por ejecutivas user_ids = self._get_user(cr, uid, group1=True) for user in user_ids: res = self._query_report(cr, uid, user_id=user.id) elements = self._report_table(cr, uid, res, elements, title=user.name) # facturas sin ejecutivas res = self._query_report(cr, uid) elements = self._report_table(cr, uid, res, elements, title=u'Sin ejecutiva responsable') # PDF pdfreport_fd, pdfreport_path = tempfile.mkstemp(suffix='.pdf', prefix='reporte.cobranza.consol.') body_html = 'Hola <b>%s</b>, <p>Se adjunta el reporte semanal de cobranza consolidado.</p>' % manager.name doc = SimpleDocTemplate(pdfreport_path, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) doc.build(elements) attachments = [[title, pdfreport_path]] # EMAIL self.send_mail(cr, uid, attachments=attachments, email_to=email, subject=title, html=body_html, force_send=True) return True
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 PrintPdf(projectNo, probeInf, holelist, index=None): import os from config import basedir cptPath = os.path.join(basedir, 'app', 'static', 'download') if not os.path.exists(cptPath): os.makedirs(cptPath) doc = SimpleDocTemplate(cptPath, pagesize=A4, rightMargin=10, leftMargin=20, topMargin=30, bottomMargin=20 ) doc.pagesize = portrait(A4) filename = '' elements = [] for i in range(len(holelist)): if index is not None: i = index filename = projectNo + '__' + holelist[i].holeName + '.pdf' # Attenion:where elments.extend must be used,but not elements.append elements.extend(Cpt2Pdf(holelist[i], probeInf)) break; else: filename = projectNo + '__' + 'all.pdf' # Attenion:where elments.extend must be used,but not elements.append elements.extend(Cpt2Pdf(holelist[i], probeInf)) doc.filename = os.path.join(cptPath, filename) print("dd" + doc.filename) doc.build(elements) # url='/'.join(['download',projectNo,filename]) # os.path.join('download',projectNo,filename)将返回download\projectNo\filename,浏览器无法识别 return doc.filename
def saveFileAsPDF(self, name, path): fullData = self.loadData(1) doc = SimpleDocTemplate(path + "\\" + name + ".pdf", pagesize=A4) doc.pagesize = landscape(A4) elements = [] 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 fullData] t = Table(data2) t.setStyle(style) elements.append(t) print(data2) doc.build(elements) print("Test3")
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 pdf_write(generated_pdf_path): """ 生成pdf :return: """ # 增加的字体,支持中文显示,需要自行下载支持中文的字体 font_path = current_app.config.get("SIM_SUN") pdfmetrics.registerFont(TTFont('SimSun', os.path.join(font_path, 'SimSun.ttf'))) styles = getSampleStyleSheet() styles.add(ParagraphStyle(fontName='SimSun', name='SimSun', leading=20, fontSize=12)) data = list() # 添加一段文字 paragraph = paragraph_model("测试添加一段文字") data.append(paragraph) data.append(PageBreak()) # 分页标识 # 添加table和图片 table = table_model() data.append(table) data.append(PageBreak()) # 分页标识 img = image_model() data.append(img) # 设置生成pdf的名字和编剧 pdf = SimpleDocTemplate(generated_pdf_path, rightMargin=0, leftMargin=0, topMargin=40, bottomMargin=0, ) # 设置pdf每页的大小 pdf.pagesize = (9 * inch, 10 * inch) pdf.multiBuild(data) return generated_pdf_path
def go(): doc = SimpleDocTemplate("phello.pdf") doc.pagesize = (6 * inch, 4 * inch) doc.leftMargin = 0.25 * inch doc.bottommargin = 0.25 * inch # doc.height=3.75*inch # doc.width=5.75*inch doc.height = 4 * inch doc.width = 6 * inch Story = [] style = styles["Normal"] for i in range(3): bogustext = ("This is Paragraph number %s. " % i) * 2 p = Paragraph(bogustext, style) # p = Paragraph(bogustext) Story.append(p) # Story.append(Spacer(1,0.2*inch)) l = [] for x in range(3): l.append(["row%i col1" % x, "row%i col2" % i]) Story.append(Table(l)) Story.append(Paragraph("Hello", styles["Title"])) # Story.append(Paragraph("Hello")) #doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc.build(Story)
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 pdf_jeu_genre(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="jeu_genre.pdf"' doc = SimpleDocTemplate(response, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=20) doc.pagesize = A4 elements = [] # Get data games = Game.objects.filter(owner__is_bringing=True).distinct() data = [ ["JEU", "GENRE", "", "JEU", "GENRE"], ] styles = getSampleStyleSheet() # We build the data l = len(games) if l % 2 == 0: sc = l/2 else: sc = l/2+1 for i in range(sc): # in case we have an odd number of elements, we display the last line if l % 2 != 0 and i == l/2: data.append([Paragraph(games[i].name, styles['BodyText']), games[i].type_genre, "", "", ""]) elif i < l: data.append([Paragraph(games[i].name, styles['BodyText']), games[i].type_genre, "", Paragraph(games[i+sc].name, styles['BodyText']), games[i+sc].type_genre]) t = Table(data, colWidths=(None, 60, 50, None, 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), ('INNERGRID', (3, 0), (-1, -1), 0.25, colors.grey), ('BOX', (0, 0), (1, -1), 0.25, colors.grey), ('BOX', (3, 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)])) t.setStyle(TableStyle([('BACKGROUND', (3, each), (-1, each), bg_color)])) # Send the data and build the file elements.append(t) doc.build(elements) return response
def write_pdf(request): now = datetime.datetime.now() name = 'Statistics' + now.strftime("%d-%m-%Y") + '.pdf' doc = SimpleDocTemplate(name, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [ ["<b>S.No.</b>", "<b>Item</b>", "<b>Price</b>", "<b>Quantity</b>"], ] items = Item.objects.all() n = 0 for i in items: total = 0 n += 1 for s in Stock.objects.filter(item=i): total += s.quantity data.append([str(n), str(i.name), str(i.price), str(total)]) # TODO: Get this line right instead of just copying it from the docs 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.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) s = s["BodyText"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t = Table(data2) t.setStyle(style) ptext = '<font size=40>ANNADAATA FOOD CO.OP </font>' elements.append(Paragraph(ptext, s)) elements.append(Spacer(1, 20)) ptext = '<font size=20>Statistics on %s</font>' % (now.strftime("%d-%m-%Y")) elements.append(Paragraph(ptext, s)) elements.append(Spacer(1, 20)) elements.append(t) # Send the data and build the file doc.build(elements) shutil.move(name, "buy/static/pdf/"+name) return redirect('/buy')
def write(self): """Assembles the final PDF and writes to disk.""" pdf_writer = pyPdf.PdfFileWriter() if self.front_matter is not None: front_matter = pyPdf.PdfFileReader(file(self.front_matter, "rb")) for page in range(front_matter.getNumPages()): pdf_writer.addPage(front_matter.getPage(page)) working_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) doc = SimpleDocTemplate(working_file) doc.pagesize = portrait(letter) story = [] styles = getSampleStyleSheet() for section in self.sections: heading_text = section.heading story.append(Paragraph(heading_text, styles['Heading1'])) for content in section.contents: if 'figure' in content: figure = content['figure'] if os.path.exists(figure): im = utils.ImageReader(figure) img_width, img_height = im.getSize() aspect = img_height / float(img_width) story.append( Image(figure, width=img_width, height=(img_width * aspect))) if content.get('caption', None) is not None: caption_text = '<font size=10>{0}</font>'.format( content['caption'].strip()) story.append(Paragraph(caption_text, styles['Italic'])) story.append(Spacer(1, 10)) if 'table' in content: _t = self.build_table(content['table']) story.append(_t) if content.get('caption', None) is not None: caption_text = '<font size=10>{0}</font>'.format( content['caption'].strip()) story.append(Paragraph(caption_text, styles['Italic'])) story.append(Spacer(1, 10)) if 'text' in content: for para in content['text']: story.append(Paragraph(para, styles['Normal'])) story.append(Spacer(1, 12)) doc.build(story) body_matter = pyPdf.PdfFileReader(working_file) for page in range(body_matter.getNumPages()): pdf_writer.addPage(body_matter.getPage(page)) try: os.remove(working_file.name) except OSError: # Windows reports file in use, other OS errors, etc. pass if self.end_matter is not None: end_matter = pyPdf.PdfFileReader(file(self.end_matter, "rb")) for page in range(end_matter.getNumPages()): pdf_writer.addPage(end_matter.getPage(page)) output_stream = file(self.output_filename, "wb") pdf_writer.write(output_stream)
def create_doc(elements): """ Method will create a PDF documents with Images and paragraphs :param elements: List of Paragraph objects and Image objects (PIL images) :return: Creates a PDF document and returns None """ doc = SimpleDocTemplate("{name}.pdf".format(name=save_image.name), pagesize=A4) doc.pagesize = landscape(A4) doc.build(elements, canvasmaker=TemplateCanvas)
def report_pdf(request,id): application = get_object_or_404(Application, id=id) permissions = App_Permission.objects.filter(application = application) doc = SimpleDocTemplate("report.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [] data.append(["User ID","First Name","Last Name","Permission","Reviewed By"]) for permission in permissions: user = permission.regular_user id = user.id firstname = user.first_name lastname = user.last_name status = permission.status if permission.reviewed_by: reviewer = permission.reviewed_by.first_name+" "+permission.reviewed_by.last_name else: reviewer = "None" data.append([str(id),firstname,lastname,status,reviewer]) 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 stylesheet = getSampleStyleSheet() s = stylesheet["BodyText"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t=Table(data2) t.setStyle(style) title = "Access Review Report for " title += application.app_name elements.append(Paragraph(title,stylesheet['Title'])) elements.append(t) doc.build(elements) with open('report.pdf', 'r') as pdf: response = HttpResponse(pdf.read(),content_type='application/pdf') response['Content-Disposition'] = 'filename=report.pdf' return response pdf.closed
def save_as_pdf(self): options = QFileDialog.Options() path, _ = QFileDialog.getSaveFileName(self, options=options) doc = SimpleDocTemplate(path + '.pdf', pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = portrait(A4) elements = [] data = [] for i in range(self.checkpoints_tb.rowCount()): line = [] for j in range(self.checkpoints_tb.columnCount()): if i < 1: line.append( self.checkpoints_tb.horizontalHeaderItem(j).text()) else: line.append(self.checkpoints_tb.item(i, j).text()) data.append(line) im_path = 'im_aux.png' self.save_plot(im_path) style = TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ('TEXTCOLOR', (1, 1), (-2, -2), colors.red), ('VALIGN', (0, 0), (0, -1), 'BOTTOM'), ('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' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t = Table(data2) t.setStyle(style) I = Image(im_path) proportion = 0.9 I.drawWidth = doc.width * proportion ratio = (self.l_y[1] - self.l_y[0]) / (self.l_x[1] - self.l_x[0]) I.drawHeight = doc.width * ratio * proportion # Send the data and build the file elements.append(I) elements.append(t) doc.build(elements)
def create_report_pdf(self): PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() total_amount="0" #styles.add(ParagraphStyle(name="x", fontSize=12, leading = 7, alignment=TA_LEFT)) #styles.add(ParagraphStyle(name="x2", fontSize=10, leading = 7, alignment=TA_LEFT)) connection = sqlite3.connect("fci.db") results=connection.execute("SELECT PRINTER_HEATER_TITLE,PRINTER_HEADER,PRINTER_FOOTER FROM GLOBAL_VAR") for x in results: Title = Paragraph(str(x[0]), styles["Title"]) ptext = "<font name=Helvetica size=10>"+str(x[1])+" </font>" Title2 = Paragraph(str(ptext), styles["Title"]) connection.close() connection = sqlite3.connect("fci.db") results=connection.execute("SELECT count(*) FROM WEIGHT_MST_FCI_VW "+str(self.whr_sql2)) for x in results: total_amount=str(x[0]) connection.close() summary_data=[["From Date: "+str(self.from_dt),"To Date: "+str(self.to_dt) , "Total Trucks: "+str(total_amount), "Report Date: "+str(datetime.datetime.now().strftime("%d %b %Y %H:%M"))]] f3=Table(summary_data) #f3.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.20, colors.black),('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),('FONT', (0, 0), (-1, -1), "Helvetica", 10)])) Elements = [Title,Spacer(1,12),Title2,Spacer(1,12),f3,Spacer(1,12),Spacer(1,12)] childs_data=[] childs_data=[['Serial ID.','Order Id', ' Vehicle.No ','Material Name' ,' Net Wt.',' Tare Wt.',' Gross Wt.','Storage Name']] connection = sqlite3.connect("fci.db") results=connection.execute("SELECT SERIAL_ID_DISPLY,(SELECT A.ORDER_ID FROM ISSUE_MST A WHERE A.ISSUE_ID=ISSUE_ID) as ISSUE_ID,VEHICLE_NO,MATERIAL_NAME,printf(\"%6d\",IFNULL(NET_WEIGHT_VAL,0)),printf(\"%6d\", TARE_WT_VAL) as TARE_WT_VAL,printf(\"%6d\", GROSS_WT_VAL) as GROSS_WT_VAL,TARGET_STORAGE FROM WEIGHT_MST_FCI_VW "+str(self.whr_sql2)) for k in results: childs_data.append(k) connection.close() f=Table(childs_data) f.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.20, colors.black),('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),('FONT', (0, 0), (-1, -1), "Helvetica", 9)])) Elements.append(f) doc = SimpleDocTemplate('./reports/dr_other_report.pdf',pagesize=A4) doc.pagesize = landscape(A4) doc.build(Elements) print("Done") self.filter_col_name=""
def gen_pdf(questions, game_rounds): """generate speaker PDF""" styles = getSampleStyleSheet() doc = SimpleDocTemplate("pngs-speaker.pdf") doc.pagesize = landscape(A5) style = styles["Normal"] page_elements = [] for round in game_rounds: for num, question in enumerate( questions_per_round(questions, game_round=round)): q_data = question.as_pdf_dict page_elements.append( Paragraph("<em>Game Round</em>: {0}".format(round), style) ) page_elements.append(Spacer(0, 0.1*cm)) page_elements.append( Paragraph( "<font size=12><em>Question {0}:</em> <bold>{1}</bold>" "</font>".format(num + 1, q_data['text'].encode('utf-8')), style) ) page_elements.append(Spacer(0, 0.2*cm)) page_elements.append( Paragraph("<em>Comment</em>: {0}".format(q_data.get('comment').encode('utf-8')), style) ) page_elements.append(Spacer(0, 0.2*cm)) page_elements.append( Paragraph("<em>Answers</em>:", style) ) page_elements.append( Paragraph("* " + "<br />* ".join([unicode(t['text']) for t in q_data['answers']]), style) ) page_elements.append( Paragraph("<em>Points</em>: {0}".format(q_data.get('tier')), style) ) page_elements.append(PageBreak()) doc.build(page_elements) return Story = [Spacer(0, 1*cm)] p = Paragraph("Blubber1", styles["Normal"]) Story.append(p) p = Paragraph("Blubber2", styles["Normal"]) Story.append(p) Story.append(Spacer(10, 5*cm)) p = Paragraph("Blubber3", styles["Normal"]) Story.append(p) #doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc.build(Story)
def getDocument(filename): """Returns a ReportLab Document with the appropriate margins set.""" doc = SimpleDocTemplate(filename) doc.pagesize = (PAGE_WIDTH, PAGE_HEIGHT) doc.leftMargin = doc.rightMargin = \ doc.bottomMargin = inch * 0.5 doc.topMargin = inch return doc
def generateTableOfTestCases(self): print "report: " + self.reportName testSuite = TestSuites.objects.get(report=self.reportName) print str(testSuite) if testSuite is None: return testCases = TestCases.objects.filter(testSuite=testSuite) columns = ['TestCaseId', 'TestCase', 'Result', 'Attachment'] name = MEDIA_ROOT + '/' + self.reportName doc = SimpleDocTemplate(name, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [columns] #pie_data={'passed': 0,'retest': 0, 'blocked':0 , 'failed':0 , 'untested':0 , 'retest':0} pie_data = {} for testCase in testCases: row = [ str(testCase.id), str(testCase.testCase), testCase.result, str(testCase.output) ] data.append(row) pie_data[testCase.result] = pie_data.get(testCase.result, 0) + 1 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' 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 drw = self.Pie(pie_data) elements.append(drw) elements.append(Spacer(1, 48)) elements.append(t) doc.build(elements) return name
def generate_pdf(self): """ Generate a pdf version of the pools.""" doc = SimpleDocTemplate("files/"+self.name + ".pdf", rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18, showBoundary=1) doc.pagesize=landscape(A4) Story=[] file_path="file_path" date = time.ctime() header_title="CDL - tableaux de poules" number_pool="10" field="Jc et Nath \n3080 Tervuren" tournament="Double Mixte - Juniors - JUN" #frames frameTable = Frame(doc.leftMargin, doc.height*0.20, doc.height-doc.rightMargin , 400, leftPadding=0, rightPadding=0, id='normal') def footer_header(canvas,doc): """Footer and header description""" canvas.saveState() canvas.setFont('Times-Roman',12) #Header header_y=doc.height + 72 canvas.drawString(20, header_y, date) canvas.drawString(doc.width/2, header_y, header_title) canvas.drawString(doc.leftMargin, header_y-20, "Numéro:") canvas.drawString(doc.leftMargin+100, header_y-20, "Terrain:") canvas.drawString(doc.leftMargin+5, header_y-45, number_pool) canvas.drawString(doc.leftMargin+105, header_y-45, field) canvas.drawString(doc.leftMargin+5, header_y-70, tournament) #Footer footer_y=10 canvas.drawString(25, footer_y, file_path) canvas.drawString(doc.width , footer_y, "page %d" % doc.page) canvas.restoreState() #Table score pools = Pool.objects.filter(tournament=self); templates=[] for pool in pools: Story.append(Spacer(1, 48)) Story.append(self.pdf_pool(pool)) Story.append(NextPageTemplate(str(pool))) Story.append(PageBreak()) templates.append(PageTemplate(id=str(pool),frames=frameTable,onPage=footer_header)) doc.addPageTemplates(templates) doc.build(Story)
def printdashboard(request): user_timezone = request.session['visitor_timezone'] selecteddate = request.GET['selecteddate'] boookingdetails = getbookingdetails(user_timezone, selecteddate) file = "dashboard.pdf" response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="{}"'.format(file) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) Catalog = [] styles = getSampleStyleSheet() styles.wordWrap = 'CJK' header = Paragraph("Product Inventory", styles['Normal']) Catalog.append(header) style = styles['Normal'] pdfdetails = [] for bkditem in boookingdetails: head = [] pdfrow = [] pdfrow.append(bkditem['hhmm']) for bkd in bkditem['bookingdetail']: header1 = Paragraph(bkd["employee"], styles['Normal']) header2 = Paragraph(bkd["servicename"], styles['Normal']) header3 = Paragraph(bkd["customername"], styles['Normal']) head.extend([header1, header2, header3, Spacer(1, 0.2 * inch)]) pdfrow.append(head) pdfdetails.append(pdfrow) headings = ('Working Time', 'Booking Details') t = Table([headings] + pdfdetails) t.setStyle( TableStyle([('GRID', (0, 0), (1, -1), 2, colors.black), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.red), ('BACKGROUND', (0, 0), (-1, 0), colors.pink)])) Catalog.append(t) doc.build(Catalog) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def mainMakePdf(list_mahasiswa, kode_dosen, tipe_bimbingan): doc = SimpleDocTemplate( f'./beritaacarapitak/BERITA ACARA PITAK-{tipe_bimbingan.upper()}-{kelas.getTahunID()}-{kode_dosen}-{kelas.getEmailDosen(kode_dosen)}.pdf', pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = portrait(A4) elements = [] logo = Image("logoKAMBING.PNG", 3.5 * inch, 1 * inch) logo.hAlign = "LEFT" styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) for npm in list_mahasiswa: studentid, studentname = getDataMahasiswa(npm) status_nilai, nilai_total = totalNilai( studentid, config.MINIMUM_PERTEMUAN_BIMBINGAN, kode_dosen, tipe_bimbingan) status_nilai = True if status_nilai: JUDUL_BIMBINGAN = f"{getJudulFromNpm(npm)}" KODE_DOSEN = kode_dosen NAMA_DOSEN = kelas.getNamaDosen(KODE_DOSEN) NIDN_DOSEN = getNIDNDosen(KODE_DOSEN) TAHUN_AJARAN = kelas.getTahunAjaran( kelas.getProdiIDwithStudentID(studentid)).split(' ')[-1] makePdf(npm_mahasiswa=studentid, nama_mahasiswa=studentname, tipe_bimbingan=getTipeBimbingan(studentid), nama_pembimbing=NAMA_DOSEN, kode_dosen_pembimbing=KODE_DOSEN, nidn_pembimbing=NIDN_DOSEN, tahun_ajaran=TAHUN_AJARAN, photo=cekPhotoRoute(studentid), judul=JUDUL_BIMBINGAN, total_nilai=str(nilai_total), elements=elements, logo=logo, styles=styles, kode_dosen_koordinator='NN056L') elements.append(PageBreak()) else: pass doc.build(elements)
def handle_pdf(self, request, queryset): if "pdf" not in formats: raise ImportError, "The site is not configured to handle pdf." # this is again some quick and dirty sample code elements = [] styles = getSampleStyleSheet() styles["Title"].alignment = TA_LEFT styles["Title"].fontName = styles["Heading2"].fontName = "Helvetica" styles["Normal"].fontName = "Helvetica" filename = mkstemp(".pdf")[-1] doc = SimpleDocTemplate(filename) doc.pagesize = pagesizes.landscape(pagesizes.LETTER) request = WSGIRequest({"REQUEST_METHOD": "GET"}) site = RequestContext(request).get("site") if site and site.get("title"): elements.append(Paragraph(site.get("title"), styles["Title"])) elements.append(Paragraph("%s List" % self.model.__name__, styles["Heading2"])) data = [] header = False for row in queryset: if not header: data.append([f["name"] for f in self.fields]) header = True ctx = Context({"object": row}) values = [Template(h["bit"]).render(ctx) for h in self.fields] data.append(values) table = PDFTable(data) table.setStyle( TableStyle( [ ("ALIGNMENT", (0, 0), (-1, -1), "LEFT"), ("LINEBELOW", (0, 0), (-1, -0), 2, colors.black), ("LINEBELOW", (0, 1), (-1, -1), 0.8, colors.lightgrey), ("FONT", (0, 0), (-1, -1), "Helvetica"), ("ROWBACKGROUNDS", (0, 0), (-1, -1), [colors.whitesmoke, colors.white]), ] ) ) elements.append(table) elements.append(Paragraph("Created: %s" % datetime.now().strftime("%d/%m/%Y"), styles["Normal"])) doc.build(elements) response = HttpResponse(mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=report.pdf" response.write(open(filename).read()) os.remove(filename) return response
def write(self): """Assembles the final PDF and writes to disk.""" pdf_writer = pyPdf.PdfFileWriter() if self.front_matter is not None: front_matter = pyPdf.PdfFileReader(file(self.front_matter, "rb")) for page in range(front_matter.getNumPages()): pdf_writer.addPage(front_matter.getPage(page)) working_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) doc = SimpleDocTemplate(working_file) doc.pagesize = portrait(letter) story = [] styles = getSampleStyleSheet() for section in self.sections: heading_text = section.heading story.append(Paragraph(heading_text, styles["Heading1"])) for content in section.contents: if "figure" in content: figure = content["figure"] if os.path.exists(figure): im = utils.ImageReader(figure) img_width, img_height = im.getSize() aspect = img_height / float(img_width) story.append(Image(figure, width=img_width, height=(img_width * aspect))) if content.get("caption", None) is not None: caption_text = "<font size=10>{0}</font>".format(content["caption"].strip()) story.append(Paragraph(caption_text, styles["Italic"])) story.append(Spacer(1, 10)) if "table" in content: _t = self.build_table(content["table"]) story.append(_t) if content.get("caption", None) is not None: caption_text = "<font size=10>{0}</font>".format(content["caption"].strip()) story.append(Paragraph(caption_text, styles["Italic"])) story.append(Spacer(1, 10)) if "text" in content: for para in content["text"]: story.append(Paragraph(para, styles["Normal"])) story.append(Spacer(1, 12)) doc.build(story) body_matter = pyPdf.PdfFileReader(working_file) for page in range(body_matter.getNumPages()): pdf_writer.addPage(body_matter.getPage(page)) try: os.remove(working_file.name) except OSError: # Windows reports file in use, other OS errors, etc. pass if self.end_matter is not None: end_matter = pyPdf.PdfFileReader(file(self.end_matter, "rb")) for page in range(end_matter.getNumPages()): pdf_writer.addPage(end_matter.getPage(page)) output_stream = file(self.output_filename, "wb") pdf_writer.write(output_stream)
def results_as_pdf(scrape_results): buff = io.BytesIO() doc = SimpleDocTemplate(buff, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [ ['Posted At', 'Symbol', 'Headline', 'Article'], ] for result in scrape_results: data.append([ str(result.posted_at), result.symbol.name, result.headline, result.article ]) style = TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ('TEXTCOLOR', (1, 1), (-2, -2), colors.red), ('VALIGN', (0, 0), (0, -1), 'CENTER'), ('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.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) s = s["BodyText"] s.wordWrap = 'CJK' 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) response = HttpResponse(content_type='application/pdf') pdf_name = "results.pdf" response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name response.write(buff.getvalue()) buff.close() return response
def generate_report_pdfs(reports, path): for report in reports: if (not (report.recipent.email)): print(report.recipent.name) doc = SimpleDocTemplate( os.path.join(path, report.recipent.email + ".pdf")) doc.pagesize = landscape(A4) flowables = [] title = Paragraph(report.college_name, styles.get_title_style()) flowables.append(title) office_name = Paragraph(report.office_name, styles.get_title_style()) flowables.append(office_name) semester = Paragraph(report.semester, styles.get_semester_style()) flowables.append(semester) date = Paragraph(report.date, styles.get_date_style()) flowables.append(date) greeting = Paragraph(report.greeting, styles.get_greeting_style()) flowables.append(greeting) intro = Paragraph(report.intro, styles.get_intro_style()) flowables.append(intro) flowables.append(Spacer(1, 15)) table = Table(report.table.rows, style=styles.get_table_style()) flowables.append(table) flowables.append(Spacer(1, 20)) signature_1 = Paragraph(report.signature, styles.get_signature_style()) flowables.append(signature_1) signature_2 = Paragraph(report.office_name, styles.get_signature_style()) flowables.append(signature_2) flowables.append(Spacer(1, 20)) for index, note in enumerate(report.notes): item = Paragraph(f"{index + 1}. {note}", styles.get_intro_style()) flowables.append(item) doc.build(flowables)
def build_slide_pdf(imageList, base_folder, filename): doc = SimpleDocTemplate(base_folder + '/' + filename) doc.pagesize = landscape(A4) story = [] width = 10 * inch height = width * 1080 / 1920 for i in imageList: im = Image(f"{base_folder}/{i}.png", width, height) story.append(im) story.append(PageBreak()) doc.build(story)
def printPdf(self): filename = self.name + '_timetable.pdf' doc = SimpleDocTemplate(filename, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = portrait(A4) story = [] for i, day in enumerate(self.slots): data = [[''] * 5 for i in range(3)] data[0][0] = self.name data[1] = [ 'Date', 'Time', 'Course Code', 'Course Name', 'No. of\nStudents' ] data[2][0] = 'Day ' + str(i + 1) style = [('SPAN', (0, 0), (-1, 0)), ('SPAN', (0, 2), (-1, 2)), ('ALIGN', (0, 0), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, 1), 'MIDDLE'), ('ALIGN', (0, 3), (-1, -1), 'CENTER'), ('VALIGN', (0, 3), (-1, -1), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)] for i, slot in enumerate(day): for sub in slot.subjects: d = slot.time_slot[0] time = '12:' if not slot.time_slot[1] // 100 in [0, 12]: time = str((slot.time_slot[1] // 100) % 12) + ':' time += str(slot.time_slot[1] % 100) time += 'PM' if (slot.time_slot[1] // 100) > 11 else 'AM' data.append([ d, time, sub.code, sub.name, sub.nbStudent(self.students) ]) start, end = len(data) - len(slot.subjects), len(data) - 1 style.append(('SPAN', (0, start), (0, end))) style.append(('SPAN', (1, start), (1, end))) if i + 1 != len(day): style.append(('SPAN', (0, end + 1), (-1, end + 1))) data.append([''] * 5) table = Table(data) table.setStyle(TableStyle(style)) story.append(table) story.append(PageBreak()) doc.multiBuild(story)
def gen_pdf_table(file_name , data , year , week): buf = io.BytesIO() doc = SimpleDocTemplate(buf , pagesize=A4 , rightMargin=30 , leftMargin=30 , topMargin=30 , bottomMargin=18) doc.pagesize = landscape(A4) elements = [] # TODO: Get this line right instead of just copying it from the docs 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() p = s s = s["BodyText"] s.wordWrap = 'CJK' elements.append(Paragraph(' Generated schedule for year{0} , week {1}'.format(year,week) , p['title'])) elements.append(Paragraph(' Effective date range for this period is {0}'.format(get_date_range(year , week)) , p['title'])) elements.append(Paragraph(' ' , p['Normal'])) # 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) style = getSampleStyleSheet() normal = style["Normal"] normal.alignment = TA_CENTER for line in data: elements.append(Paragraph(line,normal)) doc.build(elements) save_file(file_name=file_name , buffer=buf)
def export(self, filename, data_align='LEFT', table_halign='LEFT'): """ Export the data to a PDF file. Arguments: filename - The filename for the generated PDF file. data_align - The alignment of the data inside the table (eg. 'LEFT', 'CENTER', 'RIGHT') table_halign - Horizontal alignment of the table on the page (eg. 'LEFT', 'CENTER', 'RIGHT') """ doc = SimpleDocTemplate(filename, pagesize=letter) doc.pagesize = landscape(A4) styles = getSampleStyleSheet() styleH = styles['Heading1'] story = [] if self.title: story.append(Paragraph(self.title, styleH)) story.append(Spacer(1, 0.25 * inch)) if self.subtitle: story.append(Paragraph(self.subtitle, styles['Heading3'])) story.append(Spacer(1, 0.25 * inch)) if self.sort_by: reverse_order = False if (str(self.sort_by[1]).upper() == 'DESC'): reverse_order = True self.data = sorted(self.data, key=itemgetter(self.sort_by[0]), reverse=reverse_order) converted_data = self.__convert_data() table = Table(converted_data, hAlign=table_halign) table.setStyle( TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN', (0, 0), (0, -1), data_align), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) story.append(table) doc.build(story)
def gen_pdf(questions, game_rounds): """generate speaker PDF""" styles = getSampleStyleSheet() doc = SimpleDocTemplate("pngs-speaker.pdf") doc.pagesize = landscape(A5) style = styles["Normal"] page_elements = [] for round in game_rounds: for num, question in enumerate( questions_per_round(questions, game_round=round)): q_data = question.as_pdf_dict page_elements.append( Paragraph("<em>Game Round</em>: {0}".format(round), style)) page_elements.append(Spacer(0, 0.1 * cm)) page_elements.append( Paragraph( "<font size=12><em>Question {0}:</em> <bold>{1}</bold>" "</font>".format(num + 1, q_data['text'].encode('utf-8')), style)) page_elements.append(Spacer(0, 0.2 * cm)) page_elements.append( Paragraph( "<em>Comment</em>: {0}".format( q_data.get('comment').encode('utf-8')), style)) page_elements.append(Spacer(0, 0.2 * cm)) page_elements.append(Paragraph("<em>Answers</em>:", style)) page_elements.append( Paragraph( "* " + "<br />* ".join( [unicode(t['text']) for t in q_data['answers']]), style)) page_elements.append( Paragraph("<em>Points</em>: {0}".format(q_data.get('tier')), style)) page_elements.append(PageBreak()) doc.build(page_elements) return Story = [Spacer(0, 1 * cm)] p = Paragraph("Blubber1", styles["Normal"]) Story.append(p) p = Paragraph("Blubber2", styles["Normal"]) Story.append(p) Story.append(Spacer(10, 5 * cm)) p = Paragraph("Blubber3", styles["Normal"]) Story.append(p) #doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc.build(Story)
def go_pdf(result, tmp_name): doc = SimpleDocTemplate(f'{tmp_name}', pagesize=A4, rightMargin=15, leftMargin=20, topMargin=15, bottomMargin=18) # doc.pagesize = landscape(A4) doc.pagesize = portrait(A4) elements = [] data = _go_data(result) t = Table(data) t.setStyle(style) elements.append(t) doc.build(elements)
def export(self, filename, data_align='LEFT', table_halign='LEFT'): """ Export the data to a PDF file. Arguments: filename - The filename for the generated PDF file. data_align - The alignment of the data inside the table (eg. 'LEFT', 'CENTER', 'RIGHT') table_halign - Horizontal alignment of the table on the page (eg. 'LEFT', 'CENTER', 'RIGHT') """ doc = SimpleDocTemplate(filename, pagesize=letter) doc.pagesize = landscape(A4) styles = getSampleStyleSheet() styleH = styles['Heading1'] story = [] if self.title: story.append(Paragraph(self.title, styleH)) story.append(Spacer(1, 0.25 * inch)) if self.subtitle: story.append(Paragraph(self.subtitle, styles['Heading3'])) story.append(Spacer(1, 0.25 * inch)) if self.sort_by: reverse_order = False if (str(self.sort_by[1]).upper() == 'DESC'): reverse_order = True self.data = sorted(self.data, key=itemgetter(self.sort_by[0]), reverse=reverse_order) converted_data = self.__convert_data() table = Table(converted_data, hAlign=table_halign) table.setStyle(TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN',(0, 0),(0,-1), data_align), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) story.append(table) doc.build(story)
def pdf_a_apporter(request): """ display the games to bring for one user """ response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="a_apporter.pdf"' doc = SimpleDocTemplate(response, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=20) doc.pagesize = A4 elements = [] games = request.user.owned_games.filter(owner__is_bringing=True) data = [ ["Nombre de jeux à apporter : {}".format(len(games)), "", "", "", "", ""], ["", "", "", "", "", ""] ] styles = getSampleStyleSheet() # We build the data l = len(games) if l % 2 == 0: sc = l/2 else: sc = l/2+1 for i in range(sc): # in case we have an odd number of elements, we display the last line if l % 2 != 0 and i == l/2: data.append([Paragraph(games[i].name, styles['BodyText']), "", "", "", "", ""]) elif i < l: data.append([Paragraph(games[i].name, styles['BodyText']), "", "", Paragraph(games[i + sc].name, styles['BodyText']), "", ""]) t = Table(data, colWidths=(None, 40, 40, None, 40, 40)) # Styling the titles and the grid style = TableStyle([('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 2), (-1, -1), 0.25, colors.grey), ('BOX', (0, 2), (-1, -1), 0.25, colors.grey) ]) t.setStyle(style) # Send the data and build the file elements.append(t) doc.build(elements) return response
def generateTableOfTestCases(self): print "report: "+self.reportName testSuite = TestSuites.objects.get(report=self.reportName) print str(testSuite) if testSuite is None: return testCases = TestCases.objects.filter(testSuite=testSuite) columns = ['TestCaseId', 'TestCase', 'Result', 'Attachment'] name = MEDIA_ROOT+'/'+self.reportName doc = SimpleDocTemplate(name, pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [columns] #pie_data={'passed': 0,'retest': 0, 'blocked':0 , 'failed':0 , 'untested':0 , 'retest':0} pie_data={} for testCase in testCases: row =[str(testCase.id), str(testCase.testCase), testCase.result,str(testCase.output)] data.append(row) pie_data[testCase.result]= pie_data.get(testCase.result, 0)+1 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' 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 drw= self.Pie(pie_data) elements.append(drw) elements.append(Spacer(1, 48)) elements.append(t) doc.build(elements) return name
def handle_pdf(request, queryset, fields, file_name): # this is again some quick and dirty sample code elements = [] styles = getSampleStyleSheet() styles['Title'].alignment = TA_LEFT styles['Title'].fontName = styles['Heading2'].fontName = "Helvetica" styles["Normal"].fontName = "Helvetica" filename = mkstemp(".pdf")[-1] doc = SimpleDocTemplate(filename) elements.append(Paragraph("MCTC", styles['Title'])) elements.append(Paragraph("%s List" % file_name, styles['Heading2'])) # data = [] header = False for row in queryset: if not header: data.append([f["name"] for f in fields]) header = True ctx = Context({"object": row }) values = [ Template(h["bit"]).render(ctx) for h in fields ] data.append(values) table = PDFTable(data,None,None,None,1) table.setStyle(TableStyle([ ('ALIGNMENT', (0,0), (-1,-1), 'LEFT'), ('LINEBELOW', (0,0), (-1,-0), 2, colors.black), ('LINEBELOW', (0,1), (-1,-1), 0.8, colors.lightgrey), ('FONT', (0,0), (-1, -1), "Helvetica"), ('ROWBACKGROUNDS', (0,0), (-1, -1), [colors.whitesmoke, colors.white]), ])) elements.append(table) elements.append(Paragraph("-", styles["Normal"])) elements.append(Paragraph("Created: %s" % datetime.now().strftime("%d/%m/%Y"), styles["Normal"])) doc.pagesize = landscape(A4) doc.build(elements) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % file_name response.write(open(filename).read()) os.remove(filename) return response
def generar_pdf(request, cliente_id=None): im = Image('media/ifes/logo_opt.jpg', width=2*inch, height=2*inch) im.hAlign = 'CENTER' cliente = get_object_or_404(Order, id=cliente_id) response = HttpResponse(content_type='application/pdf') pdf_name = "Orden_de_compra.pdf" buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=30, leftMargin=60, topMargin=30, bottonMargin=10, ) doc.pagesize = landscape(A4) order = [] styles = getSampleStyleSheet() header = Paragraph("Orden de compra", styles['Heading1']) fetch = [(f.order_date) for f in Order.objects.all() ] fecha = Paragraph("Fecha:", styles['Heading2']) order.append(im) order.append(header) order.append(fecha) headings = ('Orden de compra', 'Fecha', 'Monto total', 'Usuario', 'Operador','Producto','precio unitario','cantidad','total') allorder = [(p.orden_de_compra, p.order_date, p.total_amount, p.user, p.operador, a.product, a.product.price, a.quantity, (a.product.price*a.quantity)) for p in Order.objects.filter(user = cliente_id) for a in ProductOrder.objects.filter(order__user= cliente_id)] t = Table([headings] + allorder + fetch) t.setStyle(TableStyle( [ ('GRID', (0,0), (10, -1), 1, colors.green), ('LINEBELOW', (0,0), (-1,0), 2, colors.greenyellow), ('BACKGROUND', (0,0), (-1,0), colors.green) ] )) order.append(t) doc.build(order) response.write(buff.getvalue()) buff.close() return response
def go(): doc = SimpleDocTemplate("phello.pdf") doc.pagesize=(6*inch,4*inch) doc.leftMargin=0.25*inch doc.bottommargin=0.25*inch #doc.height=3.75*inch #doc.width=5.75*inch doc.height=4*inch doc.width=6*inch Story = [] style = styles["Normal"] for i in range(3): bogustext = ("This is Paragraph number %s. " % i) *2 p = Paragraph(bogustext, style) Story.append(p) #Story.append(Spacer(1,0.2*inch)) l=[] for x in range(3): l.append(["row%i col1" % x, "row%i col2" % i]) Story.append(Table(l)) Story.append(Paragraph("Hello", styles["Title"])) #doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc.build(Story)
def ImprimirVentasCreditos(request, fechaI, fechaF): response = HttpResponse(content_type='application/pdf') finicio = datetime.fromtimestamp(int(fechaI) / 1e3) ffin = datetime.fromtimestamp(int(fechaF) / 1e3) pdf_name = "ventasacredito.pdf" buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=50, leftMargin=50, topMargin=20, bottomMargin=18, ) doc.pagesize = landscape(A4) ventas = [] totales = Venta.objects.filter(fecha__gte = finicio, fecha__lte = ffin, credito = True , estado = 'ACTIVO').aggregate(precio_total=Sum(F('total'))) ventas.append(Spacer(1, 0.05 * inch)) header = Paragraph("GRUPOEJ - SRL." , getStyleSheet()['Title']) subtitel = Paragraph("Ventas al credito." , getStyleSheet()['Subtitle']) ventas.append(header) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(subtitel) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(Paragraph("<para>Fecha Inicio: "+finicio.strftime('%d/%m/%Y')+" "+" Fecha Fin:"+ffin.strftime('%d/%m/%Y')+"</para>", getStyleSheet()['TopicTitle8'])) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(Paragraph("DETALLE", getStyleSheet()['TopicTitle10'])) ventas.append(Spacer(1, 0.1 * inch)) styles = getSampleStyleSheet() headings = ('DNI/RUC', 'CLIENTE', "RESPONSABLE", 'NRO_VENTA','FECHA' ,'TOTAL') venta = [(str(v.pedido.cliente.nro_documento), str(v.pedido.cliente.nombres)+"/"+str(v.pedido.cliente.apellidos), str(v.pedido.cliente.responsable), str(v.numero_correlativo)+"-"+str(v.numero_documento), str(v.fecha), str(v.total)) for v in Venta.objects.filter(fecha__gte = finicio, fecha__lte = ffin, credito = True , estado = 'ACTIVO')] data = ([headings] + venta) data2 = [[Paragraph(cell, getStyleSheet()['TopicItemq0']) for cell in row] for row in data] t=Table(data2) style = TableStyle( [ ('BACKGROUND', (0, 0), (-1, 0), colors.gray), ('LINEABOVE', (0,0), (-1,0), 2, colors.green), ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green), ('ALIGN', (1,1), (-1,-1), 'CENTER'), ] ) t.setStyle(style) t._argW[0]=0.8*inch t._argW[1]=2.8*inch t._argW[2]=2.8*inch t._argW[3]=0.9*inch t._argW[4]=0.9*inch t._argW[5]=0.9*inch ventas.append(t) ventas.append(Paragraph("Total: S/ "+str(totales['precio_total']), getStyleSheet()['TopicTitle8Right'])) # ventas.append(Paragraph("IGV:___"+str(venta.igv)+" S/", getStyleSheet()['TopicTitle8Right'])) # ventas.append(Paragraph("Total:__ "+str(venta.total)+" S/", getStyleSheet()['TopicTitle8Right'])) doc.build(ventas) response.write(buff.getvalue()) buff.close() return response
def all_providers_list_pdf(request, file_name, chw=False): zones = Case.objects.values('zone').distinct() # this is again some quick and dirty sample code elements = [] styles = getSampleStyleSheet() styles['Title'].alignment = TA_LEFT styles['Title'].fontName = styles['Heading2'].fontName = "Helvetica" styles["Normal"].fontName = "Helvetica" styles["Normal"].fontSize = 10 styles["Normal"].fontWeight = "BOLD" filename = mkstemp(".pdf")[-1] doc = SimpleDocTemplate(filename) elements.append(Paragraph("RapidResponse MVP Kenya: %s" % datetime.today().strftime("%Y-%m-%d"), styles['Title'])) #elements.append(Paragraph(, styles['Heading2'])) # for z in zones: zone = Zone.objects.filter(id=z['zone'])[0] #elements.append(Paragraph("%s" % zone.name, styles['Heading3'])) providers = Case.objects.filter(zone=z['zone']).values('provider').distinct() for p in providers: provider = Provider.objects.filter(id=p['provider'])[0] queryset, fields = build_report("provider", p['provider']) data = [] header = False for row in queryset: if not header: data.append([f["name"] for f in fields]) header = True ctx = Context({"object": row }) values = [ Template(h["bit"]).render(ctx) for h in fields ] data.append(values) table = PDFTable(data,None,None,None,1) table.setStyle(TableStyle([ ('ALIGNMENT', (0,0), (-1,-1), 'LEFT'), ('LINEBELOW', (0,0), (-1,-0), 2, colors.black), ('LINEBELOW', (0,1), (-1,-1), 0.8, colors.lightgrey), ('FONT', (0,0), (-1, -1), "Helvetica", 8), ('ROWBACKGROUNDS', (0,0), (-1, -1), [colors.whitesmoke, colors.white]), ])) table.hAlign = "LEFT" elements.append(Paragraph("%s" % zone.name, styles['Heading3'])) sms_sent = MessageLog.objects.filter(sent_by=provider.user_id).count() sms_processed = MessageLog.objects.filter(sent_by=provider.user_id, was_handled=True).count() sms_refused = MessageLog.objects.filter(sent_by=provider.user_id,was_handled=False).count() if sms_sent != 0: sms_rate = round(float(sms_processed)/float(sms_sent)*100) else: sms_rate = 0 elements.append(Paragraph("%s : %s SMS Accuracy Rate %s%% (%s/%s)" % (provider.get_name_display(), provider.mobile, sms_rate, sms_processed,sms_sent), styles['Normal'])) elements.append(table) if chw is True: elements.append(PageBreak()) #elements.append(Paragraph("-", styles["Normal"])) elements.append(PageBreak()) elements.append(Paragraph("Created: %s" % datetime.now().strftime("%d/%m/%Y"), styles["Normal"])) doc.pagesize = landscape(A4) doc.build(elements, onFirstPage=myFirstPage, onLaterPages=myLaterPages) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % file_name response.write(open(filename).read()) os.remove(filename) return response
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY from reportlab.lib.styles import ParagraphStyle from reportlab.lib import colors elements =[] styleS = getSampleStyleSheet() styleS.add(ParagraphStyle(name='Left', alignment=TA_LEFT,fontName='Times-Bold',fontSize=14,spaceAfter=10)) elements.append(Paragraph(title, styleS["Left"])) MakeTable() if Layout == "Landscape8x11": PDF = scratch + r"\LandscapeMap.pdf" doc = SimpleDocTemplate(PDF, rightMargin = 72,bottomMargin=10, topMargin=10) doc.pagesize = landscape(A4) elif Layout == "Portrait8x11": PDF = scratch + r"\PortraitMap.pdf" doc = SimpleDocTemplate(PDF, rightMargin = 72,bottomMargin=10, topMargin=10) doc.pagesize = portrait(A4) doc.build(elements) if WebMap == '#' or not WebMap: finalPdf = PDF # Set output file arcpy.SetParameterAsText(1, PDF) arcpy.AddMessage(" Finished") else:
def BillPrint(request): text_footer_stzef = "AppEm - Aplicacion para administracion de Empresas [email protected]" # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; attachment; filename="somefilename.pdf"' manageParameters = ManageParameters(request.db) data = request.GET cfac = data.get('cfac') factura = Fac.objects.using(request.db).get(cfac=cfac) factura_deta = Facdeta.objects.using(request.db).filter(cfac=factura) sucursal = factura.ccaja.csucur slug_company = manageParameters.get("slug_company") doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=10,leftMargin=10, topMargin=0,bottomMargin=40) doc.pagesize = portrait((190, 1900)) hr_linea = "___________________________________" elements = [] MEDIA_ROOT = os.path.join('infa_web/static') url = MEDIA_ROOT + manageParameters.get("company_logo") image = Image(url, width=128, height=82) if slug_company == "fitness_juice": data_header = [ [manageParameters.get("company_name")], [manageParameters.get("text_header_pos_bill")], [manageParameters.get("company_id_name") + " : " + manageParameters.get("company_id")], ["I.V.I Serie 5205964"], [sucursal.nsucur], ["Dir:" + sucursal.dirsucur], ["Tel:" + sucursal.telsucur], ["Cel:" + sucursal.celsucur], ] elif slug_company == "roma_pizza": data_header = [ [manageParameters.get("company_name")], [manageParameters.get("text_header_pos_bill")], [manageParameters.get("company_id_name") + " : " + manageParameters.get("company_id")], [sucursal.nsucur], [manageParameters.get("company_adress")], [manageParameters.get("company_telephone")+" - "+manageParameters.get("company_celphone")], ] else: data_header = [ [manageParameters.get("company_name")], [manageParameters.get("text_header_pos_bill")], [manageParameters.get("company_id_name") + " : " + manageParameters.get("company_id")], [sucursal.nsucur], ["Dir:" + sucursal.dirsucur], ["Tel:" + sucursal.telsucur], ["Cel:" + sucursal.celsucur], ] data = [ ["_______________ ", "________", "_____________"], ["<br/><strong>Descripcion</strong>", " <strong>Cant</strong>", " <strong>Vr. Total</strong>"], ["_______________ ", "________", "_____________"] ] if slug_company == "fitness_juice": for facdeta in factura_deta: data.append([facdeta.carlos.ncorto[:10],str(int(facdeta.canti)),""]) data.append(["IVI","",intcomma( int(facdeta.vtotal))]) elif slug_company == "roma_pizza": for facdeta in factura_deta: data.append(["<br/>"+facdeta.carlos.ncorto," "+str(int(facdeta.canti))," "+intcomma( int(facdeta.vtotal))]) else: for facdeta in factura_deta: data.append([facdeta.carlos.ncorto[:10],str(int(facdeta.canti)),intcomma( int(facdeta.vtotal))]) data.append(["_______________ ", "________", "_____________"]) data.append(["<br/><strong>TOTAL</strong>","-------->"," <strong>"+intcomma(int(factura.vttotal))+"</strong>"]) data.append(["_______________ ", "________", "_____________"]) style_table_header = 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),'LEFT'), ('VALIGN',(0,-1),(-1,-1),'MIDDLE'), ('TEXTCOLOR',(0,-1),(-1,-1),colors.green), ('LEFTPADDING',(0,0),(-1,-1), 0), ('RIGHTPADDING',(0,0),(-1,-1), 0), ('TOPPADDING',(0,0),(-1,-1), 0), ('BOTTOMPADDING',(0,0),(-1,-1), 0), #('LINEABOVE', (0,0), (-1,0), 1, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 1, colors.black), #('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) style_table_facdeta = 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),'LEFT'), ('VALIGN',(0,-1),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1), 0), ('RIGHTPADDING',(0,0),(-1,-1), 0), ('TOPPADDING',(0,0),(-1,-1), 0), ('BOTTOMPADDING',(0,0),(-1,-1), 0), ('TEXTCOLOR',(0,-1),(-1,-1),colors.green), ]) #Configure style and word wrap s = getSampleStyleSheet() s.add(ParagraphStyle(name='tirilla',fontSize=8,leading=12,rightMargin=0,leftMargin=0, topMargin=0,bottomMargin=0,alignment=TA_CENTER)) s.add(ParagraphStyle(name='header',fontSize=8.5,leading=12,alignment=TA_CENTER)) s.add(ParagraphStyle(name='body',fontSize=8,leading=12,alignment=TA_CENTER)) bodytext = s["tirilla"] headertext = s["header"] #s.wordWrap = 'CJK' bodytext.wordWrap = 'LTR' data2 = [[Paragraph(cell, bodytext) for cell in row] for row in data] t=Table(data2) t.setStyle(style_table_facdeta) elements.append(image) data2_header = [[Paragraph(cell, headertext) for cell in row] for row in data_header] t_header=Table(data2_header) t_header.setStyle(style_table_header) elements.append(t_header) elements.append(Paragraph("<br/>Factura No. %s" % factura.cfac,s['tirilla'])) elements.append(Paragraph("Fecha : %s " % timezone.localtime(factura.femi).strftime("%Y-%m-%d %H:%M:%S"),s['tirilla'])) elements.append(Paragraph("Atendido por : %s <br/>" % factura.cvende.nvende,s['tirilla'])) elements.append(t) elements.append(Paragraph(manageParameters.get("text_footer_pos_bill") ,s['body'])) elements.append(Paragraph(hr_linea ,s['body'])) elements.append(Paragraph(text_footer_stzef ,s['body'])) elements.append(Paragraph(hr_linea ,s['body'])) elements.append(Paragraph("." ,s['body'])) doc.build(elements) return response
reload(sys) sys.setdefaultencoding('utf8') from reportlab.lib import colors from reportlab.lib.pagesizes import A4, landscape from reportlab.platypus import Table, TableStyle from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus import Paragraph, SimpleDocTemplate from reportlab.lib.styles import getSampleStyleSheet pdfmetrics.registerFont(TTFont('hei', 'simhei.ttf')) doc = SimpleDocTemplate("test_report_lab.pdf", pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [["Title:","","","",""], ["Letter", "Number", "Stuff", "Long stuff that should be wrapped", u"备注"], ["A", "01", "ABCD", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", ""], ["B", "02", "CDEF", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", ""], ["C", "03", "SDFSDF", "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC", ""], ["D", "04", "SDFSDF", "DDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", ""], ["E", "05", "GHJGHJGHJ", "EEEEEEEEEEEEEE EEEEEEEEEEEEEEEEE EEEEEEEEEEEEEEEEEEEE", ""], ] # SPAN, (sc,sr), (ec,er) # style : style name, start column,start row,end column,end row,(style value) style = TableStyle([('SPAN',(0,0),(-1,0)), # 合并第一行 ('ALIGN', (0,0), (-1, 0), 'CENTER'), # 第一行左右居中,
def Popis(request): # TODO:Implement this view # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = 'attachment; filename="somefilename.pdf"' doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] header = ["Name", "Code", "Price", "Amount"] allitems = [[p.nazivArtikal, p.sifraArtikal, p.pojedinacnaCena, p.kolicina] for p in Item.objects.all()] data = [] data.append(header) for p in allitems: data.append(p) # TODO: Get this line right instead of just copying it from the docs 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), ("BACKGROUND", (0, 0), (-1, 0), colors.grey), ] ) # Configure style and word wrap s = getSampleStyleSheet() styleH = s["Bullet"] stitle = s["Title"] sdefinition = s["Definition"] elements.append(Paragraph("Inventory document", stitle)) elements.append(Spacer(1, 0.25 * inch)) elements.append(Paragraph("Date: {}".format(strftime("%m/%d/%Y %H:%M")), styleH)) elements.append(Spacer(1, 0.10 * inch)) elements.append(Paragraph("Author: {}".format(request.user), styleH)) elements.append(Spacer(1, 0.10 * inch)) elements.append(Paragraph("Store: {}".format("Test storage & co."), styleH)) elements.append(Spacer(1, 0.15 * inch)) s = s["BodyText"] s.wordWrap = "CJK" data2 = [[Paragraph(str(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) totalprice = 0 for p in Item.objects.all(): totalprice += p.pojedinacnaCena * p.kolicina elements.append(Spacer(1, 0.25 * inch)) elements.append(Paragraph("Total items: {}".format(Item.objects.all().count()), sdefinition)) elements.append(Spacer(1, 0.10 * inch)) elements.append(Paragraph("Total value: {}".format(totalprice), sdefinition)) doc.build(elements) return response
def ImprimirVenta(request, idventa): response = HttpResponse(content_type='application/pdf') pdf_name = "ventas.pdf" buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=50, leftMargin=50, topMargin=20, bottomMargin=18, ) doc.pagesize = landscape(A5) ventas = [] venta = Venta.objects.get(id = idventa) styles = getSampleStyleSheet() header = Paragraph("GRUPOEJ - SRL." , getStyleSheet()['Title']) documento = Paragraph("DOCUMENTO: "+(str(venta.tipo_documento))+" "+(str(venta.numero_correlativo))+"-"+(str(venta.numero_documento)) , getStyleSheet()['TopicItem1']) cliente = Paragraph("CLIENTE / RAZON SOCIAL: "+(str(venta.pedido.cliente.nombres))+" "+(str(venta.pedido.cliente.apellidos))+" - "+(str(venta.pedido.cliente.area)) , getStyleSheet()['TopicItem1']) ventas.append(header) ventas.append(Spacer(1, 0.2 * inch)) ventas.append(documento) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(cliente) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(Paragraph(venta.pedido.cliente.tipo_documento+": "+venta.pedido.cliente.nro_documento+" ",getStyleSheet()['TopicItem1'])) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(Paragraph("DIRECCION: "+venta.pedido.cliente.direccion+" ",getStyleSheet()['TopicItem1'])) ventas.append(Spacer(1, 0.05 * inch)) ventas.append(Paragraph("FECHA DE COMPRA: "+datetime.strftime(venta.fecha, "%d-%m-%Y")+" ",getStyleSheet()['TopicItem1'])) ventas.append(Spacer(1, 0.1 * inch)) ventas.append(Paragraph("DETALLE DE LA COMPRA", getStyleSheet()['TopicTitle10'])) ventas.append(Spacer(1, 0.1 * inch)) headings = ('DESCRIPCION', 'PRECIO', "CANTIDAD", 'SUBTOTAL') detalleventa = [(str(dv.producto.descripcion), str(dv.precio), str(dv.cantidad), str(dv.precio*dv.cantidad)) for dv in DetalleVenta.objects.filter(venta_id=idventa)] data = ([headings] + detalleventa) data2 = [[Paragraph(cell, getStyleSheet()['TopicItemq0']) for cell in row] for row in data] t=Table(data2) style = TableStyle( [ ('BACKGROUND', (0, 0), (-1, 0), colors.gray), ('LINEABOVE', (0,0), (-1,0), 2, colors.green), ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green), ('ALIGN', (1,1), (-1,-1), 'CENTER'), ] ) t.setStyle(style) t._argW[0]=4*inch t._argW[1]=0.8*inch t._argW[2]=0.8*inch t._argW[3]=0.8*inch ventas.append(t) ventas.append(Paragraph("Sub total:__ "+str(venta.sub_total)+" S/", getStyleSheet()['TopicTitle8Right'])) ventas.append(Paragraph("IGV:___"+str(venta.igv)+" S/", getStyleSheet()['TopicTitle8Right'])) ventas.append(Paragraph("Total:__ "+str(venta.total)+" S/", getStyleSheet()['TopicTitle8Right'])) doc.build(ventas) response.write(buff.getvalue()) buff.close() return response
def checkout_receipt(context, request): db_session = request.db_session results = filter_aliquot(context, request, state='pending-checkout') query = results['full_query'] try: sent_name = ( db_session.query(sa.distinct(models.Aliquot.sent_name)) .select_from(query.subquery()) .scalar()) except orm.exc.MultipleResultsFound: sent_name = None try: location = ( db_session.query(models.Location) .join(query.subquery(), models.Location.aliquot) .one()) except orm.exc.NoResultFound: location = None except orm.exc.MultipleResultsFound: location = None fp = six.StringIO() doc = SimpleDocTemplate( fp, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = landscape(letter) elements = [] styles = getSampleStyleSheet() paragraph_style = styles['Normal'] if location: elements.append(Paragraph(_('Send to:'), paragraph_style)) if sent_name: elements.append(Paragraph(sent_name, paragraph_style)) if location.long_title1: elements.append(Paragraph(location.long_title1, paragraph_style)) if location.long_title2: elements.append(Paragraph(location.long_title2, paragraph_style)) if location.address_street: elements.append( Paragraph(location.address_street, paragraph_style)) if location.address_city and \ location.address_state and location.address_zip: elements.append(Paragraph('{0}, {1} {2}'.format( location.address_city, location.address_state, location.address_zip), paragraph_style)) if location.phone_number: elements.append(Paragraph(location.phone_number, paragraph_style)) if location.fax_number: elements.append(Paragraph(location.fax_number, paragraph_style)) else: elements.append( Paragraph(_( u'Multiple send locations were found. ' u'Please update your aliquot, or change your filter.' ), paragraph_style)) elements.append(Spacer(1, 12)) # TODO: Get this line right instead of just copying it from the docs style = TableStyle([ ('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' header = [ _(u'ID'), _(u'PID'), _(u'Collect Date & Time'), _(u'Visit'), _(u'Type'), _(u'Amt.'), _(u'Sent Date'), _(u'Shipping Notes') ] full_width = 10 * inch column_widths = [ 0.07 * full_width, # id 0.08 * full_width, # pid 0.15 * full_width, # collect date 0.10 * full_width, # visit 0.15 * full_width, # type 0.10 * full_width, # amount 0.10 * full_width, # sent date 0.25 * full_width, # shipping notes ] rows = chain([header], iter([ six.text_type(sample.id), six.text_type(sample.specimen.patient.pid), '{} {}'.format( sample.collect_date.isoformat(), sample.collect_time.strftime('%H:%M')), u'{0} - {1}'.format( sample.specimen.cycle.study.short_title, sample.specimen.cycle.week), sample.aliquot_type.title, u'{0}{1}'.format( six.text_type(sample.amount or u'--'), sample.aliquot_type.units or u''), sample.sent_date.isoformat() if sample.sent_date else '', sample.sent_notes or '', ] for sample in query )) data = [[Paragraph(cell, s) for cell in row] for row in rows] t = Table(data, colWidths=column_widths) t.setStyle(style) # Send the data and build the file elements.append(t) doc.build(elements) fp.flush() fp.seek(0) response = request.response response.content_type = 'application/pdf' response.content_disposition = 'attachment;filename=receipt.pdf' response.app_iter = FileIter(fp) return response
def reportGen(request): response = HttpResponse(content_type="application/pdf") # response['Content-Disposition'] = 'attachement; filename=acs.pdf' doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = portrait(A4) h1 = PS(name="Heading1", fontSize=14, leading=30, leftIndent=170) h2 = PS(name="Heading1", fontSize=12, leading=20, leftIndent=30, spaceAfter=20) # Table Headers elements = [] elements.append(Paragraph("<b>Damage Assessment Format</b>", h1)) elements.append( Paragraph( "<i>[In-depth sectoral Assessment to have medium and long-term relief, rehabilitation and reconstruction assistance for critical sectors, assessment to be carried out by specialist]</i>", h2, ) ) context = {} context["Food"] = Food.objects.values_list() context["FoodData"] = {} for listItems in context["Food"]: if listItems[1] in context["FoodData"]: context["FoodData"][listItems[1]] = context["FoodData"][listItems[1]] + int(listItems[2]) else: context["FoodData"][listItems[1]] = listItems[2] Data = [["<b>Food Type Requirement</b>", "<b>Information</b>"]] for key, values in context["FoodData"].iteritems(): Data.append([key, str(values)]) Data.append(["", ""]) Data.append(["<b>Victim Affected</b>", "<b>Information</b>"]) context = {} context["Victim"] = Victims.objects.values_list() context["VictimData"] = {} for listItems in context["Victim"]: if listItems[1] in context["VictimData"]: context["VictimData"][listItems[1]] = context["VictimData"][listItems[1]] + int(listItems[2]) else: context["VictimData"][listItems[1]] = listItems[2] for key, values in context["VictimData"].iteritems(): Data.append([key, str(values)]) Data.append(["", ""]) Data.append(["<b> Health Situation</b>", "<b>Information</b>"]) context = {} context["Health"] = Health.objects.values_list() context["HealthData"] = {} for listItems in context["Health"]: if listItems[1] in context["HealthData"]: context["HealthData"][listItems[1]] = context["HealthData"][listItems[1]] + int(listItems[2]) else: context["HealthData"][listItems[1]] = listItems[2] for key, values in context["HealthData"].iteritems(): Data.append([key, str(values)]) Data.append(["", ""]) Data.append(["<b> Shelter Situation</b>", "<b>Information</b>"]) context = {} context["Shelter"] = Shelter.objects.values_list() context["ShelterData"] = {} for listItems in context["Shelter"]: if listItems[1] in context["ShelterData"]: context["ShelterData"][listItems[1]] = context["ShelterData"][listItems[1]] + int(listItems[2]) else: context["ShelterData"][listItems[1]] = listItems[2] for key, values in context["ShelterData"].iteritems(): Data.append([key, str(values)]) context["countIMG"] = Files.objects.filter(Type="IMG").count() context["countVID"] = Files.objects.filter(Type="VID").count() context["countSMS"] = Files.objects.filter(Type="SMS").count() context["countTXT"] = Files.objects.filter(Type="TXT").count() context["countAUD"] = Files.objects.filter(Type="AUD").count() Data.append(["", ""]) Data.append(["<b>Types of Files in DropBox</b>", "<b>Information</b>"]) Data.append(["Image Files", str(context["countIMG"])]) Data.append(["Video Files", str(context["countVID"])]) Data.append(["Audio Files", str(context["countAUD"])]) Data.append(["Text Files", str(context["countTXT"])]) Data.append(["SMS Files", str(context["countSMS"])]) # TODO: Get this line right instead of just copying it from the docs 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), ("FONTSIZE", (0, 1), (-1, 1), 18), ("TEXTFONT", (0, 1), (-1, 1), "Times-Bold"), ("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" 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) return response