def tree_equation_id_pdf(request, id): tree_equation = TreeEquation.objects.get(ID=id) template = get_template('data/template.tree_equation.pdf.html') html = template.render(Context({ 'tree_equation': tree_equation })) def fetch_resources(uri, rel): path = 'ERROR' if uri[0:6] == 'static': path = settings.STATIC_ROOT + uri[6:] elif uri[0:5] == 'media': path = settings.MEDIA_ROOT + uri[5:] print uri, path return path buffer = StringIO.StringIO() pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), buffer, link_callback=fetch_resources) pdf = buffer.getvalue() buffer.close() # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=TreeEquation_%s.pdf' % tree_equation.ID response.write(pdf) return response
def record_by_id_pdf_view(request, id, model_class, record_content_template, record_title, record_url): record = model_class.objects.get(pk=id) template = get_template('base/template.record.pdf.html') html = template.render(Context({ 'record': record.serialize(request=request), 'record_content_template': record_content_template, 'record_title': record_title, 'record_url': record_url, 'is_pdf': True })) def fetch_resources(uri, rel): path = 'ERROR' if uri[0:7] == '/static': path = os.path.join(settings.PROJECT_PATH, 'templates', 'static') + uri[7:] return path result = StringIO.StringIO() pisa.pisaDocument( StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8',link_callback=fetch_resources) pdf = result.getvalue() result.close() # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % record_title.lower().replace(' ', '_') response.write(pdf) return response
def defaultview(): """ serving landing page index.html """ if request.method == "POST": #in case of report generation dict = json.loads(request.form['data']) if request.form['type'] == "pdf": #Generate PDF html = flask.render_template('report.html', content=dict) result = StringIO.StringIO() pisa.pisaDocument(StringIO.StringIO(html), result) result.seek(0) download_filename = "reports.pdf" response = flask.current_app.response_class(result, mimetype='application/pdf') response.headers.add('Content-Disposition', 'attachment', filename=download_filename) return response else: #Generate XML xml = dicttoxml.dicttoxml(dict) download_filename='reports.xml' response = flask.current_app.response_class(xml, mimetype='application/pdf') response.headers.add('Content-Disposition', 'attachment', filename=download_filename) return response else: #Serve index.html return flask.render_template('index.html')
def write_img_to_pdf (src, dest): # Helper xhtml2pdf function to dump image/template to pdf context = dict(img_path = src) template = get_template('tracker/pdf_img_template.html') html = template.render(Context(context)) with open(dest, 'wb') as f: pisa.pisaDocument(cStringIO.StringIO( html.encode('UTF-8')), f )
def buffer_pdf(html): """ Return a cstringio datas containing a pdf """ result = StringIO.StringIO() pisa.pisaDocument(html, result, link_callback=fetch_resource, encoding='utf-8', html_encoding="utf-8") return result
def generate(self, header, data, output_stream): def fetch_resources(uri, rel): urls = {settings.MEDIA_ROOT: settings.MEDIA_URL, settings.STATICFILES_ROOT: settings.STATIC_URL} for k, v in urls.items(): if (uri.startswith(v)): return os.path.join(k, uri.replace(v, "")) return '' pisa.pisaDocument( force_text(render_template(self.template_name, {'pagesize': 'A4', 'headers': header, 'data': data})), output_stream, encoding=self.encoding, link_callback=fetch_resources )
def download_merged_pdf(obj, files): """ Returns a HTTPResponse that contains all PDF files merged into a single PDF file. """ warnings.simplefilter('ignore', DeprecationWarning) filename = u"%s_%s_%s_files.pdf" % (obj.type, obj.reference, obj.revision) output = StreamedPdfFileWriter() # generate a summary ctx = { "obj" : obj, "files" : files, "state_histories" : get_state_histories(obj), } template = get_template("summary.xhtml") html = template.render(Context(ctx)) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-16")), result) result.seek(0) inp = PdfFileReader(result) for page in inp.pages: output.addPage(page) # append all pdfs for pdf_file in files: inp = PdfFileReader(file(pdf_file.file.path, "rb")) for page in inp.pages: output.addPage(page) response = http.StreamingHttpResponse(output, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"' % filename warnings.simplefilter('default', DeprecationWarning) return response
def factura_pdf(html): reporventa = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF:8")), reporventa) if not pdf.err: return HttpResponse(reporventa.getvalue(), mimetype='application/pdf') return HttpResponse("Error en generar el pdf")
def save_pdf(pdf_data,file,diagnoseId,fileName,identityPhone): default.DEFAULT_FONT["helvetica"]="msyh" fontFile = os.path.join( constant.DirConstant.ROOT_DIR+ '/DoctorSpring/static/font', 'msyh.ttf') pdfmetrics.registerFont(TTFont('msyh',fontFile)) # from xhtml2pdf.pisa.sx.pisa3 import pisa_default pdf = pisa.pisaDocument(StringIO( pdf_data.encode("UTF-8")), file,encoding='utf-8') file.close() output = PdfFileWriter() with open(fileName, "rb") as f1: input1 = PdfFileReader(f1) for i in range(input1.getNumPages()): output.addPage(input1.getPage(i)) #print(identityPhone) password = str(int(identityPhone)) owner_pwd = ''.join(random.choice(string.letters + string.digits) for _ in range(64)) #print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + owner_pwd) output.encrypt(password, owner_pwd) output.write(open("temp.pdf", "wb")) os.remove(fileName) os.rename("temp.pdf", fileName) fileUrl=upload_pdf(fileName,diagnoseId) return fileUrl
def transform_to_pdf(response, pdfname, return_stringIO=False): """ call xhtml2pdf.pisa to convert html responce to pdf """ # response['mimetype'] = 'application/pdf' # TODO : on the fly filename from url # response['Content-Disposition'] = 'attachment; filename=%s.pdf' % pdfname content = response.content if not return_stringIO: new_response = HttpResponse(content="", mimetype="application/pdf") new_response["Content-Disposition"] = "attachment; filename=%s.pdf" % pdfname else: new_response = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(content), new_response, link_callback=fetch_resources) if not pdf.err: if return_stringIO: pdf = new_response.getvalue() new_response.close() return pdf else: return new_response else: # TODO return error and redirect to default view return HttpResponse( "We had some errors in pdfMiddleWare : \ <br/><pre>%s</pre>" % pdf )
def create_pdf_body(self): from apps.mail.models import Attachment from xhtml2pdf import pisa import os try: #ghetto tmp file for pdf creation, will this work on HEROKU? I think so but could be slow... if not os.path.exists('tmp'): os.makedirs('tmp') #TODO: need default attachment attachment = None html = self.free_edit_body fname = 'tmp/request_%s_tmp.pdf' % self.id with open(fname, 'wb') as f: doc = pisa.pisaDocument(html, f) if not doc.err: with open(fname, 'rb') as f: to_file = ContentFile(f.read()) attachment = Attachment() attachment.user = self.author attachment.file.save('request_%s.pdf' % self.id, to_file) attachment.save() os.remove(fname) else: logger.error("error writing to PDF: %s" % doc.err) self.printed = attachment self.save() return attachment.url except Exception as e: logger.exception(e) return None
def generar_pdf(html): # Función 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 export_pdf(self, request, pk): group = get_object_or_404(Group, pk=pk) attrs = {'group__pk': pk} if request.GET.get('finished', '0') == '1': attrs['enroll_finished'] = True elif request.GET.get('finished', '0') == '2': attrs['enroll_finished'] = False if request.GET.get('activate', '0') == '1': attrs['enroll_activate'] = True elif request.GET.get('activate', '0') == '2': attrs['enroll_activate'] = False student_list = Enroll.objects.filter(**attrs) template = get_template('Pdf/student_list.html') html = template.render(Context({'student_list': student_list, 'group': group})) result = io.StringIO() pdf = pisa.pisaDocument(io.StringIO(html), result) if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="student_list_%s.pdf"' % (group.name) return response return HttpResponse("Error " + str(pdf.err) + " " + html)
def render_pdf(html): # Function to generate the pdf document and return it throught 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 when generating the pdf: %s' % cgi.escape(html))
def dm_monthly(request, year, month): html = render_to_string('download.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request)) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources ) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
def handle_noargs(self, **options): print "Testing" person_list = Person.objects.all() # person_list = person_list.filter(status='ok_all') person_list = person_list.filter(date_modified__gt=datetime.today() - timedelta(days=3)) translation.activate('es') avui = _date(datetime.now(), "d \d\e F \d\e Y") for person in person_list: for course in person.courses.all(): context = { 'object' : person, 'course' : course, 'avui' : avui } output_filename = 'generated_files/fitxaMEC/%s_ficha_participantes_%s.pdf' % (course.code, person.slug) if not os.path.isfile(output_filename): html = render_to_string('contacts/person/ficha_participantes_mec.html',context) result = file(output_filename,'wb') pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources) result.close() print "%s generated" % output_filename if pdf.err: raise Exception('Error generating pdf. %d errors' % pdf.err )
def html_to_pdf(content, encoding="utf-8", link_callback=fetch_resources, **kwargs): """ Converts html ``content`` into PDF document. :param unicode content: html content :returns: PDF content :rtype: :class:`bytes` :raises: :exc:`~easy_pdf.exceptions.PDFRenderingError` """ src = BytesIO(content.encode(encoding)) dest = BytesIO() #result = open("/home/midas/Documentos/appem/infa_web/static/report.pdf", 'wb') # Changed from file to filename result = open(os.path.join(settings.MEDIA_ROOT, kwargs["filename_to_save"]), 'w') # Changed from file to filename pdf = pisa.pisaDocument(src, result, encoding=encoding, link_callback=link_callback, **kwargs) #pdf = pisa.pisaDocument(src, dest, encoding=encoding, link_callback=link_callback, **kwargs) if pdf.err: logger.error("Error rendering PDF document") for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_ERROR: logger_x2p.error("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3]) raise PDFRenderingError("Errors rendering PDF", content=content, log=pdf.log) if pdf.warn: for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_WARNING: logger_x2p.warning("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3]) print (".................................") result = open(os.path.join(settings.MEDIA_ROOT, kwargs["filename_to_save"]), 'r') # Changed from file to filename return result
def create_page(self, page): data = StringIO.StringIO(page.encode('utf-8')) temp = StringIO.StringIO() pdf = pisa.pisaDocument(data, temp) self.pdf_base.addDocument(pdf)
def _generatePDF(write_file=False, title="Latest CCOL Events", school_id="", grade="", subject=""): events = Event.objects.all().order_by('-start_date')[:4] context_dict = {'events':events, 'title':title} template = get_template("flyer_pdf.html") context = Context(context_dict) html = template.render(context) result = StringIO() pdf = pisa.pisaDocument(StringIO( "{0}".format(html) ), result) if not pdf.err: if write_file: tempFileName = settings.MEDIA_ROOT+"/"+title.replace(" ","")+".pdf" tempFile = open(tempFileName, 'wb+') tempFile.write(result.getvalue()) tempFile.close() return tempFileName else: return HttpResponse(result.getvalue(), content_type='application/pdf') if write_file: return None return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
def generar_pdf_view(request,pk): canino = Canino.objects.filter(id = int(pk)) serovares = Serovar.objects.all() result = StringIO() template = get_template("home/reporte.html") BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath('images/facultad.jpg'))) BASE_DIR += '/vete/static/images/' facultad_image = BASE_DIR + 'facultad.jpg' unlp_image = BASE_DIR + 'unlp.jpg' punta_indio_image = BASE_DIR + 'punta_indio.jpg' data = { 'pagesize':'A4', 'title':'Reporte', 'canino':canino[0], 'facultad_image':facultad_image, 'unlp_image':unlp_image, 'punta_indio_image':punta_indio_image, 'serovares':serovares, } context = Context(data) html = template.render(context) pdf = pisa.pisaDocument(StringIO( "{0}".format(html.encode('ascii','ignore')) ), result) if not pdf.err: return http.HttpResponse( result.getvalue(), content_type='application/pdf') return http.HttpResponse('We had some errors')
def html_to_pdf(content, encoding="utf-8", link_callback=fetch_resources, **kwargs): """ Converts html ``content`` into PDF document. :param unicode content: html content :returns: PDF content :rtype: :class:`bytes` :raises: :exc:`~easy_pdf.exceptions.PDFRenderingError` """ src = BytesIO(content.encode(encoding)) dest = BytesIO() pdf = pisa.pisaDocument(src, dest, encoding=encoding, link_callback=link_callback, **kwargs) if pdf.err: logger.error("Error rendering PDF document") for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_ERROR: logger_x2p.error("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3]) raise PDFRenderingError("Errors rendering PDF", content=content, log=pdf.log) if pdf.warn: for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_WARNING: logger_x2p.warning("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3]) return dest.getvalue()
def _create_pdf(self): # Dati di esempio #order = self.resource.order xres = self.resource #querySet = self._get_resource_list(self.request).distinct() querySet, nSup, nProducts, nPacts = self._get_pdfrecords_pacts(self._get_resource_list(self.request).order_by('name')) context_dict = { 'order' : xres, 'recSup' : querySet, 'Suppliers_count' : nSup, 'pacts_count' : nPacts, 'products_count' : nProducts, 'user' : self.request.user, } REPORT_TEMPLATE = "blocks/%s/report.html" % self.BLOCK_NAME template = get_template(REPORT_TEMPLATE) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() #DOMTHU: <th title='TOT account'>€</th> #pdf = pisa.pisaDocument(StringIO.StringIO(html), result) pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1", "ignore")), result) #pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8", "ignore")), result ) #, link_callback = fetch_resources ) if not pdf.err: response = HttpResponse(result.getvalue(), mimetype='application/pdf') response['Content-Disposition'] = "attachment; filename=Suppliers.pdf" return response return self.response_error(_('We had some errors<pre>%s</pre>') % cgi.escape(html))
def pdf(self): """ Converts html to pdf and returns the char stream """ result = StringIO() # h3 and down shouldn't make chapters html = self.html.encode("UTF-8") html = html.replace('<h3>', '<h3 class="not_outline">') html = html.replace('<h4>', '<h4 class="not_outline">') html = html.replace('<h5>', '<h5 class="not_outline">') html = html.replace('<h6>', '<h6 class="not_outline">') # add page breaks before each h2 html = html.replace('<h2>', '<h2 class="break">') # generate the pdf pisa.pisaDocument(StringIO(html), result) return result.getvalue()
def render_pdf(html, request): result = StringIO.StringIO() #pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result, link_callback=_fix_pdf_links) try: pdf = pisa.pisaDocument(StringIO.StringIO(html), result, link_callback=_fix_pdf_links) except: try: pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result, link_callback=_fix_pdf_links) except: try: pdf = pisa.pisaDocument(StringIO.StringIO(html.decode("utf-8")), result, link_callback=_fix_pdf_links) except Exception as e: pdf = pisa.pisaDocument(StringIO.StringIO("Cannot render pdf %s" % (e.message())), result, link_callback=_fix_pdf_links) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse(_(u'Error al generar el PDF: %s') % cgi.escape(html))
def render_to_pdf(template_src, context_dict, **kwargs): """ Renders html template to PDF. Returns a response of MIME type 'application/pdf' """ context_instanse= kwargs.get('context', None) context_dict.update({'download': True}) result= StringIO.StringIO() try: html= render_to_string(template_src, context_dict, context_instanse) pdf= pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding="utf8") except xhtml2pdf.w3c.cssParser.CSSParseError: html= render_to_string(template_src, context_dict, None) pdf= pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding="utf8") return pdf, result
def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None
def write_pdf(template_src, context_dict, filename): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = open(filename, 'wb') # Changed from file to filename pdf = pisa.pisaDocument(StringIO.StringIO( html.encode("UTF-8")), result) result.close()
def PDF_HTTP_Response(sourceHtml, filename): result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(sourceHtml.encode("UTF-8")), result) response = HttpResponse(result.getvalue(), mimetype='application/pdf') response['Content-Disposition'] = 'filename=' + filename if not pdf.err: return response return HttpResponse('We had some errors<pre>%s</pre>' % 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("UTF-8")), result) if not pdf.err: return http.HttpResponse(result.getvalue(), content_type='application/pdf') return http.HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
def render_to_response(self, context, **response_kwargs): template = get_template(self.template_name) html = template.render(RequestContext(self.request, context)) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def get(self, request, *args, **kwargs): try: template = get_template('datemedical/admin/ticket.html') context = { 'comp': Mainpage.objects.first(), 'datemedical': DateMedical.objects.get(pk=self.kwargs['pk']) } html = template.render(context) result = BytesIO() links = lambda uri, rel: os.path.join( settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') except Exception as e: print(e) return HttpResponseRedirect(self.success_url)
def export_pdf(resume, resume_func, resume_func_kwargs=None): """ Export resume as PDF. :param resume: Resume to export :type resume: :class:`curriculum.models.Resume` :param resume_func: Function for create resume as :mod:`xhtml2pdf` format :type resume_func: function :param resume_func_kwargs: Keyword argument for ``resume_func`` :type resume_func_kwargs: dict :returns: Raw PDF """ resume_func_kwargs = resume_func_kwargs or {} html = resume_func(resume, **resume_func_kwargs) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), dest=result, encoding='UTF-8', link_callback=fetch_resources) return pdf, result
def render_to_pdf(template_src, context_dict={}): dot_data = StringIO() template = get_template(template_src) html = template.render(context_dict) result = BytesIO() links = lambda uri, rel: os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, '')) #pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=links) pdf = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), dest=result, link_callback=links) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None if url.startswith("http"): image = io.BytesIO(urllib.urlopen(url).read()) return 'data:image/png;base64,' + base64.b64encode(image.read()) return url
def render_to_pdf(request, template_src, context_dict): template = get_template(template_src) context = Context(context_dict) #html = template.render(context) context_instance = RequestContext(request) html = loader.render_to_string(template_src, context_dict, context_instance=context_instance) html = includeCss(html) result = StringIO.StringIO() #pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def render_pdf2(request): path = "orm/resume2.html" context = { 'internship': request.session['internshipinfo'], 'personal': request.session['personalinfo'], 'education': request.session['educationinfo'], 'certificate': request.session['certificateinfo'], 'tech': request.session['technicalinfo'], 'project': request.session['projectinfo'] } html = render_to_string('orm/resume2.html', context) io_bytes = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), io_bytes) if not pdf.err: return HttpResponse(io_bytes.getvalue(), content_type='application/pdf') else: return HttpResponse("Error while rendering PDF", status=400)
def html2pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() filename = 'somefilename.pdf' print "render" pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result, filename) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') #CON ESTE CODIGO SE CAMBIA EL ARCHVIO DEL PDF DESCARGADO AUTOMATICAMENTE, PERO SE PIERDE EL PDF PREVIEW. """response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=Client_Summary.pdf' return response""" return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def summary_cover(data, is_group=False, out_file=None): import codecs import StringIO from xhtml2pdf import pisa # open output file for writing (truncated binary) result = open(out_file, "w+b") html_file = 'cover_group.html' if is_group else 'cover_subj.html' html_dir = op.abspath(op.join(op.dirname(__file__), 'html', html_file)) with codecs.open(html_dir, mode='r', encoding='utf-8') as f: html = f.read() # convert HTML to PDF status = pisa.pisaDocument(html % data, result, encoding='UTF-8') result.close() # return True on success and False on errors return status.err
def getpdfPage(request): try: orderId = request.GET['orderId'] orderList = Order.objects.get(pk=orderId) today = date.today() data = {'orderList': orderList, 'today': today} template = get_template("user/pdf_page.html") data_p = template.render(data) response = BytesIO() pdfPage = pisa.pisaDocument(BytesIO(data_p.encode("UTF-8")), response) if not pdfPage.err: print(">>>>>>>>>>>>>>>>>>>>>>", orderList) return HttpResponse(response.getvalue(), content_type="application/pdf") else: return HttpResponse("Error Generating PDF") except Exception as e: print(e)
def investigationsreport(request, patient_pk): template_path = 'pdfs/investigationsreport.html' patient = get_object_or_404(Patient, pk=patient_pk) investigation = None usg = None ttdose = None investigationdata = Investigation.objects.all().filter( patient=patient).first() usgdata = Usg.objects.all().filter(patient=patient).first() ttdosedata = TtDose.objects.all().filter(patient=patient).first() if investigationdata: investigation = investigationdata if usgdata: usg = usgdata if ttdosedata: ttdose = ttdosedata context = { 'patient': patient, 'investigation': investigation, 'usg': usg, 'ttdose': ttdose } # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # To download the PDF # response['Content-Disposition'] = 'attachment; filename="report.pdf"' # To only display PDF response['Content-Disposition'] = 'filename="investigations.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) result = io.BytesIO() pdf = pisa.pisaDocument(io.BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return
def render_to_pdf(template, context={}): """ method: render_to_pdf(template, context) This method is based on xhtml2pdf package. This method returns a pdf from a supplied html document. :Input params: template -> The html template that has to be rendered as PDF. context -> Dictionary that contains the elements that has to be rendered inside the template. Default is empty dictionary :return: HttpResonse of the converted pdf """ template = get_template(template) html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(html, result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None
def render_to_pdf(template_src, context_dict): """ Permet la génération d'un pdf en construisant un template grâce à un dictionnaire des données nécessaires à sa création. :param template_src: le template a construire en pdf :type template_src: template :param context_dict: les données utile à la construction du template :type context_dict: dict :return: le fichier pdf ou reponse d'erreur :rtype: HttpResponse """ template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def liste_eleve_pdf(request): eleve=get_object_or_404(Eleve,id=10) response=HttpResponse(content_type="application/pdf") response["content-Disposition"]="attachement ;"\ "filename=%$_%$.pdf" %( eleve.nom, eleve.prenom ) html=render_to_string("registration/eleve/eleve_pdf.html",{ "eleve":eleve, "MEDIA_ROOT":settings.MEDIA_ROOT, "STATIC_ROOT": settings.STATIC_ROOT, }) pdf=pisa.pisaDocument( StringIO(html.encode("UTF-8")), response, encoding="UTF-8", ) return response
def _generate_pdf(cls, course): from io import BytesIO from xhtml2pdf import pisa from django.http import HttpResponse from django.template.loader import render_to_string risposte = SurveyResult.objects.filter(course=course) html = render_to_string('pdf_questionario.html', { 'risposte': risposte, }).encode('utf-8') result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html), result, encoding='UTF-8') converted = result.getvalue() if not pdf.err else '' filename = 'Questionario-di-gradimento.pdf' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s' % filename response.write(converted) return response
def render_to_pdf(template_src, context_dict, to): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) email = EmailMessage( 'Daily Parking History', 'The attached pdf contains the detial', '*****@*****.**', [ to, ], reply_to=['*****@*****.**'], headers={'Message-ID': 'foo'}, ) if not pdf.err: email.attach('my_pdf.pdf', result.getvalue(), 'application/pdf') email.content_subtype = "html" email.send() return redirect("/") return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def generate_form_pdf(request, uuid): try: project = Project.objects.get(uuid=uuid) if request.method == "POST": if 'content' not in request.POST: raise Exception("Content is missing") html = str(request.POST['content']) result_file = open('/static/' + str(uuid) + '.pdf', "w+b") pisa_status = pisa.pisaDocument( BytesIO(html.encode("UTF-8")), # the HTML to convert dest=result_file) # file handle to recieve result return JsonResponse({ "status": "success", "path": str(uuid) + '.pdf' }) else: raise Exception("Method is wrong") except Project.DoesNotExist: raise Http404 except Exception as e: return JsonResponse({"message": str(e)})
def render_to_pdf(path, params): # Se crean variables para establecer las opciones necesarias para ejecutar el proceso: # - template: Indica cual es el codigo HTML que se va a seguir. Se usa el parametro "path" para indicarselo. # - html: Aqui se renderiza la plantilla mediante la variable "template". El parametro que se le pasa # es el contexto que se usara en la pagina para establecer el contenido. # - response: Se trata del tipo de datos que se incluira en el PDF, es algo obligatorio y propio del modulo usado. # - pdf: Es la conversion del HTML al PDF. Usamos codificacion "UTL-8" para que se puedan mostrar todos # los caracteres españoles a la hora de mostrarlo. template = get_template(path) html = template.render(params) response = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), dest=response) # El siguiente condicional simplemente enlaza a diferentes HTML si se produce un error a la hora de crear el PDF. # En el caso de que no haya error, te redireccionara a la pagina del PDF. # En caso contrario, simplemente mostrara una pagina de error. if not pdf.err: return HttpResponse(response.getvalue(), content_type='application/pdf') else: return HttpResponse("Error Rendering PDF", status=400)
def HechosVictimizantesPDF(request, id=None): try: logo = "icbf-reporte.png" beneficiario = Beneficiario.objects.get(id=id) if beneficiario.a20 != None: parentezco = beneficiario.a20 else: parentezco = "Ninguno" result = StringIO() html = render_to_string( "reportes/hechos_victimizantes_pdf.html", { "url": URL, "logo": logo, "beneficiario": beneficiario, "titulo": "HECHOS VICTIMIZANTES", "parentezco": parentezco }) pdf = pisa.pisaDocument(html, result) return HttpResponse(result.getvalue(), content_type='application/pdf') except ObjectDoesNotExist: return HttpResponseRedirect("/")
def generate(self): """ Generates pdf using context from self.data and template from self.template_path. Saves pdf in the directory from env. Env variable "PATH_GENERATED_PDF". Generates file name using current date and time. """ context = {'info': self.data} template = get_template(self.template_path) html = template.render(context) response = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), dest=response, link_callback=self.fetch_pdf_resources) if pdf.err: raise Exception("We had some errors rendering PDF document <pre>" + html + "</pre>") else: return response.getvalue()
def download_channel_pdf(request): import time start = time.time() template = get_template('export/channels_pdf.html') channels = Channel.objects.prefetch_related('editors', 'secret_tokens', 'tags')\ .select_related('main_tree')\ .filter(public=True, deleted=False)\ .distinct()\ .order_by('name') print "Channel query time:", time.time() - start site = get_current_site(request) default_thumbnail = get_default_thumbnail() channel_list = [ get_channel_data(c, site, default_thumbnail) for c in channels ] context = Context({"channels": channel_list}) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8', path=settings.STATIC_ROOT) if not pdf.err: response = FileResponse(result.getvalue()) response['Content-Type'] = 'application/pdf' response['Content-disposition'] = 'attachment;filename=channels.pdf' response['Set-Cookie'] = "fileDownload=true; path=/" print "\n\n\nTotal time:", time.time() - start, "\n\n\n" return response
def render_to_pdf(request, order_id): """ Generate a PDF for the provided Order """ # Attempt to grab order via order_id from url. 404 if not found. try: cur_order = Order.objects.get(pk=order_id) except Order.DoesNotExist: raise Http404 # Ensure only patients can submit surveys, and that they can only submit surveys on their own orders if not is_in_group( request.user, "Patient") or cur_order.patient.pk != request.user.user_obj.pk: return Http404 # Define which user groups can see medical info, add to context medical_groups = ['Technicians', 'Radiologists', 'Physicians'] context = { 'cur_order': cur_order, 'user': request.user, 'url': request.build_absolute_uri('/')[:-1], 'show_medical': is_in_group(request.user, medical_groups) } # Send thumbnails into context and render HTML context['thumbnails'] = get_image_files(cur_order.images.all()) template = get_template('pdf_temp.html') html = template.render(context) result = BytesIO() # Free PythonAnywhere accounts do not have access to this type of file download... try: pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) except: return None if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None
def export_to_response(self): template = get_template(self.template_name) context_dict = { 'dates_list': self.queryset, 'first_session': self.first_session, 'full_static_path': self.full_static_path, 'summary_data': self.summary_data } context = Context(context_dict) html = template.render(context) result = BytesIO() encoding = 'utf8' pdf = pisa.pisaDocument(BytesIO(html.encode(encoding)), result, encoding, show_error_as_pdf=True) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def render_pdf(request): try: data = { "fname": request.session['fname'], "lname": request.session['lname'], "address": request.session['address'], "number": request.session['number'], "email": request.session['email'], "education": request.session['education'], "skills": request.session['skills'], "pdetails": request.session['pdetails'], "project": request.session['project'], "declaration": request.session['declaration'] } except: form = forms.ResumeForm() return render(request, 'testapp/form.html', { "error": True, "form": form }) template_path = 'testapp/pdf_template.html' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="resume.pdf"' template = get_template(template_path) html = template.render(data) pisaStatus = pisa.pisaDocument(html, dest=response, encoding='utf8', link_callback=link_callback) if pisaStatus.err: return HttpResponse('We had some errors with code %s <pre>%s</pre>' % (pisaStatus.err, html)) else: return response
def generate_pdf(request, args): # try: template_path = 'pdf_output.html' user_id = request.user.id user_name = request.user.username data = UserAnswer.objects.filter(user=user_id, advise=args) # Create a Django response object, and specify content_type as pdf context = {'data': data, 'username': user_name} response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="report"+str(datetime.now()).pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) file_name = 'temp/' + get_random_string(10) + '.pdf' result = open(file_name, 'wb') pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) result.close() try: user_email = request.user.email email = EmailMessage( 'Advise from Expert', 'This email contains expert advise in PDF format. Please download it. DONT REPLY', '*****@*****.**', [user_email]) email.attach_file(file_name) email.send() except: pass try: os.remove(file_name) except: pass # create a pdf pisa_status = pisa.CreatePDF(html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response
def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None # 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 HttpResponse(result.getvalue(), content_type='application/pdf') # return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) # def fetch_resources(uri, rel): # path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) # return path
def render(cls, report, column_labels, report_rows, report_inlines): # where is_export is being used? setattr(report, 'is_export', True) context_dict = { 'report': report, 'column_labels': column_labels, 'report_rows': report_rows, 'report_inlines': report_inlines, 'pagesize': 'legal landscape' } template = get_template('report_creator/export_pdf.html') #template = get_template(path) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) #html = render_to_string('report_creator/export_pdf.html', context_dict) #html = str(html) #print(type(html)) # context = Context(context_dict) # html = template.render(context) #result = StringIO.StringIO() pdf_encoding = 'UTF-8' #pdf = pisa.CreatePDF(html.encode('utf-8'), result, encoding='utf-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=%s.pdf' % report.slug else: response = HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) result.close() return response
def admin_order_pdf(request, order_id): # order = get_object_or_404(Order, id=order_id) # html = render_to_string('orders/order/pdf.html', {'order': order}) # response = HttpResponse(content_type='application/pdf') # response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(order.id) # weasyprint.HTML(string=html).write_pdf(response,stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) # return response order = get_object_or_404(Order, id=order_id) html = render_to_string('orders/order/pdf.html', {'order': order}) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format( order.id) return response else: response = HttpResponse("Error Rendering PDF", status=400) return response
def download_award_reg_form(request, award_reg_id): html = '' try: print '\nRequest IN | awards_landing.py | download_award_reg_form | User = '******'backoffice/awards/award_form.html') html = template.render(Context({'award_reg_obj': award_reg_obj})) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result) if not pdf.err: print '\nResponse OUT | awards_landing.py | download_award_reg_form | User = '******'application/pdf') response['Content-Disposition'] = 'inline; filename="' + str( award_reg_obj.company_name) + '.pdf"' return response return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) except Exception, e: print '\nException IN | awards_landing.py | download_award_reg_form | EXCP = ', str( traceback.print_exc()) return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def render_to_pdf(template, content_dic={}): t = get_template(template) send_data = t.render(content_dic) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(send_data.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else: return None # from io import StringIO # from xhtml2pdf import pisa # from django.template.loader import get_template # from django.template import Context # from django.http import HttpResponse # from cgi import escape # import datetime # def render_to_pdf(template_src, context_dict={}): # print(type(context_dict)) # template = get_template(template_src) # # context = Context(context_dict) # html = template.render(context_dict) # result = StringIO() # # pdf name generate with date # date = datetime.date.today() # tmpName = template_src.split('.')[0] # pdfName = tmpName+'-'+str(date) # pdf = pisa.pisaDocument(StringIO(html.encode("ISO-8859-1")), result) # if not pdf.err: # response = HttpResponse(result.getvalue(), content_type='application/pdf') # response['Content-Disposition']='attachment; filename='+pdfName+'.pdf' # return response # return None # # return HttpResponse("We had some errors<pre>%s</pre>" %escape(html))
def prescriptionpdf(request, patient_pk): template_path = 'pdfs/prescriptionpdf.html' patient = get_object_or_404(Patient, pk=patient_pk) prescriptions = [] today = date.today() prescriptionsdata = PrescriptionItem.objects.all().filter( patient=patient, date_prescribed=datetime.date(today.year, today.month, today.day)) if prescriptionsdata: for p in prescriptionsdata: prescriptions.append(p) context = {'patient': patient, 'prescriptions': prescriptions} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="prescriptions.pdf"' template = get_template(template_path) html = template.render(context) result = io.BytesIO() pdf = pisa.pisaDocument(io.BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return
def send_invoice(path: str, params: dict, client_mail_id: str, extra_file: str): template = get_template(path) html = template.render(params) response = BytesIO() file = open("invoice.pdf", "wb") pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), file) file.close() if not pdf.err: draft_email = EmailMessage( "Triveni: Invoice", "Hi,\nYour invoice is attached. Please remit payment at your earliest convenience.\nThank you.", settings.EMAIL_HOST_USER, [client_mail_id], ) draft_email.attach_file("invoice.pdf") if extra_file: draft_email.attach_file(settings.MEDIA_ROOT + '/triveni.localhost/' + extra_file) draft_email.send() return True else: return False