def write_pdf( self, file_object, ): context = self.get_context_data() template = self.get_template_names()[0] generate_pdf(template, file_object=file_object, context=context)
def make_current_month_invoice(email): resp = HttpResponse(content_type='application/pdf') this_account = Account.objects.get(email=email) context = { "email": email, "invoice_number": 124124, "services": Service.objects.filter(account=this_account) } print generate_pdf('invoice.html', context=context)
def getreleasenotepage(request, project_name, version_pk): project_list = Project.objects.all() project = get_object_or_404(Project, name=project_name) version = get_object_or_404(Version, pk=version_pk) stage = Stage.objects.all() baselinetype = BaselineType.objects.all() firmwarecatalog = FirmwareCatalog.objects.all() releaseinfocatalog = ReleaseInfoCatalog.objects.all() baselineinclusion = BaselineInclusion.objects.filter(project=project) firmware = Firmware.objects.filter(project=project) releaseinfo = [] for rc in releaseinfocatalog: releaseinfo.append( ReleaseInfo.objects.filter(version=version, catalog=rc)) # Non-ASCii Code character checkbox = '\xe2\x96\xa1' filledcheckbox = '\xe2\x96\xa0' if version.releasenote: tmpfile = open(version.releasenote.filedata.path, 'w+') result = generate_pdf('release/release_pdf.html', file_object=tmpfile, context=locals()) tmpfile.close() else: filename = ''.join('%s_SDP_2_1_08_01_a_Release_Note_Ver_%s.pdf' % (project.name, version.releasename)) # XHTML2PDF tmpfile = tempfile.NamedTemporaryFile() result = generate_pdf('release/release_pdf.html', file_object=tmpfile, context=locals()) f = File(tmpfile) # For Database rnfile = ReleaseNoteFile() rnfile.filedata.save(filename, f) tmpfile.close() version.releasenote = rnfile version.save() response = HttpResponse(version.releasenote.filedata.read(), mimetype='application/pdf') return response
def pdfview(request): resp = HttpResponse(content_type='application/pdf') context = { 'students': Student.objects.all() } result = generate_pdf('pdf/student_pdf.html', file_object=resp, context=context) return result
def salida_print(request, id): salida = Salida.objects.get(id = id) resp = HttpResponse(content_type = 'application/pdf') context = {'salida': salida} result = generate_pdf('pdf/salida.html', file_object = resp, context = context) return result
def inventario_print(request, id): almacen = Almacen.objects.get(pk = id) stock = Stock.objects.filter(en_almacen = almacen) resp = HttpResponse(content_type = 'application/pdf') context = {'stock': stock, 'almacen': almacen, 'total': total_monto_stock(almacen)} result = generate_pdf('pdf/inventario.html', file_object = resp, context = context) return result
def venta_print(request, id): venta = Venta.objects.get(id = id) resp = HttpResponse(content_type = 'application/pdf') context = {'venta': venta} result = generate_pdf('pdf/venta.html', file_object = resp, context = context) return result
def test_view_fileobject(request): # this test file_object as None in py2 and py3 resp = HttpResponse(content_type='application/pdf') result = generate_pdf('test_pdf.html') result.seek(0) resp.write(result.read()) return resp
def liquidacion_cobradores(request): cant_impr = int(request.GET['cant_impr']) ult_impr = int(request.GET['ult_impr']) primer_num = ult_impr+1 ultimo_num = primer_num + cant_impr numeracion_liq = numeracion.objects.filter(nombre='liquidaciones')[0:1].get() numeracion_liq.numero = ultimo_num numeracion_liq.save() numbers = [] for i in range(primer_num, ultimo_num): numbers += [str(i).zfill(8)] globales = custom_proc(request) result = generate_pdf( 'reportes_pdf_liquidacion_cobradores.html', file_object=HttpResponse(content_type='application/pdf'), context={ 'numeros': numbers, 'globales':globales, } ) return result
def f_student_report(request, pago_id): pago = Pago.objects.get(pk=pago_id) #get_object_or_404 student = pago.alumno student_services = student.suscript_services( ) #servicios suscriptos-no muestra pagos unicos realizados fecha = date.today() comentarios = pago.comentarios items = ItemPago.objects.filter(pago=pago.id) fname = '%s_%d-%d-%d' % (student.last_name, fecha.day, fecha.month, fecha.year) resp = HttpResponse(content_type='application/pdf') resp['Content-Disposition'] = 'attachment; filename=%s.pdf' % fname result = generate_pdf('finance/f_student_report_improved.html', file_object=resp, context={ 'student': student, 'services': student_services, 'items': items, 'pago': pago, 'fecha': fecha, 'comentarios': comentarios, }) return result
def cotizacion_print(request, id): cotizacion = Cotizacion.objects.get(id = id) resp = HttpResponse(content_type = 'application/pdf') context = {'cotizacion': cotizacion} result = generate_pdf('pdf/cotizacion.html', file_object = resp, context = context) return result
def quotation_pdf(request, pk): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="cotizacion.pdf"' order = Order.objects.get(pk=pk) context = {'order': order} result = generate_pdf('store/quotation_pdf.html', file_object=response, context=context) return result
def entrada_print(request, id): entrada = Entrada.objects.get(id = id) resp = HttpResponse(content_type = 'application/pdf') context = {'entrada': entrada} result = generate_pdf('front/pdf/entrada.html', file_object = resp, context = context) return result
def books_plain_old_view(request): resp = HttpResponse(content_type='application/pdf') context = {'books': Book.objects.all()} result = generate_pdf('books_plain_old_view.html', file_object=resp, context=context) return result
def books_plain_old_view(request): resp = HttpResponse(content_type='application/pdf') context = { 'books': Book.objects.all() } result = generate_pdf('books_plain_old_view.html', file_object=resp, context=context) return result
def myview(response, id): pres = { 't': Badanie.objects.filter(zbiornik_id=id).aggregate(Max('cisnienie')), } pres = pres['t']['cisnienie__max'] pres = float(pres / 10) poj = Zbiornik.objects.get(id=id) print(poj.rodzaj.capacity) woda = {'w': Badanie.objects.filter(zbiornik_id=id).aggregate(Max('woda'))} woda = woda['w']['woda__max'] procent = woda / poj.rodzaj.capacity * 100 print(procent) data = { 'today': datetime.date.today(), 'tank': Zbiornik.objects.get(id=id), 'badania': Badanie.objects.filter(zbiornik_id=id).order_by('cisnienie'), 'pres': pres, 'woda': woda, 'procent': procent, 'typ': poj.rodzaj.tank } resp = HttpResponse(content_type='application/pdf') result = generate_pdf('print.html', context=data, file_object=resp) return result
def merch_invoice(merch_id): print "starting the generate_invoice task" MerchandiseApp = get_model('mcmun', 'MerchandiseApp') merch = MerchandiseApp.objects.get(pk=merch_id) invoice_context = { 'first_name': merch.school.first_name, 'school_name': merch.school.school_name, 'total_balance': merch.get_total_price(), 'currency': merch.school.get_currency(), } invoice_subject = 'Invoice for merchandise order' invoice_message_filename = 'merch-invoice' invoice_id = 'SSUNS14' + str(merch_id).zfill(3) + 'M' pdf_context = { 'invoice_id': invoice_id, 'school': merch.school, 'merch': merch, } # Generate the invoice PDF, save it under tmp/ pdf_filename = 'mcmun/invoice/ssuns_invoice_%s_merchandise.pdf' % merch_id file = open(pdf_filename, 'wb') pdf = generate_pdf('pdf/merch-invoice.html', file_object=file, context=pdf_context) file.close() attachment_filenames = [pdf_filename] send_email.delay(invoice_subject, invoice_message_filename, [merch.school.account.email], context=invoice_context, bcc=[settings.IT_EMAIL, settings.STAFF_EMAIL, settings.FINANCE_EMAIL], attachment_filenames=attachment_filenames)
def render_pdf(request, template, context, pk=None, company_name=None): filename = 'export.pdf' if company_name and pk: filename = '%s_%s_%s.pdf' % (company_name, 'invoice'.upper(), pk) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=%s' % filename return generate_pdf( 'invoice_pdf.html', context=context, file_object=response)
def books_plain_old_view_content_disp(request): resp = HttpResponse(content_type='application/pdf') resp['Content-Disposition'] = 'attachment; filename="output.pdf"' context = {'books': Book.objects.all()} result = generate_pdf('books_plain_old_view.html', file_object=resp, context=context) return result
def books_plain_old_view_content_disp(request): resp = HttpResponse(content_type='application/pdf') resp['Content-Disposition'] = 'attachment; filename="output.pdf"' context = { 'books': Book.objects.all() } result = generate_pdf('books_plain_old_view.html', file_object=resp, context=context) return result
def render_html_or_pdf(request, templateName, context, **kwargs): fmt = kwargs.get('fmt', 'pdf') if fmt == 'pdf': context = RequestContext(request, context) file_object = HttpResponse(content_type='application/pdf') return generate_pdf(templateName, file_object, context) else: return render(request, templateName, context)
def render_to_response(self, context, **response_kwargs): context = self.get_context_data() template = self.get_template_names()[0] resp = HttpResponse(content_type="application/pdf") resp["Content-Disposition"] = 'attachment; filename="{0}.pdf"'.format( self.get_pdf_name()) result = generate_pdf(template, file_object=resp, context=context) return result
def generate_invoice(school_id, username, password): print "starting the generate_invoice task" RegisteredSchool = get_model('mcmun', 'RegisteredSchool') school = RegisteredSchool.objects.get(pk=school_id) invoice_context = { 'first_name': school.first_name, 'school_name': school.school_name, 'username': username, 'password': password, 'num_delegates': school.num_delegates, 'payment_method': 'online payment' if school.use_online_payment else 'cheque', 'payment_type': school.get_payment_type(), 'total_balance': school.get_total_owed(), 'currency': school.get_currency(), 'tiered_or_not': 'using our tiered system of deposit and remainder' if school.use_tiered else 'in full', } # Send out an email to the user explaining that their account has been approved # CC myself just in case they forget the password or whatever invoice_subject = 'Invoice for McMUN 2013' invoice_message_filename = 'invoice' invoice_id = 'MC13' + str(school_id).zfill(3) pdf_context = { 'invoice_id': invoice_id, 'payment_type': school.get_payment_type(), 'school': school, } # Generate the invoice PDF, save it under tmp/ pdf_filename = 'tmp/mcmun_invoice_%s.pdf' % invoice_id file = open(pdf_filename, 'wb') pdf = generate_pdf('pdf/invoice.html', file_object=file, context=pdf_context) file.close() attachment_filenames = [pdf_filename] send_email.delay(invoice_subject, invoice_message_filename, [school.email], context=invoice_context, bcc=[settings.IT_EMAIL, settings.CHARGE_EMAIL], attachment_filenames=attachment_filenames)
def pedido_imprimir_consumo(request, id): pedido = Pedido.objects.get(id = id) consumo = Consumo.objects.get(pedido = pedido) resp = HttpResponse(content_type = 'application/pdf') context = {'consumo': consumo} result = generate_pdf('pdf/consumo.html', file_object = resp, context = context) return result
def render_pdf(context, **kwargs): """ """ filename = kwargs.get("filename") template = kwargs.get("template") response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "filename=%s" % filename return generate_pdf(template, context=context, file_object=response)
def print_pedido(request, id): try: pedido = Pedido.objects.get(id = id) except pedido.DoesNotExist: raise Http404 resp = HttpResponse(content_type='application/pdf') context = {'pedido': pedido, 'total': total_pedido(pedido)} result = generate_pdf('pedido.html', file_object = resp, context = context) return result
def venta_print(request, id): venta = Venta.objects.get(id = id) resp = HttpResponse(content_type = 'application/pdf') context = {'venta': venta} if venta.tipo_venta == 'P': amortizaciones = Amortizacion.objects.filter(deuda = venta.deuda.pk) context['amortizaciones'] = amortizaciones result = generate_pdf('pdf/venta.html', file_object = resp, context = context) return result
def catalog1(request): refCat1_A = Category1.objects.get(name = "Hotelaria") queryset = Product.objects.select_related().filter( cat1=refCat1_A) # return render_to_response("products/product_list_PDF.html", {"object_list": queryset }) resp = HttpResponse(content_type='application/pdf') result = generate_pdf('products/product_list_PDF.html', file_object=resp, context={"object_list": queryset}) return result
def invoice_page(request): from django_xhtml2pdf.utils import generate_pdf resp = HttpResponse(content_type='application/pdf') context = { "user": request.user, "invoice_number": 124124, "services": Service.objects.filter(account=request.user) } result = generate_pdf('invoice.html', file_object=resp, context=context) return result
def generate_current_month_invoice(account): from django_xhtml2pdf.utils import generate_pdf from core.models import Invoice context = { "user": account, "invoice_number": 124124, "services": Service.objects.filter(account=request.user) } result = generate_pdf('invoice.html', file_object=resp, context=context) return result
def _get_output(self, res, **kwargs): from django_xhtml2pdf.utils import generate_pdf output = BytesIO() ctx = { 'headers': res.header_strings, 'data': res.data, } result = generate_pdf('explorer/pdf_template.html', file_object=output, context=ctx) return output
def gerar_pdf(request,emissor, destinatario, protocolo): from django.template import Context# loader,Context, Template path = os.path.join(BASE_DIR, "static/imagens/") print(protocolo.data_emissao, protocolo.hora_emissao) parametros = { 'emissor_nome':emissor.nome, 'emissor_cpf_cnpj':formatar_cpf_cnpj(emissor.cpf_cnpj), 'emissor_endereco':emissor.endereco, 'emissor_contatos':emissor.contatos, 'destinatario_nome':destinatario.nome, 'destinatario_cpf_cnpj':destinatario.cpf_cnpj, 'destinatario_endereco':destinatario.endereco, 'destinatario_complemento':destinatario.complemento, 'destinatario_contatos':destinatario.contatos, 'codigo_protocolo':destinatario.codigo_protocolo, 'emitido_por':'Marcelo', 'data_emissao':protocolo.data_emissao, 'hora_emissao':protocolo.hora_emissao, 'recebido_por':"",#recebido_por, 'identificacao':"",#identidade, 'data_entrega':"",#data_entrega, 'hora_entrega':"",#hora_entrega, 'documentos':"",#formulario.temporarios, #'documentos':[ # ["33","IMPOSTO DE RENDA","2015","","R$ 285,50"], # ["8","EMISSAO DE CERTIFICADO DIGITAL","","31/12/2018","R$ 175,10"], # ["14","CONTRATO - PLANO COMPLETO","","31/12/2018","R$ 475,00"], # ], #'formulario_protocolo':"Nada por enquanto", #'erro':"sem erros tambem", #'path':path, 'path_imagens':path } c = Context(parametros) # RENDERIZAR NORMAL #return render_to_response('protocolo/imprimir_protocolo.html', c) # RENDERIZAR PDF from django_xhtml2pdf.utils import generate_pdf resp = HttpResponse(content_type='application/pdf') result = generate_pdf('protocolo/imprimir_protocolo.html', file_object=resp,context=c) return result
def CoursesListPdf(request): if request.user.is_authenticated: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="output.pdf"' context = {'courses': Courses.objects.all()} result = generate_pdf('courses_pdf.html', file_object=response, context=context) return result else: return HttpResponse("you need to login!!")
def pedido_imprimir_factura(request, id): pedido = Pedido.objects.get(id = id) factura = Factura.objects.get(pedido = pedido) factura.totalnum = cardinal(factura.total) resp = HttpResponse(content_type = 'application/pdf') context = {'factura': factura} result = generate_pdf('pdf/factura.html', file_object = resp, context = context) return result
def pedido_imprimir_boleta(request, id): pedido = Pedido.objects.get(id = id) boleta = Boleta.objects.get(pedido = pedido) boleta.totalnum = cardinal(boleta.total) resp = HttpResponse(content_type = 'application/pdf') context = {'boleta': boleta} result = generate_pdf('pdf/boleta.html', file_object = resp, context = context) return result
def regenerate_add_invoice(school_id, add_id): print "starting the add generate_invoice task" RegisteredSchool = get_model('mcmun', 'RegisteredSchool') AddDelegates = get_model('mcmun', 'AddDelegates') school = RegisteredSchool.objects.get(pk=school_id) addDelegates = AddDelegates.objects.get(pk=add_id) invoice_context = { 'first_name': school.first_name, 'school_name': school.school_name, 'num_delegates': addDelegates.add_num_delegates, 'payment_method': 'online payment' if addDelegates.add_use_online_payment else 'cheque', 'payment_type': school.get_payment_type(), 'total_balance': addDelegates.get_add_total_owed(), 'currency': school.get_currency(), } # Send out an email to the user explaining that their account has been approved # CC myself just in case they forget the password or whatever invoice_subject = 'Invoice for SSUNS 2014, addtional delegates' invoice_message_filename = 'add-invoice' invoice_id = 'SSUNS14' + str(add_id).zfill(3) pdf_context = { 'invoice_id': invoice_id, 'school': school, 'addDelegates': addDelegates, } # Generate the invoice PDF, save it under tmp/ pdf_filename = 'mcmun/addinvoice/ssuns_invoice_%s.pdf' % invoice_id file = open(pdf_filename, 'wb') pdf = generate_pdf('pdf/add-invoice.html', file_object=file, context=pdf_context) file.close() attachment_filenames = [pdf_filename] send_email.delay( invoice_subject, invoice_message_filename, [school.account.email], context=invoice_context, bcc=[settings.IT_EMAIL, settings.CHARGE_EMAIL, settings.FINANCE_EMAIL], attachment_filenames=attachment_filenames)
def invoice(request, pk=None): context = {} company = Company.get_solo() if company: context['company'] = company pdf = get_query(request, 'pdf') context['pdf'] = pdf invoice = get_object_or_404(Invoice, pk=pk) document_id = str(invoice.document_id) document_type = invoice._meta.verbose_name document_type_upper = document_type.upper() document_type_title = document_type.title() context['edit_url'] = 'invoice_edit' # Delete form modal context['item'] = invoice context['document_type_upper'] = document_type_upper context['document_type_title'] = document_type_title times_project = Time.objects.filter( invoiced=False, project=invoice.project, estimate=None, invoice=None) times_invoice = Time.objects.filter(invoice=invoice) times = times_project | times_invoice times = times.order_by('-date') entries, subtotal, paid_amount, hours, amount = entries_total(times) context['entries'] = entries context['amount'] = amount context['paid_amount'] = paid_amount context['subtotal'] = subtotal context['hours'] = hours context['invoice'] = True if pdf: response = HttpResponse(content_type='application/pdf') if company.name: company_name = company.name.replace('.', '_') company_name = company_name.replace(', ', '_') company_name = company_name.upper() else: company_name = 'COMPANY' filename = '_'.join([document_type_upper, document_id, company_name]) response['Content-Disposition'] = 'filename=%s.pdf' % filename return generate_pdf( 'pdf_table.html', context=context, file_object=response) else: return render(request, 'invoice.html', context)
def get_adult_update_application_summary(adult_id): """ Generates a full adult update summary in a PDF format that has been base64 encoded """ resp = HttpResponse(content_type='application/pdf') variables = get_adult_update_summary_variables(adult_id) result = generate_pdf('adult-update-pdf-summary.html', file_object=resp, context=variables) base64_string = str(base64.b64encode(result.content).decode("utf-8")) log.debug( "Generating PDF and base64 representation for Adult Update Details Summary" ) return base64_string
def document(request, pk=None): context = {} document = get_object_or_404(Document, pk=pk) context['document'] = document pdf = request.GET.get('pdf') context['pdf'] = pdf if pdf: response = HttpResponse(content_type='application/pdf') return generate_pdf('document.html', context=context, file_object=response) else: return render(request, 'document.html', context)
def generate_invoice(invoice_number, description, amount_paid, card_type, last4, email=None, name=None, file_object=None): params = {}; if email is not None: params['to_contact_email'] = email; if name is not None: params['to'] = name; params['description'] = description params['invoice_number'] = invoice_number; params['amount_paid'] = amount_paid; params['card_number'] = "XXXXXXXXXXXX" + last4 params['card_type'] = card_type; params['date'] = datetime.now(); context = Context(params) result = generate_pdf('invoice/invoice.html', file_object=file_object, context=context) return result;
def get_full_childminder_application_summary(application_id): """ Generates a full application summary in a PDF format that has been base64 encoded (for EYC portions of a document submission to NOO) """ resp = HttpResponse(content_type='application/pdf') variables = get_application_summary_variables( application_id, apply_filtering_for_eyc=True) result = generate_pdf('childminder-pdf-summary.html', file_object=resp, context=variables) base64_string = str(base64.b64encode(result.content).decode("utf-8")) log.debug( "Generating PDF and base64 representation for Childminder Application Summary" ) return base64_string
def get_full_nanny_application_summary(application_id, application_reference): """ Generates a full nanny application summary in a PDF format that has been base64 encoded """ resp = HttpResponse(content_type='application/pdf') nanny_summary_tables = get_nanny_summary_variables(application_id) variables = { 'application_reference': application_reference, 'json': nanny_summary_tables } result = generate_pdf('nanny-pdf-summary.html', file_object=resp, context=variables) base64_string = str(base64.b64encode(result.content).decode("utf-8")) log.debug( "Generating PDF and base64 representation for Nanny Application Summary" ) return base64_string
def reporte_personal_print(request): fecha = request.GET.get('fecha') personal = Personal.objects.filter(activo = True) results = [] for persona in personal: registros = get_registros_personal(persona, fecha) horarios = get_horarios_personal(persona) results.append({ 'DNI': persona.DNI, 'nombres': persona.nombres, 'apellidos': persona.apellidos, 'horarios': horarios, 'registros': registros }) resp = HttpResponse(content_type = 'application/pdf') context = {'results': results, 'fecha': datetime.datetime.strptime(fecha, '%Y-%m-%d')} return generate_pdf('reporte-personal-print.html', file_object = resp, context = context)
def note(request, pk=None): context = {} pdf = get_query(request, 'pdf') context['pdf'] = pdf note = get_object_or_404(Note, pk=pk) notes = Note.objects.filter(note=note) notes = notes.order_by('-pk') context['edit_url'] = 'note_edit' context['item'] = note if pdf: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=note.pdf' return generate_pdf( 'pdf_note.html', context=context, file_object=response) else: return render(request, 'note.html', context)
def downloadSyllabus(request, department, class_number, year, semester, section): user = request.user c = getClassObject(department, class_number, year, semester, section, user) message = '' #Check if syllabus exists try: syllabus = CourseContent.objects.get(cid = c.cid) except CourseContent.DoesNotExist: message = 'No syllabus has been created for this class.' syllabus = [] content = getContent(c, user) content['syllabus'] = syllabus content['message'] = message filename = c.department+'%s'%c.class_number+'%s'%year+'.pdf' resp = HttpResponse(content_type='application/pdf') resp['Content-Disposition'] = 'attachment; filename='+filename.lower() result = generate_pdf('student/syllabusPDF.html', file_object=resp, context=content) return result
def listado_cobradores(request): cobr = request.GET['cobrador'] orde = request.GET['orden'] coza = request.GET['cobranza'] list_coza = cobranza.objects.get(cobranza_id=coza) recibos = recibo.objects.select_related() recibos = recibos.filter(cobranza=coza) if cobr == '0': filtro_txt = "Ninguno" elif cobr != '0': recibos = recibos.filter(cobrador=cobr) a = cobrador.objects.get(cobrador_id=cobr) filtro_txt = "Cobrador " + a.cobrador if orde == 'num': recibos = recibos.order_by('cobrador','socio__num_socio') orden_txt = 'Numero de Socio' elif orde == 'ape': recibos = recibos.order_by('cobrador','socio__apellido','socio__nombre') orden_txt = 'Apellido y Nombre' globales = custom_proc(request) result = generate_pdf( 'reportes_pdf_listado_cobradores.html', file_object=HttpResponse(content_type='application/pdf'), context={ 'recibos':recibos, 'orden_txt': orden_txt, 'filtro_txt': filtro_txt, 'list_coza':list_coza, 'globales':globales, } ) return result
def f_student_report(request, pago_id): pago = Pago.objects.get(pk=pago_id) #get_object_or_404 student = pago.alumno student_services = student.suscript_services() #servicios suscriptos-no muestra pagos unicos realizados fecha = date.today() comentarios = pago.comentarios items = ItemPago.objects.filter(pago=pago.id) fname = '%s_%d-%d-%d' % (student.last_name, fecha.day, fecha.month, fecha.year) resp = HttpResponse(content_type='application/pdf') resp['Content-Disposition'] = 'attachment; filename=%s.pdf' % fname result = generate_pdf('finance/f_student_report_improved.html', file_object=resp, context={ 'student': student, 'services': student_services, 'items': items, 'pago': pago, 'fecha': fecha, 'comentarios': comentarios, }) return result
def reporte_porcentaje_print(request): curso = request.GET.get('curso') alumnos = get_alumnos_curso(curso) results = [] for alumno in alumnos: porcentaje = get_porcentaje_alumno(alumno, curso) results.append({ 'DNI': alumno.DNI, 'nombres': alumno.nombres, 'apellidos': alumno.apellidos, 'porcentaje': '%.2f' % porcentaje }) curso = Curso.objects.get(pk = curso) resp = HttpResponse(content_type = 'application/pdf') context = {'results': results, 'curso': curso} return generate_pdf('reporte-porcentaje-print.html', file_object = resp, context = context)
def merch_invoice(merch_id): print "starting the generate_invoice task" MerchandiseApp = get_model('mcmun', 'MerchandiseApp') merch = MerchandiseApp.objects.get(pk=merch_id) invoice_context = { 'first_name': merch.school.first_name, 'school_name': merch.school.school_name, 'total_balance': merch.get_total_price(), 'currency': merch.school.get_currency(), } invoice_subject = 'Invoice for merchandise order' invoice_message_filename = 'merch-invoice' invoice_id = 'SSUNS14' + str(merch_id).zfill(3) + 'M' pdf_context = { 'invoice_id': invoice_id, 'school': merch.school, 'merch': merch, } # Generate the invoice PDF, save it under tmp/ pdf_filename = 'mcmun/invoice/ssuns_invoice_%s_merchandise.pdf' % merch_id file = open(pdf_filename, 'wb') pdf = generate_pdf('pdf/merch-invoice.html', file_object=file, context=pdf_context) file.close() attachment_filenames = [pdf_filename] send_email.delay( invoice_subject, invoice_message_filename, [merch.school.account.email], context=invoice_context, bcc=[settings.IT_EMAIL, settings.STAFF_EMAIL, settings.FINANCE_EMAIL], attachment_filenames=attachment_filenames)
def view(self, request, id=None): self.start_process(request) from django_xhtml2pdf.utils import generate_pdf id = id or request.POST['order_id'] order = Order.objects.filter(pk=int(id)) if order.count() > 0: response_order = self.prepare_order(order[0]) respone_content = HttpResponse(content_type='application/pdf') result = generate_pdf('order_pdf.html', file_object=respone_content, context={ 'order': response_order, 'company_name': 'Gigabyte', 'attendant_name': 'Diegao' }) return result return self.response({ "result": False, "object": None, "message": "Object not found" })
def generate_invoice(invoice_number, description, amount_paid, card_type, last4, email=None, name=None, file_object=None): params = {} if email is not None: params['to_contact_email'] = email if name is not None: params['to'] = name params['description'] = description params['invoice_number'] = invoice_number params['amount_paid'] = amount_paid params['card_number'] = "XXXXXXXXXXXX" + last4 params['card_type'] = card_type params['date'] = datetime.now() context = Context(params) result = generate_pdf('invoice/invoice.html', file_object=file_object, context=context) return result
def gerar_pdf(request): from django.template import Context # loader,, Template #from xhtml2pdf import pisa parametros = { 'emissor': "Digitar Contabilidade", 'destinatario': "HELDER PASTI", 'endereco_destinatario': "Rua demósthenes Nunes Vieira, 60, Alto Lage, Cariacica - ES", 'endereco_emissor': "Reta da Penha, Vitória - ES", 'codigo_protocolo': "P102", 'documentos': [ ["33", "IMPOSTO DE RENDA", "2015", "", "R$ 285,50"], [ "8", "EMISSÃO DE CERTIFICADO DIGITAL", "", "31/12/2018", "R$ 175,10" ], ["14", "CONTRATO - PLANO COMPLETO", "", "31/12/2018", "R$ 475,00"], ], 'formulario_protocolo': "Nada por enquanto", 'erro': "sem erros tambem" } c = Context(parametros) #{'message': 'Your message'}) from django_xhtml2pdf.utils import generate_pdf resp = HttpResponse(content_type='application/pdf') result = generate_pdf('protocolo/novo_protocolo.html', file_object=resp, context=c) return result
def quote(req, num=None, pdf=False): user = req.user if 0: # messages_test from django.contrib import messages #messages.add_message(req, messages.INFO, 'Hello world.') #Some shortcut methods provide a standard way to add messages with commonly used tags (which are usually represented as HTML classes for the message): messages.debug(req, '%s SQL statements were executed.' % 123) messages.info(req, '%s SQL statements were executed.' % 123) messages.info(req, 'Three credits remain in your account.') messages.success(req, 'Profile details updated.') messages.warning(req, 'Your account expires in three days.') messages.error(req, 'Document deleted.') if num: # render it directly try: q = Quote.objects.get(quote_number=num) except Quote.DoesNotExist: raise Http404 if q: address1 = Address.objects.filter(customer=q.customer) #print address1 shipping_addr = None billing_addr = None if address1: for address in address1: print address.type if address.type == "shipping": shipping_addr = address if address.type == "billing": billing_addr = address if address.type == "both": shipping_addr = address billing_addr = address prod = dict( address1=address1, shipping_addr=shipping_addr, billing_addr=billing_addr, q=q, totprice=q.totprice, summary=q.summary, notes=q.header_items, # terms, discounts, etc? #qty = q.totqty, qty=1, opts={}, baseprice=q.totprice, weight=q.shipping, sku='Quote/%s' % q.quote_number, ) if req.POST.get('add', None): # add quote to cart as product prod = dict( totprice=q.totprice, summary=q.summary, notes=q.header_items, # terms, discounts, etc? #qty = q.totqty, qty=1, opts={}, baseprice=q.totprice, weight=q.shipping, sku='Quote/%s' % q.quote_number, ) ses = req.session ses['cart'] = ses.get('cart', []) + [prod] ses['prod'] = {} return HttpResponseRedirect('/cart/') from pdfdocument.document import PDFDocument text = "Your email confirmation, as PDF attachment\n\n" pdf = generate_pdf('pdf/index.html', context=prod).getvalue() msg = EmailMultiAlternatives( 'Your %s eracks quote #%s' % (settings.HNN[0], q.quote_number), text, # nope: '', # let's try attaching the text, settings.ORDER_FROM_EMAIL, ['*****@*****.**']) msg.attach('eRacks_Quote_#%s.pdf' % q.quote_number, pdf, "application/pdf") # msg.send() if req.POST.get('pdf', None): # add quote to cart as product response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=eRacks_Quote_#%s.pdf' % q.quote_number response.write(pdf) return response # drop thru: email admin, render the quote_number subject = "%s user accessed %s" % (settings.HOST_NAME, req.path) ip = req.META.get( 'HTTP_X_FORWARDED_FOR', req.META.get('HTTP_X_REAL_IP', req.META.get('REMOTE_ADDR', 'unknown'))) message = quote_viewed_template.format(s=settings, ip=ip, u=user, r=req) to = settings.CONTACT_EMAILS fm = '*****@*****.**' # user.email send_mail(subject, message, fm, to, fail_silently=not settings.DEBUG) for line in q.quotelineitem_set.all( ): # lame: dj templates can't do multiplcation or expressions line.ext = line.quantity * line.price return render_to_response('quote.html', dict( title="Quote: %s" % q.quote_number, q=q, ), context_instance=RequestContext(req)) else: # render the list if user.is_staff: qs = Quote.objects.filter(approved_by=user) else: qs = Quote.objects.filter(customer__user=user) return render_to_response('entries.html', dict( entries=qs, title='Quote list for %s' % user, ), context_instance=RequestContext(req))
def pdfGenerate(request): id = request.POST.get("sid") resp = HttpResponse(content_type='application/pdf') context = resultMixin(id) result = generate_pdf('getresult.html', file_object=resp, context=context) return result
def test_view(request): resp = HttpResponse(content_type='application/pdf') result = generate_pdf('test_pdf.html', file_object=resp) return result
def generate_report_view(request, update_index): resp = HttpResponse(content_type='application/pdf') # Fetch data from database raw_data = uRawDataModel.objects.filter(update_index = update_index) ave_temperature = uCalibrationUpdate.objects.get(update_index= update_index).observed_temperature staff_number = uCalibrationUpdate.objects.get(update_index=update_index).staff_number.staff_number staff_owner = uCalibrationUpdate.objects.get(update_index=update_index).staff_number.staff_owner level_number = uCalibrationUpdate.objects.get(update_index=update_index).level_number observation_date = uCalibrationUpdate.objects.get(update_index= update_index).calibration_date # define the staff attributes Staff_Attributes = {'dObsTemperature': ave_temperature, 'dStdTemperature': Staff.objects.get(staff_number=staff_number).standard_temperature, 'dThermalCoefficient': StaffType.objects.get(staff__staff_number=staff_number).thermal_coefficient*10**-6} # Find the range value from the range database month = observation_date.strftime('%b') range_value = RangeParameters.objects.values_list('pin', month) if range_value.exists(): # extract data staff_reading = raw_data.values_list( 'pin_number','staff_reading','number_of_readings','standard_deviations') staff_reading = [list(x) for x in staff_reading] # preprocess data staff_reading2 = preprocess_staff(staff_reading) # compute scale factor CF, GradUnc, StaffCorrections, CF0, T_at_CF_1, Correction_Lists = process_correction_factor(staff_reading2, range_value, Staff_Attributes) # Observer observer = uCalibrationUpdate.objects.get(update_index=update_index) #print(observer.observer) if observer.observer is None or observer.observer == '' or observer.observer == ',': try: if request.user.last_name: observer = request.user.last_name + ', '+ request.user.first_name else: observer = request.user.email except: observer = request.user.email else: observer = observer.observer #print(Correction_Lists) context = { 'update_index': update_index, 'observation_date': observation_date.strftime('%d/%m/%Y'), 'staff_number': staff_number, 'staff_length': Staff.objects.get(staff_number=staff_number).staff_length, 'staff_type': StaffType.objects.get(staff__staff_number=staff_number).staff_type, 'authority': staff_owner, 'thermal_coefficient':StaffType.objects.get(staff__staff_number=staff_number).thermal_coefficient*10**-6, 'level_number': level_number, 'observer': observer, 'average_temperature': ave_temperature, 'ScaleFactor': CF, 'GraduationUncertainty': GradUnc, 'StaffCorrections': StaffCorrections, 'ScaleFactor0': CF0, 'Temperatre_at_1': T_at_CF_1, 'CorrectionList': Correction_Lists, 'today': datetime.now().strftime('%d/%m/%Y %I:%M:%S %p'), } result = generate_pdf('staff_calibration/pdf_staff_report.html', file_object=resp, context=context) return result else: #print("Not range exists") messages.warning(request, 'No range measurements exist for the month of '+month+'. Use the values as shown on the left or try again later.') return redirect('staff_calibration:user-staff-lists') # return render(request, 'staff_calibration/staff_calibration_report.html', context)
def print_table(request, id): table = get_object_or_404(Panel, pk=id) resp = HttpResponse(content_type='application/pdf') return generate_pdf('print/table.html', file_object=resp, context=locals())