def helloWorld(): filename = __file__ + ".pdf" datauri = pisa.makeDataURIFromFile('img/denker.png') bguri = os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir, "pdf/background-sample.pdf")) bguri = pisa.makeDataURIFromFile(bguri) html = """ <style> @page { background: url("%s"); @frame text { top: 6cm; left: 4cm; right: 4cm; bottom: 4cm; -pdf-frame-border: 1; } } </style> <p> Hello <strong>World</strong> <p> <img src="%s"> """ % (bguri, datauri) pdf = pisa.pisaDocument( html, open(filename, "wb"), path = __file__ ) if not pdf.err: pisa.startViewer(filename)
def xhtml2pdf(request): url = "" htmlsrc = "" if request.META["REQUEST_METHOD"] == "POST": htmlsrc = request.POST.items()[0][0] else: request.GET['url'] r = requests.get(url, verify=False) htmlsrc = r.text html = render_to_string('blank.html', {'html': htmlsrc}, context_instance=RequestContext(request)) if request.META["REQUEST_METHOD"] == "POST": rhash = str(urandom(16).encode('hex')) filename = rhash + ".pdf" result = open('/var/www/pdf.voolks.com/media/' + filename, 'wb') pdf = pisa.pisaDocument( StringIO.StringIO(html.encode('ascii')), result) result.close() url = "/media/" + filename return HttpResponse(json.dumps('id': rhash, 'url': url}), content_type="application/json"); else: result = StringIO.StringIO() pdf = pisa.pisaDocument( StringIO.StringIO(html.encode('ascii', 'xmlcharrefreplace')), result, link_callback=link_callback) return HttpResponse(result.getvalue(), mimetype='application/pdf')
def xhtml2pdf(request): url = "" htmlsrc = "" if request.META["REQUEST_METHOD"] == "POST": htmlsrc = request.POST.items()[0][0] else: url = request.GET['url'] r = requests.get(url, verify=False) htmlsrc = r.text html_urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+/', htmlsrc) for html_url in html_urls: if html_url.find(".voolks.com/") < 0 and html_url.find("/voolks.com/") < 0 and html_url.find(".googleapis.com/") < 0: return HttpResponse(json.dumps({"error":"External URL not permitted: " + html_url,"code":"2"}) + "\n", content_type="application/json") html = render_to_string('blank.html', {'html': htmlsrc}, context_instance=RequestContext(request)) if request.META["REQUEST_METHOD"] == "POST": rhash = str(urandom(16).encode('hex')) filename = rhash + ".pdf" result = open(settings.MEDIA_ROOT + filename, 'wb') pdf = pisa.pisaDocument( StringIO.StringIO(html.encode('ascii', 'xmlcharrefreplace')), result) result.close() url = "/media/" + filename return HttpResponse(json.dumps({'id': rhash, 'url': url}), content_type="application/json"); else: result = StringIO.StringIO() pdf = pisa.pisaDocument( StringIO.StringIO(html.encode('ascii', 'xmlcharrefreplace')), result, link_callback=link_callback) return HttpResponse(result.getvalue(), mimetype='application/pdf')
def _generate_pdf(self, id): test = Tests.by({'id':id,'alias':self.request.user.alias}).first() if not test: return None elif test.alias == self.request.user.alias: self.response['test'] = test self.response['results'] = [] self.response['total_correct'] = 0 results = TestsResults.by({'tests_id':id}).all() total = len(results) for result in results: self.response['results'].append( self.get_question_scores(result, total, test.max_wrong_answer_allowed, test.question_time_allowed )) if bool(result.correctly_answered): self.response['total_correct'] += 1 self.response['category'] = None self.response['assessment'] = None try: category = Categories.by({'name':test.category}).first() self.response['category'] = category self.response['assessment'] = category.assess_this(test.percentage) except exc.SQLAlchemyError as e: pass # defensive pdf_html = self.template('pdf.pt') io = StringIO.StringIO() pisa.pisaDocument(StringIO.StringIO( pdf_html.text.encode( "UTF-8" )), io) return io.getvalue() else: return None
def xhtml2pdf_pisa(xhtml, pdf_file): """Converts XHTML input to PDF, using PISA.""" import ho.pisa as pisa with open(pdf_file, 'wb') as outfile: pisa.pisaDocument( StringIO.StringIO(xhtml.encode("UTF-8")), outfile)
def xhtml2pdf(request): url = "" htmlsrc = "" if request.META["REQUEST_METHOD"] == "POST": htmlsrc = request.POST.items()[0][0] else: url = request.GET['url'] r = requests.get(url, verify=False) htmlsrc = r.text html_urls = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+/', htmlsrc) for html_url in html_urls: if html_url.find(".voolks.com/") < 0 and html_url.find( "/voolks.com/") < 0 and html_url.find(".googleapis.com/") < 0: return HttpResponse( json.dumps({ "error": "External URL not permitted: " + html_url, "code": "2" }) + "\n", content_type="application/json") html = render_to_string('blank.html', {'html': htmlsrc}, context_instance=RequestContext(request)) if request.META["REQUEST_METHOD"] == "POST": rhash = str(urandom(16).encode('hex')) filename = rhash + ".pdf" result = open(settings.MEDIA_ROOT + filename, 'wb') pdf = pisa.pisaDocument( StringIO.StringIO(html.encode('ascii', 'xmlcharrefreplace')), result) result.close() url = "/media/" + filename return HttpResponse(json.dumps({ 'id': rhash, 'url': url }), content_type="application/json") else: result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO( html.encode('ascii', 'xmlcharrefreplace')), result, link_callback=link_callback) return HttpResponse(result.getvalue(), mimetype='application/pdf')
def export_budget(request): template = get_template('budget_pdf.html') pjt_id = request.GET.get('pjt_id') version = request.GET.get('version') projectbudget = ProjectBudget.objects.filter(project__id=pjt_id, \ version=version)[0] projectbudgetcost = ProjectBudgetCost.objects.filter(\ project_budget=projectbudget) projectbudgetefforts = ProjectBudgetEfforts.objects.filter(\ project_budget=projectbudget) threshold_effort, threshold_cost, deviation_duration, tot_duration = threshold( request, projectbudget) pagedata = ({ 'projectbudget': projectbudget, 'projectbudgetcost': projectbudgetcost, 'projectbudgetefforts': projectbudgetefforts, 'threshold_effort': threshold_effort, 'threshold_cost': threshold_cost, 'deviation_duration': deviation_duration, 'tot_duration' : tot_duration , 'rejection_reason': '1' if str(projectbudget.status.id) == 'RS5' else '0', 'activity_type': 'Phase' \ if projectbudgetefforts[0].activity_type == '1' else 'Module', }) context = Context(pagedata) html = template.render(context) result = StringIO.StringIO() pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, \ link_callback=fetch_resources) result.seek(0) filename = str(projectbudget.project.name) + '_version' + str(\ projectbudget.version) + '.pdf' folder = 'budgetpdf' currentdir = settings.MEDIA_ROOT currentosdir = currentdir + '/' + folder currentdir = os.listdir(currentdir) check = 0 for each in currentdir: if each == folder: check = 1 if (check != 1): os.mkdir(currentosdir) fd = open('%s/%s' % (currentosdir, filename), 'wb') fd.write(result.getvalue()) fd.close() response = HttpResponse(result.getvalue(), mimetype='application/pdf') filename = filename.replace(' ', '') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response
def pdf_wrapper(request, *args, **kwargs): response = func(request, *args, **kwargs) pdf_context = pisa.pisaDocument(response.content) if not pdf_context.err: return HttpResponse(pdf_context.dest.getvalue(), mimetype='application/pdf') else: raise RuntimeError(pdfpdf_context.log)
def create_pdf(input, output): html = urllib2.urlopen(input).read() result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('utf-8')), result, show_error_as_pdf=True, encoding='UTF-8') if not pdf.err: with open(output, 'wb') as file: file.write(result.getvalue())
def write_pdf(template_src, context_dict): from django import http from django.template.loader import get_template from django.template import Context import ho.pisa as pisa import io.StringIO as StringIO import cgi import os from django.conf import settings template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument( StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8', path=__file__, # link_callback=fetch_resources ) if not pdf.err: return http.HttpResponse(result.getvalue(), \ content_type='application/pdf') return http.HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
def render(self, ar, output_file): context = { 'action': self, 'ar': ar, 'as_html_table': self.as_html_table, } extend_context(context) template = settings.SITE.plugins.jinja.renderer.jinja_env.get_template( self.template_name) html = template.render(**context).encode('utf-8') with open(output_file + '.html', "w") as file: file.write(html) result = io.StringIO() h = logging.FileHandler(output_file + '.log', 'w') pisa.log.addHandler(h) pdf = pisa.pisaDocument( io.StringIO(html), result, encoding='utf-8') pisa.log.removeHandler(h) h.close() with open(output_file, 'wb') as file: file.write(result.getvalue()) file.close() if pdf.err: raise Exception("pisa.pisaDocument.err is %r" % pdf.err)
def generate_pdf(template, request, contexte, extra_pdf_files=None): template = get_template(template) contexte.update({'MEDIA_ROOT': settings.MEDIA_ROOT, 'cdate': now(), 'user': request.user}) context = Context(contexte) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if extra_pdf_files: output = PdfFileWriter() append_pdf(PdfFileReader(result), output) result = StringIO.StringIO() for pdf_file in extra_pdf_files: append_pdf(PdfFileReader(pdf_file), output) output.write(result) if not pdf.err: return http.HttpResponse(result.getvalue(), mimetype='application/pdf') return http.HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
def generate_pdf(self): """ Renders an invoice into html template and transfers it to a pdf document Returns url of the generated pdf """ tmplt = get_template('invoice_template.html') context = Context({ 'pagesize': 'A4', 'invoice': self._invoice, 'numb': self._invoice.pk }) html = tmplt.render(context) save_to = os.path.join('invoices', strftime('%Y-%m')) save_path = os.path.join(settings.MEDIA_ROOT, save_to) if not os.path.exists(save_path): os.makedirs(save_path) buffer = open('%s/%s.pdf' % (save_path, self.get_filename_string()), 'wb') pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), buffer) buffer.close() return '%s/%s.pdf' % (save_to, self.get_filename_string())
def index(request): basic = BasicInformation.objects.all() if len(basic) != 1: raise Exception( 'Error: You must have exactly ONE BasicInformation object') basic = basic[0] degrees = Degree.objects.all().order_by('order') jobs = Job.objects.all().order_by('order') projects = Project.objects.all().order_by('order') skills = Skill.objects.all().order_by('order') extras = Extracurricular.objects.all().order_by('order') for job in jobs: job.dates = DateRange.objects.filter(job=job) for project in projects: project.dates = DateRange.objects.filter(project=project) for extra in extras: extra.dates = DateRange.objects.filter(extra=extra) pdf = False if request.method == "GET" and "pdf" in request.GET: pdf = True context = RequestContext(request, locals()) template = get_template("index.html") html = template.render(context) result = StringIO.StringIO() if pdf: pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) response = HttpResponse(mimetype="application/pdf") response['Content-Disposition'] = 'attachment; Resume.pdf' response.write(result.getvalue()) return response return render_to_response('index.html', locals())
def convert_to_pdf(self, response): html = response.content pdf = pisa.pisaDocument(src=StringIO.StringIO(html), encoding='utf8', link_callback=fetch_resources) if not pdf.err: response.content = pdf.dest.getvalue() response['Content-Disposition'] = 'attachment; filename=%s.pdf' % self.title.replace(' ', '_') return response
def generar_pdf(html): result = StringIO.StringIO() links = lambda uri,rel: os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, '')) pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-16")),result, link_callback=links) if not pdf.err: return HttpResponse(result.getvalue(),content_type='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html))
def render(self, name=None): if isinstance(self.object, dict): html = render_to_string( self.template, self.object) else: html = render_to_string( self.template, {'object': self.object}) result = StringIO() pdf = pisa.pisaDocument( StringIO(html.encode("UTF-8")), result, encoding="utf-8") if pdf.err: return HttpResponse('Erro ao gerar pdf') resp = HttpResponse(result.getvalue(), mimetype='application/pdf') if name: resp['Content-Disposition'] = ( 'attachment; filename=%s' % name) return resp
def generate_pdf_ticket(registration=None, context=None, encoding='utf-8'): import ho.pisa as pisa import cStringIO as StringIO from django.utils.six import BytesIO if not registration and not context: raise Http404(_("Invalid arguments")) if not context: d = ConfirmationEmailView.get_extra_context(registration) context = Context(d) template = loader.get_template('registration/ticket.html') html = template.render(context) if not registration: registration = context['r'] result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) result = result.getvalue() try: file = TemporaryFile() file.write(result) registration.ticket_file = File(file) registration.save() file.close() except Exception, e: charge = registration.charge if charge: charge.save_server_message(['Failed while saving ticket file'], exception=e)
def create_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) return pdf, result
def write_PDF(html): result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type = 'application/pdf') else: return HttpResponse("Error al generar el pdf: %s" % cgi.escape(html))
def __html_to_pdf(self, htmlstring, pdffile, cssstring=None, encoding='utf-8', debug=False): '''Converts an html string to pdf. inputs: htmlstring : string containing html to convert pdffile : file like object to write output to cssstring : string containing css to override default encoding : html encoding debug : debug flag Wrap call in try: finally: to close open file object returns pdf context object will raise some exceptions but must also check that pdfcontext.err == 0 ''' # must convert any <br></br> to just <br/> # then feed result to pisaDocument pisaHTMLString = htmlstring.replace('<br></br>', '<br/>') #logging.error( 'pisaHTMLString is %s' % type(pisaHTMLString)) # wrap string in file like StringIO pdfcontext = pisa.pisaDocument(cStringIO.StringIO(pisaHTMLString), dest=pdffile, debug=debug, default_css=cssstring, encoding=encoding) return pdfcontext
def unused_as_printable(obj,as_pdf=True,model=None): #~ if model is None: #~ tn = obj._meta.db_table + "_print.html" #~ else: #~ tn = model._meta.db_table + "_print.html" tplnames = [ obj._meta.db_table, "lino/page" ] tpls = [ x + "_printable.html" for x in tplnames ] template = select_template(tpls) context = dict( #report=self, instance=obj, title = unicode(obj), #title=u"%s - %s" % (self.get_title(),obj), #layout = layout ) html = template.render(Context(context)) if not as_pdf: return html html = html.encode("ISO-8859-1") #file('tmp.html','w').write(html) result = cStringIO.StringIO() pdf = pisa.pisaDocument(cStringIO.StringIO(html), result) if pdf.err: raise Exception("pisa.pisaDocument.err is %r" % pdf.err) return result.getvalue()
def write_to_pdf(template_src, context_dict, context_instance, filename): """ Returns a tuple (st, StringIO) st is a boolean that indicate if there was error during the creation of pdf """ html = render_to_string(template_src, context_dict, context_instance=context_instance) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) return (not pdf.err, result) template = get_template(template_src) context = Context(context_dict) html = template.render(context) # Changed from file to filename pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) result.close()
def render_2_pdf(template, variables, filename = "report.pdf", is_rendered_html=False): """ Pisa Documentation : http://www.xhtml2pdf.com/static/pisa-en.html http://www.xhtml2pdf.com """ if is_rendered_html : html = template else : template = get_template(template) html = template.render(Context(variables)) os.chdir(settings.ROOT_PATH) html = html.replace("\"/common/media", "\"common/media") html = html.replace("\"/budget/site_media", "\"budget/media") html = html.replace("\"/invoice/site_media", "\"invoice/media") html = html.replace("\"/partner/site_media", "\"partner/media") html = html.replace("\"/purchase/site_media", "\"purchase/media") result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result) if not pdf.err : response = HttpResponse(result.getvalue(), mimetype="application/pdf") response['Content-Disposition'] = 'attachment; filename=%s' %(filename) return response return HttpResponse(u'Хөрвүүлэлтийн явцад алдаа гарлаа! %s' %cgi.escape(html))
def generate_pdf(self, html): # Funcion para generar el archivo PDF y devolverlo mediante HttpResponse result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=self.fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html))
def generar_pdf(html): # Funcion para generar el archivo PDF y devolverlo mediante HttpResponse result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html))
def printer_school_report(request, school_list=None): """ Generate the school report for each school in the query set""" html = '' #Will hold rendered templates for assigned_school in school_list: student_list = SchoolStudent.objects.filter(school = assigned_school) grade_bucket = {8:[], 9:[], 10:[], 11:[], 12:[]} for igrade in range(8, 13): grade_bucket[igrade].extend(student_list.filter(grade=igrade).order_by('reference')) responsible_teacher = ResponsibleTeacher.objects.filter(school = assigned_school) timestamp = str(datetime.datetime.now().strftime('%d %B %Y at %H:%M')) gold_count = student_list.filter(award='G').count() merit_count = student_list.filter(award='M').count() merit_count = merit_count + student_list.filter(award='MOX').count() school_award = student_list.filter(award='OX') | student_list.filter(award='MOX') school_award_blurb = 'Congratulations! %s has received '%(unicode(assigned_school)) if merit_count > 0 or gold_count > 0: if gold_count > 0: school_award_blurb+='%d Gold award%s'%(gold_count, 's' if gold_count>1 else '') if school_award.count() > 0: school_award_blurb+='an Oxford Prize for %s %s' % (school_award[0].firstname, school_award[0].surname) if (gold_count > 0 or school_award.count() > 0) and merit_count > 0: school_award_blurb+=' and ' if merit_count > 0: school_award_blurb+='%d Merit award%s'%(merit_count, 's' if merit_count>1 else '') else: school_award_blurb = '' year = str(datetime.datetime.now().strftime('%Y')) if responsible_teacher: c = {'type':'Students', 'timestamp':timestamp, 'schooln':assigned_school, 'responsible_teacher':responsible_teacher[0], 'student_list':grade_bucket, 'entries_open':isOpen(), 'school_award_blurb':school_award_blurb, 'grade_range':range(8,13), 'year':year} #Render the template with the context (from above) template = get_template('school_report.html') c.update(csrf(request)) context = Context(c) html += template.render(context) #Concatenate each rendered template to the html "string" result = StringIO.StringIO() #Generate the pdf doc pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return result else: pass #Error handling?
def generar_pdf(html, filename): """ Recibe un template html y el nombre del archivo pdf a crear, se resuelve la ruta donde se alojara el archivo pdf y se procede a la creacion del mismo a partir del template creado de la funcion llamadora. @type html: html. @param request: Contiene el formato y los datos del informe, el cual, posteriormente se convertira en pdf. @type filename: string. @param filename: Contiene el nombre del archivo pdf a crear. @rtype: PDF. @return: linea_base_numero.html, donde se encuentra el informe de linea base. @author: Marcelo Denis. """ STATICFILES_DIRS, = settings.STATICFILES_DIRS path = '%s/aplicaciones/informes/%s' % (STATICFILES_DIRS, filename) result = open(path, 'wb') pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) result.close() if not pdf.err: return HttpResponseRedirect('/static/aplicaciones/informes/%s' % filename) return HttpResponse('Error al generar el informe PDF: %s' % cgi.escape(html))
def build(self, ar, action, elem): if six.PY2: import ho.pisa as pisa else: from xhtml2pdf import pisa # pisa.showLogging() tpl = self.get_template(action, elem) filename = action.before_build(self, elem) if filename is None: return #~ html = self.render_template(elem,tpl,request=ar.request) html = self.render_template(elem, tpl, ar=ar) html = html.encode("utf-8") open(filename + '.html', 'w').write(html) result = io.BytesIO() h = logging.FileHandler(filename + '.log', 'w') pisa.log.addHandler(h) pdf = pisa.pisaDocument( io.BytesIO(html), result, encoding='utf-8') pisa.log.removeHandler(h) h.close() fd = open(filename, 'wb') fd.write(result.getvalue()) fd.close() if pdf.err: raise Exception("pisa.pisaDocument.err is %r" % pdf.err) return os.path.getmtime(filename)
def send(request): username = "******" print username message = "hi" subject = "Confirmation mail" from_email = '*****@*****.**' m_id = request.POST.get("m3") n_id = request.POST.get("n3") q_id = request.POST.get("q2") u_id = request.POST.get("u2") y_id = request.POST.get("y12") p_id = request.POST.get("p2") j_id = request.POST.get("j1") e_id = request.POST.get("e1") i_id = request.POST.get("i1") f_id = request.POST.get("f1") k_id = request.POST.get("k1") print k_id print request to = [m_id] message = get_template('/home/ss/Desktop/Resume/res/res1/templates/sample1.html').render( Context({'fullname': n_id,'mailing':m_id,'qua': q_id,'univ':u_id,'year':y_id,'perc':p_id,'job':j_id,'exp':e_id,'ind':i_id,'func':f_id,'key':k_id})) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(message), result) try: mail = EmailMessage(subject,message,from_email,to) attachment = myview(request) mail.attach('p1.pdf',result.getvalue(),'application/pdf') mail.send() return render(request,'sample.html',{'mail':m_id,'name':n_id,'qua':q_id,'univ':u_id,'year':y_id,'perc':p_id,'job':j_id,'exp':e_id,'ind':i_id,'func':f_id,'key':k_id}) except BadHeaderError: return HttpResponse('Invalid header found.')
def render_to_pdf(output, template, context, request=None): response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = ('attachment; filename=%s' % output) t = loader.get_template(template) if request: c = RequestContext(request, context) else: c = Context(context) html = t.render(c) result = StringIO.StringIO() pdf = pisa.pisaDocument( StringIO.StringIO( html.encode("UTF-8")), result, link_callback=fetch_resources) if not pdf.err: response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = ('attachment; filename=%s' % output) response.write(result.getvalue()) return response return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
def helloWorld(): filename = __file__ + ".pdf" datauri = pisa.makeDataURIFromFile('img/denker.png') bguri = os.path.normpath( os.path.join(os.path.abspath(__file__), os.pardir, "pdf/background-sample.pdf")) bguri = pisa.makeDataURIFromFile(bguri) html = """ <style> @page { background: url("%s"); @frame text { top: 6cm; left: 4cm; right: 4cm; bottom: 4cm; -pdf-frame-border: 1; } } </style> <p> Hello <strong>World</strong> <p> <img src="%s"> """ % (bguri, datauri) pdf = pisa.pisaDocument(html, open(filename, "wb"), path=__file__) if not pdf.err: pisa.startViewer(filename)
def generar_pdf(html): result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype="application/pdf") return HttpResponse("Error al generar el PDF: %s" % cgi.escape(html))
def create_pdf(template_file, pdf_args, o): import ho.pisa as pisa import cStringIO as StringIO import cgi from django.template.loader import get_template from utils import get_rand_str, get_abs_attach_fname """ 在对象单一显示时,输出PDF文件。 参数从o 的属性中取出。 """ def get_pdf_context(o): def get_val(o, k): if type(k) == list: for key in k: try: o = getattr(o, key) if callable(o): o = o() except: o = "" break else: o = k return o context = {} for i, j in pdf_args.items(): context[i] = get_val(o, j) randstr = get_rand_str(10) context['randstr'] = randstr return context context = get_pdf_context(o) template = get_template(template_file) str = template.name[-9:-5] context = Context(context) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result, encoding='utf-8') if str == 'pdf1': fn = o.bmbh + "-certificate" else: fn = o.bmbh + "-registration" fname = get_abs_attach_fname('/pdf/' + fn) f = open(fname, 'wb') testf = result.getvalue() f.write(testf) f.close() if not pdf.err: response = HttpResponse(testf, mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % (fn) return response return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
def HTML2PDF( data, filename ): result = StringIO.StringIO() pdf = pisa.pisaDocument( StringIO.StringIO( data.encode( 'UTF-8' ) ), result, encoding = "UTF-8" ) f = open( filename, 'wb' ) f.write( result.getvalue() ) f.close() return pdf.err
def generar_pdf(html): result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html)) ##################################-Para PDF-##################################
def build(self, ar, action, elem): if six.PY2: import ho.pisa as pisa else: from xhtml2pdf import pisa # pisa.showLogging() tpl = self.get_template(action, elem) filename = action.before_build(self, elem) if filename is None: return #~ html = self.render_template(elem,tpl,request=ar.request) html = self.render_template(elem, tpl, ar=ar) html = html.encode("utf-8") open(filename + '.html', 'w').write(html) result = io.BytesIO() h = logging.FileHandler(filename + '.log', 'w') pisa.log.addHandler(h) pdf = pisa.pisaDocument(io.BytesIO(html), result, encoding='utf-8') pisa.log.removeHandler(h) h.close() fd = open(filename, 'wb') fd.write(result.getvalue()) fd.close() if pdf.err: raise Exception("pisa.pisaDocument.err is %r" % pdf.err) return os.path.getmtime(filename)
def render_pdf(html, request): path = get_full_path_x(request) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html), result, link_callback=path) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse(_(u'Error al generar el PDF: %s') % cgi.escape(html)) ''' if human.id: user = user( form.name, form.email, "password" ) return HttpResponseRedirect('anonymous/Welcome/ic_membership/', args=(human.id,)) # Save the new category to the database. form.save(commit=True) # Now call the index() view. # The user will be shown the homepage. pass return index(request) switch case human: case person: reverse = 'General:Public_PersonAdmin' case company: reverse = 'General:Public_CompanyAdmin' case project: reverse = 'General:Public_ProjectAdmin' ''' '''
def generate_pdf_ticket(registration=None, context=None, encoding='utf-8'): import ho.pisa as pisa import cStringIO as StringIO from django.utils.six import BytesIO if not registration and not context: raise Http404(_("Invalid arguments")) if not context: d = ConfirmationEmailView.get_extra_context(registration) context = Context(d) template = loader.get_template('registration/ticket.html') html = template.render(context) if not registration: registration = context['r'] result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) result = result.getvalue() try: file = TemporaryFile() file.write(result) registration.ticket_file = File(file) registration.save() file.close() except Exception, e: charge = registration.charge if charge: charge.save_server_message( ['Failed while saving ticket file'], exception=e)
def __html_to_pdf(self, htmlstring, pdffile, cssstring=None, encoding='utf-8', debug=False): '''Converts an html string to pdf. inputs: htmlstring : string containing html to convert pdffile : file like object to write output to cssstring : string containing css to override default encoding : html encoding debug : debug flag Wrap call in try: finally: to close open file object returns pdf context object will raise some exceptions but must also check that pdfcontext.err == 0 ''' # must convert any <br></br> to just <br/> # then feed result to pisaDocument pisaHTMLString = htmlstring.replace('<br></br>', '<br/>') #logging.error( 'pisaHTMLString is %s' % type(pisaHTMLString)) # wrap string in file like StringIO pdfcontext = pisa.pisaDocument(cStringIO.StringIO(pisaHTMLString), dest=pdffile, debug=debug, default_css=cssstring, encoding=encoding ) return pdfcontext
def to_pdf(self, user, response): css_file = open("%s%s" % (settings.MEDIA_ROOT, "/css/pisa.css"), 'r') css = css_file.read() substitution_map = Contract.get_substitution_map() substitution_map[ugettext('customer')] = unicode(self.customer) substitution_map[ugettext('customer_legal_form')] = self.customer.legal_form substitution_map[ugettext('customer_street')] = self.customer.address.street substitution_map[ugettext('customer_zipcode')] = self.customer.address.zipcode substitution_map[ugettext('customer_city')] = self.customer.address.city substitution_map[ugettext('customer_country')] = unicode(self.customer.address.country) substitution_map[ugettext('customer_company_id')] = self.customer.company_id substitution_map[ugettext('customer_representative')] = self.customer.representative substitution_map[ugettext('customer_representative_function')] = self.customer.representative_function substitution_map[ugettext('firstname')] = user.first_name substitution_map[ugettext('lastname')] = user.last_name substitution_map[ugettext('street')] = user.get_profile().address.street substitution_map[ugettext('zipcode')] = user.get_profile().address.zipcode substitution_map[ugettext('city')] = user.get_profile().address.city substitution_map[ugettext('country')] = unicode(user.get_profile().address.country) substitution_map[ugettext('company_id')] = user.get_profile().company_id contract_content = "<h1>%s</h1>%s" % (self.title, self.content.replace(' ', ' ')) for tag, value in substitution_map.items(): contract_content = contract_content.replace('{{ %s }}' % (tag), value) pdf = pisa.pisaDocument(to_html(contract_content), response, default_css=css) return response
def render_to_pdf(request, template, data): html = jingo.render(request, template, data) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.content), result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html.content))
def generar_pdf(html): result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html))
def write_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-16")), result) if not pdf.err: return http.HttpResponse(result.getvalue(), content_type='application/pdf') return http.HttpResponse('Ocurrio un error al generar el reporte %s' % cgi.escape(html))
def html2pdf(html): try: inp=StringIO.StringIO(html) out=StringIO.StringIO() res=pisa.pisaDocument(inp,out) pdf=out.getvalue() return pdf except Exception,e: raise Exception("Failed to create PDF file: %s"%str(e))
def _generate_pdf(template, context): translation.activate(settings.LANGUAGE_CODE) context['MEDIA_ROOT'] = settings.MEDIA_ROOT context['MEDIA_URL'] = settings.MEDIA_URL context['is_pdf'] = True html = render_to_string(template, context) buf = StringIO() pdf = pisa.pisaDocument(StringIO(html.encode('utf-8')), buf, link_callback=_fetch_resources, path=settings.MEDIA_ROOT) return buf, pdf
def generar_pdf(html): result = StringIO.StringIO() links = lambda uri, rel: os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, '')) pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-16")), dest=result, link_callback=fetch_resources) #pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, link_callback=links) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html))
def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) if not pdf.err: return http.HttpResponse(result.getvalue(), mimetype='application/pdf') return http.HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
def write_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: return http.HttpResponse(result.getvalue(), mimetype='application/pdf') return http.HttpResponse('Gremlin\'s ate your pdf! %s' % cgi.escape(html))
def render_to_pdf(template_name, context_dict): template = get_template(template_name) context_dict.update({'MEDIA_URL': settings.MEDIA_URL}) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, link_callback=fetch_resources) return result.getvalue()
def generar_pdf(html): # Funcion para generar el archivo PDF y devolverlo mediante HttpResponse #html = render_to_string('cdr/cdr.html', {'formulario':formulario.as_p(), 'lista_registros':lista_con_formato, 'msg' : men, 'hay_fecha_ini':hay_fecha_ini }, context_instance=RequestContext(request)) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result) #pdf = pisa.pisaDocument(StringIO.StringIO(html), result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('Error al generar el PDF: %s' % cgi.escape(html))
def render_to_pdf(request, template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('We had some errors<pre>{}</pre>'.format(escape(html)))
def _generate_pdf(html): #Function for generating the PDF file and return it using HttpResponse result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse( _('Error while creating the PDF file: %s' % cgi.escape(html)))
def write_pdf(template_src, context_dict, filename='output.pdf'): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: response = HttpResponse(result.getvalue(), mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response return http.HttpResponse('Erro making pdf! %s' % cgi.escape(html))