#!/usr/bin/env python # encoding: utf-8 import weasyprint weasyprint.HTML("http://kaito-kidd.com/2015/03/12/python-html2pdf/").write_pdf( "test1.pdf") weasyprint.HTML("http://kaito-kidd.com/2015/03/12/python-html2pdf/").write_png( "test1.png")
def save_pdf(articles_in_html, path): """save rendered html code to pdf file""" weasyprint.HTML(string=articles_in_html).write_pdf(f'{path}.pdf') print(f'Convertion to pdf is complete. File {path}.pdf is created')
def simplify(self, url, outfile=None): """ Parse the content of a web page removing any extra elements using Mercury :param url: URL to parse :param outfile: If set then the output will be written to the specified file (supported formats: pdf, html, plain (default)). The plugin will guess the format from the extension :return: dict Example if outfile is not specified:: { "url": <url>, "title": <page title>, "content": <page parsed content> } Example if outfile is specified:: { "url": <url>, "title": <page title>, "outfile": <output file absolute path> } """ self.logger.info('Parsing URL {}'.format(url)) parser = subprocess.Popen(['node', self._mercury_script, url], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) response = parser.stdout.read().decode() try: response = json.loads(response) except Exception as e: raise RuntimeError('Could not parse JSON: {}. Response: {}'.format( str(e), response)) self.logger.info('Got response from Mercury API: {}'.format(response)) title = response.get( 'title', '{} on {}'.format( 'Published' if response.get('date_published') else 'Generated', response.get('date_published', datetime.datetime.now().isoformat()))) content = response.get('content', '') if not outfile: return { 'url': url, 'title': title, 'content': content, } outfile = os.path.abspath(os.path.expanduser(outfile)) content = '''<h1>{title}</h1><div class="_parsed-content">{content}</div>'''.\ format(title=title, content=content) style = ''' body { font-size: 22px; font-family: 'Merriweather', Georgia, 'Times New Roman', Times, serif; } ''' if outfile.lower().endswith('.pdf'): import weasyprint from weasyprint.fonts import FontConfiguration font_config = FontConfiguration() css = [ weasyprint.CSS( 'https://fonts.googleapis.com/css?family=Merriweather'), weasyprint.CSS(string=style, font_config=font_config) ] weasyprint.HTML(string=content).write_pdf(outfile, stylesheets=css) else: content = ''' <html> <head> <title>{title}</title> <style>{style}</style> </head> <body>{{content}}</body> </html> '''.format(title=title, style=style, content=content) with open(outfile, 'w', encoding='utf-8') as f: f.write(content) return { 'url': url, 'title': title, 'outfile': outfile, }
from django.conf import settings from django.template.loader import render_to_string from django.core.mail import EmailMessage from io import BytesIO import weasyprint def PaymentNotification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: order = get_object_or_404(Order, id=ipn_obj.invoice) order.paid = True order.save() valid_ipn_received.connect(PaymentNotification) # Отправка Email subject = 'Онлайн-магазин - заказ: {}'.format(Order.id) message = 'К email сообщению прикреплен PDF файл с информацией о вашем заказе.' email = EmailMessage(subject, message, '*****@*****.**', [Order.email]) # Генерация PDF html = render_to_string('orders/order/pdf.html', {'order': Order}) out = BytesIO() weasyprint.HTML(string=html).write_pdf(out, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/bootstrap.min.css')]) # Прикрепляем pdf email.attach('order_{}.pdf'.format(Order.id), out.getvalue(), 'application/pdf') email.send()
def lux_report_get(self): ref = self.request.matchdict.get("ref") job = DBSession.query(LuxPrintJob).get(ref) if job is None: return HTTPNotFound() try: resp, content = self._proxy("%s/report/%s" % (job.print_url, ref)) attributes = json.loads(job.spec)["attributes"] is_pdf = json.loads(job.spec)["format"] == "pdf" print_title = attributes.get("name") if print_title is None or len(print_title) == 0: print_title = "map_geoportal_lu" print_title = re.sub(r" ", "_", print_title) print_title = re.sub(r"[^a-zA-Z0-9\-\_]", "", print_title) if is_pdf and "firstPagesUrls" in attributes and\ attributes["firstPagesUrls"] is not None and\ len(attributes["firstPagesUrls"]) > 0: attributes["firstPagesUrls"].reverse() for pageUrl in attributes["firstPagesUrls"]: try: merger = PdfFileMerger(strict=False) if pageUrl['type'].lower() == 'pdf': opener = urllib.request.build_opener( urllib.request.HTTPHandler()) pdf_content = opener.open(pageUrl['url']).read() merger.append(BytesIO(pdf_content)) else: first_page = BytesIO() weasyprint.HTML( pageUrl['url']).write_pdf(first_page) merger.append(first_page) merger.append(BytesIO(content)) content = BytesIO() merger.write(content) content = content.getvalue() except Exception as e: log.exception(e) if is_pdf and "legend" in attributes and\ attributes["legend"] is not None: merger = PdfFileMerger(strict=False) merger.append(BytesIO(content)) lang = attributes.get("lang") for item in attributes["legend"]: if "restUrl" in item and item["restUrl"] is not None: merger.append( self._create_legend_from_url(item["restUrl"])) elif "legendUrl" in item and item["legendUrl"] is not None: legend_title = "" if "legendTitle" in item and\ item["legendTitle"] is not None: legend_title = item["legendTitle"] access_constraints = "" if "accessConstraints" in item and\ item["accessConstraints"] is not None: access_constraints = item["accessConstraints"] merger.append( self._create_legend_from_image( item["legendUrl"], legend_title, access_constraints)) elif "name" in item and item["name"] is not None: merger.append(self._get_legend(item["name"], lang)) content = BytesIO() merger.write(content) content = content.getvalue() if is_pdf and "queryResults" in attributes and\ attributes["queryResults"] is not None: css = weasyprint.CSS( string=".ng-hide {display: none !important;} " + ".no-print {display: none !important;} " + "body {font-size: 60%;} " + ".route-details-step { font-family: " + "Arial,sans-serif; font-size: 14px; " + "line-height: 20px; border-bottom: 1px " + "solid #8394A0; padding: 10px 10px 10px 30px; " + "margin: 0 -12px 0 0; position: relative;} " + ".route-info-title {font-size: 18px; " + "line-height: 19px; font-weight: 700;} " + ".route-general-info-container {display: " + "table; width: 100%;} " + ".route-single-info {display: table-cell; " + "width: auto;} " + ".route-info-general-data {font-size: 18px; " + "font-weight: 700; line-height: 22px; " + "padding-top: 10px;} " + ".route-info-data {color: #8394A0;} " + ".route-instruction-data {font-size: 16px; " + "line-height: 19px; display: inline-block; " + "margin: 0 10px 0 0;} " + ".route-instruction {margin-bottom: 10px;" + "position: relative;} " + ".icon-Direction {position: absolute; top: 0;" + "right: 100%; margin-right: 6px;} " + ".icon-Direction:before {font-family: " + "apart-geoportail!important;content: '\e903';" + "font-size: 6px;color:'#000';} " + ".south {transform: rotate(90deg);} " + ".north {transform: rotate(270deg);} " + ".west {transform: rotate(180deg);} " + ".east {transform: rotate(0deg);} " + ".n-e {transform: rotate(315deg);} " + ".n-w {transform: rotate(225deg);} " + ".s-w {transform: rotate(135deg);} " + ".s-e {transform: rotate(45deg);} ") merger = PdfFileMerger(strict=False) merger.append(BytesIO(content)) query_results = BytesIO() weasyprint.HTML(string=attributes["queryResults"]).write_pdf( query_results, stylesheets=[css]) merger.append(query_results) content = BytesIO() merger.write(content) content = content.getvalue() DBSession.delete(job) if is_pdf: resp["content-disposition"] =\ "attachment; filename=%s.pdf" % (str(print_title)) else: resp["content-disposition"] =\ "attachment; filename=%s.png" % (str(print_title)) return self._build_response(resp, content, NO_CACHE, "print") except Exception as e: log.exception(e) log.error("reference is : " + ref) if job is not None: job.is_error = True return HTTPInternalServerError()
file_loader = FileSystemLoader( "/media/jeanraltique/FishStory/Projectos/Doutoramento/PhDCode/PhDProject/PDF_generator/testJinja2" ) env = Environment(loader=file_loader) a = np.random.randint(0, 100, 100) t = np.linspace(0, 1, 100) fig = plt.plot(t, a) plt.savefig("example.png") template = env.get_template("template_test.html") output = template.render(title="Best Title", graph="""example.png""") print(output) html = open("output.html", "w") html.write(output) html.close() import os html = weasyprint.HTML('output.html') pdf = html.write_pdf("output.pdf") # # from pathlib import Path # # p = Path(Path.home()).parents[1] # # # path_wkhtmltopdf = "usr/bin/" # config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) # pdfkit.from_file("/media/jeanraltique/FishStory/Projectos/Doutoramento/PhDCode/PhDProject/PDF_generator/testJinja2/output.html", "test.pdf", configuration=config)
def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() create_action(order.first_name + ' ' + order.last_name, 'На сумму ' + str(order.summa) + ' руб.', 'bullhorn', order) #request.session['order_a'] = form for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # create invoice e-mail subject = 'Интернет магазин preparation.su - Инвойс № {}'.format( order.id) message = 'Пожалуйста, прочтите прилагаемый счет-фактуру за вашу недавнюю покупку' email = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [order.email]) #email = EmailMessage(subject,message,order.email,[settings.EMAIL_HOST_USER,]) # generate PDF html = render_to_string('shop/cart/order_pdf.html', {'order': order}) out = BytesIO() stylesheets = [ weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css') ] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail try: email.send() #send admin except socket_error as serr: if serr.errno != errno.ECONNREFUSED: # Not the error we are looking for, re-raise raise serr except SMTPException as e: error_code, error_msg = e.smtp_code, e.smtp_error print(error_msg) subject = 'Заказ № {}'.format(order.id) message = 'Поступил {},\n\nзаказ на сайте preparation.su .Заказ от {}. на сумму {} email {}'.format( order.first_name, order.id, order.summa, order.email) #email = EmailMessage(subject,message,'*****@*****.**',[order.email]) email = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER]) try: email.send() #send admin except socket_error as serr: if serr.errno != errno.ECONNREFUSED: # Not the error we are looking for, re-raise raise serr except SMTPException as e: error_code, error_msg = e.smtp_code, e.smtp_error print(error_msg) # очистить корзину cart.clear() return render(request, 'shop/cart/end_order.html', { 'order': order, 'form': form, 'step': 3, 'sect': 'order', }) else: form = OrderCreateForm() return render(request, 'shop/cart/order_created.html', { 'cart': cart, 'form': form, 'step': 2, 'orders_item': True, })
if filename.startswith('.'): continue with open(os.path.join(INPUT_DIR, filename), encoding='utf-8') as f: code = f.read() if filename.endswith('.ansi'): lexer = ANSILexer() else: lexer = get_lexer_for_filename(filename) lexer.add_filter(Sublette.filter()) highlighted = highlight(code, lexer, formatter) # Detect size by output instead of input. text = highlight(code, lexer, NullFormatter()) lines = text.split('\n') columns = max(len(line.rstrip()) for line in lines) rows = len(lines) html = weasyprint.HTML(string=TEMPLATE % { 'css': formatter.get_style_defs('body'), 'html': highlighted, 'width': (columns+4) * 15, 'height': (rows+2) * 30, }) output_path = OUTPUT_PATTERN % filename with open(output_path, 'wb') as f: html.write_png(f, font_config=font_config) print(os.path.relpath(output_path, os.path.curdir))
def get_new_items(self, response): import feedparser engine = create_engine('sqlite:///{}'.format(self.dbfile), connect_args={'check_same_thread': False}) Base.metadata.create_all(engine) Session.configure(bind=engine) self._get_or_create_source(session=Session()) feed = feedparser.parse(response.text) session = Session() source_record = self._get_or_create_source(session=session) session.add(source_record) parse_start_time = datetime.datetime.utcnow() entries = [] latest_update = self._get_latest_update(session, source_record.id) if not self.title and 'title' in feed.feed: self.title = feed.feed['title'] source_record.title = self.title content = u''' <h1 style="{title_style}">{title}</h1> <h2 style="{subtitle_style}">Feeds digest generated on {creation_date}</h2>'''.\ format(title_style=self.title_style, title=self.title, subtitle_style=self.subtitle_style, creation_date=datetime.datetime.now().strftime('%d %B %Y, %H:%M')) self.logger.info('Parsed {:d} items from RSS feed <{}>' .format(len(feed.entries), self.url)) for entry in feed.entries: if not entry.published_parsed: continue try: entry_timestamp = datetime.datetime(*entry.published_parsed[:6]) if latest_update is None \ or entry_timestamp > latest_update: self.logger.info('Processed new item from RSS feed <{}>'.format(self.url)) entry.summary = entry.summary if hasattr(entry, 'summary') else None if self.extract_content: entry.content = self._parse_entry_content(entry.link) elif hasattr(entry, 'summary'): entry.content = entry.summary else: entry.content = None content += u''' <h1 style="{article_title_style}"> <a href="{link}" target="_blank" style="{article_link_style}">{title}</a> </h1> <div class="_parsed-content" style="{article_content_style}">{content}</div>'''.format( article_title_style=self.article_title_style, article_link_style=self.article_link_style, article_content_style=self.article_content_style, link=entry.link, title=entry.title, content=entry.content) e = { 'entry_id': entry.id, 'title': entry.title, 'link': entry.link, 'summary': entry.summary, 'content': entry.content, 'source_id': source_record.id, 'published': entry_timestamp, } entries.append(e) session.add(FeedEntry(**e)) if self.max_entries and len(entries) > self.max_entries: break except Exception as e: self.logger.warning('Exception encountered while parsing RSS ' + 'RSS feed {}: {}'.format(entry.link, str(e))) self.logger.exception(e) source_record.last_updated_at = parse_start_time digest_filename = None if entries: self.logger.info('Parsed {} new entries from the RSS feed {}'.format( len(entries), self.title)) if self.digest_format: digest_filename = os.path.join(self.workdir, 'cache', '{}_{}.{}'.format( datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), self.title, self.digest_format)) os.makedirs(os.path.dirname(digest_filename), exist_ok=True) if self.digest_format == 'html': content = ''' <html> <head> <title>{title}</title> </head> <body style="{body_style}">{content}</body> </html> '''.format(title=self.title, body_style=self.body_style, content=content) with open(digest_filename, 'w', encoding='utf-8') as f: f.write(content) elif self.digest_format == 'pdf': import weasyprint from weasyprint.fonts import FontConfiguration body_style = 'body { {body_style} }'.format(body_style=self.body_style) font_config = FontConfiguration() css = [weasyprint.CSS('https://fonts.googleapis.com/css?family=Merriweather'), weasyprint.CSS(string=body_style, font_config=font_config)] weasyprint.HTML(string=content).write_pdf(digest_filename, stylesheets=css) else: raise RuntimeError('Unsupported format: {}. Supported formats: ' + 'html or pdf'.format(self.digest_format)) digest_entry = FeedDigest(source_id=source_record.id, format=self.digest_format, filename=digest_filename) session.add(digest_entry) self.logger.info('{} digest ready: {}'.format(self.digest_format, digest_filename)) session.commit() self.logger.info('Parsing RSS feed {}: completed'.format(self.title)) return NewFeedEvent(request=dict(self), response=entries, source_id=source_record.id, source_title=source_record.title, title=self.title, digest_format=self.digest_format, digest_filename=digest_filename)
def weasyprint(cls, data, options=None): return weasyprint.HTML(string=data).write_pdf()
def generate_pdf(request, r_CV_name, r_date_of_birth): data_from_redis_json = r.get(f"{r_CV_name}/{r_date_of_birth}") data = json.loads(data_from_redis_json) print(data) #Personal info pi = data['Personal_info'] first_name = pi.get('first_name') last_name = pi.get('last_name') current_position = pi.get('current_position') mobile = pi.get('mobile') email = pi.get('email') date_of_birth = pi.get('date_of_birth') address = pi.get('address') postal_code = pi.get('postal_code') city = pi.get('city') def exists(_dict: Dict[str, Any], key_1, key_2=None) -> bool: # if key_2: # return _dict.get(key_1) is not None and _dict.get(key_2) is not None # else: # return _dict.get(key_1) is not None if key_2: for index, item in enumerate(_dict.values()): if item.get(key_1) and item.get(key_2): return True else: for index, item in enumerate(_dict.values()): if item.get(key_1): return True #Experience exp = data['Experience'] #A variable made to check, whether pdf label should be displayed or not company_exists = exists(exp, 'company') print(company_exists) #Education edu = data['Education'] #A variable made to check, whether pdf label should be displayed or not institution_exists = exists(edu, 'institution') #Skills ski = data['Skill'] #A variable made to check, whether pdf label should be displayed or not skill_exists = exists(ski, 'skill', 'rating') #Licenses and certifications lic = data['License'] #A variable made to check, whether pdf label should be displayed or not license_exists = exists(lic, 'name', 'date_finished') print(license_exists) cla = data['Clause'] clause_exists = cla.get('text') != None html = render_to_string( 'tempresume/test.html', { 'data': data, 'first_name': first_name, 'last_name': last_name, 'current_position': current_position, 'mobile': mobile, 'email': email, 'date_of_birth': date_of_birth, 'address': address, 'postal_code': postal_code, 'city': city, 'exp': exp, 'company_exists': company_exists, 'edu': edu, 'institution_exists': institution_exists, 'ski': ski, 'skill_exists': skill_exists, 'lic': lic, 'license_exists': license_exists, 'cla': cla, 'clause_exists': clause_exists, }) response = HttpResponse(content_type='application/pdf') weasyprint.HTML( string=html, base_url=request.build_absolute_uri()).write_pdf( response, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + 'tempresume/pdf.css') ]) return response
def generate_the_pdf_from_body(cls, body) -> bytes: with io.BytesIO() as content: weasyprint.HTML(string=body).write_pdf(content) return content.getvalue()
def ray_download_weasy(sno: int, url: str) -> None: pdf = weasyprint.HTML(url).write_pdf() filename = Render.get_filename(1 + sno, url) open(filename, 'wb').write(pdf)
def weasyprint_render(cls, content): return weasyprint.HTML(string=content, media_type=MEDIA_TYPE).render()
def get_pdf(self): """get the file url and create output""" pdf = weasyprint.HTML(self.url).write_pdf() file_name = "output_files/" + self.output_filename with open(file_name, "wb") as file_: file_.write(pdf)
def make_doc(self): html = self.get_html_string() doc = wp.HTML(string=html) return doc.write_pdf()
def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_cost()), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() # create invoice e-mail subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [ weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css') ] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() # send sms # Your Account SID from twilio.com/console account_sid = "AC1cac4d02cc38ebe54d55d730ca00703c" # Your Auth Token from twilio.com/console auth_token = "423946a57f6b878f341abe7d66b3fe2f" client = Client(account_sid, auth_token) message = client.messages.create( to="+14027066443", from_="+117122484584", body= "Thank you {} {}, Your order {} has been placed successfully and will be delivered to {}, {}, {}" .format(order.first_name, order.last_name, order.id, order.address, order.city, order.postal_code)) print(message.sid) return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = braintree.ClientToken.generate() return render(request, 'payment/process.html', { 'order': order, 'client_token': client_token })
def rendered_content(self): html = weasyprint.HTML(string=super().rendered_content) return html.write_pdf()
def pdf(): return weasyprint.HTML(string=request.data).write_pdf()
def to_pdf(in_path, out_path): weasyprint.HTML(filename=str(in_path)).write_pdf(str(out_path))
def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_cost()), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() # create invoice e-mail subject = 'GameBoyz - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [ weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css') ] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() #send SMS # Your Account SID from twilio.com/console account_sid = "ACdb4a615b456bcb58f019a5de49166625" # Your Auth Token from twilio.com/console auth_token = "80e4e9e9163cf30489a622ac17c74953" client = Client(account_sid, auth_token) TwilioNumber = "+17122013458" custnumber = "+" + str(1) + order.phone_number message = client.messages.create( to=custnumber, from_=TwilioNumber, body="Hello " + order.first_name + " " + order.last_name + ". Your package will arrive in 5-7 business days at " + order.address + ".") return redirect('payment:done') else: return redirect('payment:canceled') else: #generate token client_token = braintree.ClientToken.generate() return render(request, 'payment/process.html', { 'order': order, 'client_token': client_token })
def Deliverables_report_pdf_render(self, siteid, projectid, ITPid, deliverableIdList): site = Site.query.filter_by(id=siteid).first() project = Project.query.filter_by(id=projectid).first() project_ITP = ITP.query.filter_by(id=ITPid).first() print(deliverableIdList) print([deliverable for deliverable in deliverableIdList]) deliverables_all = Deliverable.query.filter( Deliverable.id.in_(deliverableIdList)).all() deliverables = Deliverable.query.filter( Deliverable.id.in_(deliverableIdList)).all() deliverable_types = Deliverable_type.query.filter( Deliverable_type.id.in_([ deliverable.deliverable_type_id for deliverable in deliverables ])).all() deliverable_types_all = Deliverable_type.query.filter( Deliverable_type.id.in_([ deliverable.deliverable_type_id for deliverable in deliverables_all ])).all() today = datetime.datetime.now() # image = flask_weasyprint.default_url_fetcher("/static/img/logo-schneider-electric.png") ITC_groups = ITC_group.query.all() ITC_groups = sorted(ITC_groups, key=lambda x: x.name) self.update_state(state='PROGRESS') DDC_group = ['Automation Server', 'AS-P', 'AS'] #Set up variables to update user screen while ITCs are generated i = 0 total = len(deliverables) + len(deliverables) ITCs = Deliverable_ITC_map.query.filter( Deliverable_ITC_map.deliverable_id.in_( [deliverable.id for deliverable in deliverables])).all() ITCs = sorted( ITCs, key=lambda x: (x.deliverable.type.name, x.deliverable.name, x.ITC.group.name)) i += total * 0.1 self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Creating ITCs' }) print('ITCs have been created') ITCs_old = sorted(ITCs, key=lambda x: (x.ITC.group.name)) i += total * 0.1 self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Creating ITCs' }) env = Environment(loader=PackageLoader('app', 'templates'), autoescape=select_autoescape(['html', 'xml'])) i += total * 0.05 self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Starting Report build' }) #Creates PDF with app.app_context(): i += total * 0.025 self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Starting Report build' }) print('converting to pdf') percent_add = len(deliverables) / total #create deliverable pdfs for x in range(len(deliverables)): name = 'pdf_' + str(x) + '.pdf' deliverable = deliverables[x] #Creates PDF template = render_template( 'ITP_report.html', site=site, project=project, project_ITP=project_ITP, deliverable=deliverable, deliverables=deliverables, deliverables_all=deliverables_all, ITCs=ITCs, deliverable_types=deliverable_types, deliverable_types_all=deliverable_types_all, today=today, groups=ITC_groups, DDC_group=DDC_group) i += percent_add self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Creating ITCs' }) print('Middle pdf templates rendered') html = weasyprint.HTML(string=template) pdf = html.write_pdf('./' + name) print('converting to pdf') i += total * 0.025 self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Starting Report build' }) pdf_number = x + 1 #join pdfs pdfs = [] for y in range(pdf_number): pdfs.extend(['pdf_' + str(y) + '.pdf']) i += len(deliverables) * 0.1 self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Starting Report build' }) merger = PdfFileMerger() percent_add = len(deliverables) * 0.5 / pdf_number for pdf in pdfs: merger.append(PdfFileReader(app.config['PROJECT_ROOT'] + '/' + pdf), import_bookmarks=False) i += percent_add self.update_state(state='PROGRESS', meta={ 'current': i, 'total': total, 'status': 'Starting Report build' }) name = 'test_deliverables.pdf' merger.write('app/reports/' + name) for pdf in pdfs: os.remove(app.config['PROJECT_ROOT'] + '/' + pdf) print('page has been rendered') self.update_state(state='Complete', meta={ 'current': total, 'total': total, 'status': 'Complete' })
def report_pdf(report): cuckoopng = open("static/img/cuckoo.png", "rb").read() cuckoopng = cuckoopng.encode("base64").replace("\n", "") html = render_template("report.html", report=report, cuckoopng=cuckoopng) report = weasyprint.HTML(string=html).write_pdf() return report, 200, {"Content-Type": "application/pdf"}
def export_report_to_pdf(self, file_name, year=None, date_precision='D', combine=True, convert_timezone=True, font_size=12, template_file='shortreport_en.html', custom_column_names=None, custom_formatters=None, locale=None): """Export the capital gains report to a pdf file. :param file_name: string; Destination file name. :param year: None or 4-digit integer, default: None; Leave `None` to export all sales or choose a specific year to export. :param date_precision: one of 'D', 'H' or 'T' for daily, hourly or minutely, respectively (may also be multiplied, e.g.: '5T' for 5-minutely), default: 'D'; Floors all datetimes to the specified frequency. Does nothing if date_precision is False. :param combine: boolean, default True; Combines consecutive transactions which only differ in the 'amount', 'cost', 'proceeds' and 'profit'. Such transactions will be combined by summing up the values in these columns. This is only useful if *date_precision* is set, since otherwise consecutive dates will very seldomly match. Therefore, does nothing if *date_precision* is False. :param convert_timezone: string, pytz.timezone, dateutil.tz.tzfile, True or False; All dates (i.e. purchase_date and sell_date entries) will be converted to this timezone. The default value, True, will lead to a conversion to the locale timezone according to the system's locale setting. False keeps all dates at UTC time. Otherwise, specify a parameter that will be forwarded to pandas.Timestamp.tz_convert(). :param template_file: file name of html template inside package folder: `ccgains/templates`. Default: 'shortreport_en.html' :param custom_column_names: None or list of strings; If None (default), the column names of the DataFrame returned from `get_report_data(extended=False)` will be used. To rename them, supply a list of length 10. :param custom_formatters: None or dict of one-parameter functions; If None (default), a set of default formatters for each column will be used, using babel.numbers and babel.dates. Individual formatting functions can be supplied with the (renamed) column names as keys. The result of each function must be a unicode string. :param locale: None or locale identifier, e.g. 'de_DE' or 'en_US'; The locale used for formatting numeric and date values with babel. If None (default), the locale will be taken from the `LC_NUMERIC` or `LC_TIME` environment variables on your system, for numeric or date values, respectively. """ html = self.get_report_html(year=year, date_precision=date_precision, combine=combine, convert_timezone=convert_timezone, font_size=font_size, template_file=template_file, custom_column_names=custom_column_names, custom_formatters=custom_formatters, locale=locale) doc = weasyprint.HTML(string=html) doc.write_pdf(file_name) log.info("Saved short capital gains report %sto %s", 'for year %i ' % year if year else '', str(file_name))
def createJBImage( self, css ): html = wp.HTML( string = self.html ) doc = html.render( stylesheets = [ css ] ) png, width, height = doc.write_png( target=None ) img = JBImage( self.id, width, height, data = png, localFile= ROOT_DIR / self.getImageFileName() ) return img
def export_extended_report_to_pdf(self, file_name, year=None, date_precision='D', combine=True, convert_timezone=True, font_size=10, template_file='fullreport_en.html', payment_kind_translation=None, locale=None): """Export the extended capital gains report to a pdf file. :param file_name: string; Destination file name. :param year: None or 4-digit integer, default: None; Leave `None` to export all sales or choose a specific year to export. :param date_precision: one of 'D', 'H' or 'T' for daily, hourly or minutely, respectively (may also be multiplied, e.g.: '5T' for 5-minutely), default: 'D'; Floors all datetimes to the specified frequency. Does nothing if date_precision is False. :param combine: boolean, default True; Combines consecutive transactions which only differ in the 'amount', 'cost', 'proceeds' and 'profit'. Such transactions will be combined by summing up the values in these columns. This is only useful if *date_precision* is set, since otherwise consecutive dates will very seldomly match. Therefore, does nothing if *date_precision* is False. :param convert_timezone: string, pytz.timezone, dateutil.tz.tzfile, True or False; All dates (i.e. purchase_date and sell_date entries) will be converted to this timezone. The default value, True, will lead to a conversion to the locale timezone according to the system's locale setting. False keeps all dates at UTC time. Otherwise, specify a parameter that will be forwarded to pandas.Timestamp.tz_convert(). :param template_file: file name of html template inside package folder: `ccgains/templates`. Default: 'fullreport_en.html' :param payment_kind_translation: None (default) or dictionary; This allows for the payment kind (one out of ['sale', 'withdrawal fee', 'deposit fee', 'exchange fee']) to be translated (the dict keys must be the mentioned english strings, the values are the translations used in the output). :param locale: None or locale identifier, e.g. 'de_DE' or 'en_US'; The locale used for formatting numeric and date values with babel. If None (default), the locale will be taken from the `LC_NUMERIC` or `LC_TIME` environment variables on your system, for numeric or date values, respectively. """ html = self.get_extended_report_html( year=year, date_precision=date_precision, combine=combine, convert_timezone=convert_timezone, font_size=font_size, template_file=template_file, payment_kind_translation=payment_kind_translation, locale=locale) doc = weasyprint.HTML(string=html) doc.write_pdf(file_name) log.info("Saved detailed capital gains report %sto %s", 'for year %i ' % year if year else '', str(file_name))
# Create a pandas dataframe with demo data: import pandas as pd demodata_csv = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv' df = pd.read_csv(demodata_csv) # Pretty print the dataframe as an html table to a file intermediate_html = '/tmp/intermediate.html' #to_html_pretty(df,intermediate_html,'Iris Data') # if you do not want pretty printing, just use pandas: # df.to_html(intermediate_html) # Convert the html file to a pdf file using weasyprint import weasyprint out_pdf= '/tmp/demo.pdf' weasyprint.HTML(intermediate_html).write_pdf(out_pdf)
#!/usr/bin/env python3 import sys import os import pathlib import weasyprint ### this works pdfbytes = weasyprint.HTML('foobar.html') pdfbytes.write_pdf('foobar.pdf') pdffile = pathlib.Path('./foobar2.pdf') pdfbytes.write_pdf(pdffile) ### this does not pdfbytes = weasyprint.HTML('./foobar.html') ### this does not htmlfile = pathlib.Path('./foobar.html') print(type(htmlfile)) print(htmlfile) pdfbytes = weasyprint.HTML(htmlfile)
def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) if request.method == 'POST': # Получение токена для создания транзакции nonce = request.POST.get('payment_method_nonce', None) # Создание и сохранение транзакции # формируем идентификатор платежной транзакции, обращаясь к методу # braintree.Transaction.sale(). В качестве аргументов этот метод # принимает: # - amount (общую сумму заказа); # - payment_method_nonce (токен, сгенерированный Braintree для # платежной транзакции. Он формируется на странице силами # JavaScript SDK); # - options (дополнительные параметры. Мы передали значение submit_ # for_settlement, равное True, благодаря чему транзакция будет обраба- # тываться автоматически); result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_price()), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # Отметка заказа как оплаченного order.paid = True # Сохранение ID транзакции в заказе order.braintree_id = result.transaction.id order.save() # Создание электронного сообщения. subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your ' \ 'recent purchase.' email = EmailMessage(subject, message, 'admin@localhost', [order.email]) # Формирование PDF. html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # Прикрепляем PDF к электронному сообщению. email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # Отправка сообщения email.send() # Удаление купона из сессии, после успешной оплаты заказа del request.session['coupon_id'] return redirect('payment:done') else: return redirect('payment:canceled') else: # Формирование одноразового токена для JavaScript SDK client_token = braintree.ClientToken.generate() return render(request, 'payment/process.html', {'order': order, 'client_token': client_token})
def create_pdf(issue: Issue): """ Returns a PDF file string. """ client = issue.client uploads = FileUpload.objects.filter(issue=issue) tenancy = (Tenancy.objects.select_related( "landlord", "agent").filter(client=client).last()) client_info = [ { "name": "Client name", "answers": [client.get_full_name()] }, { "name": "Client email", "answers": [client.email] }, { "name": "Client DOB", "answers": [_format_datetime(client.date_of_birth)] if client.date_of_birth else [], }, { "name": "Client phone", "answers": [client.phone_number] }, { "name": "Client call times", "answers": [client.call_times] }, { "name": "Client special circumstances", "answers": [client.special_circumstances], }, ] tenancy_info = [ { "name": "Tenancy address", "answers": [tenancy.address] }, { "name": "Tenancy started", "answers": [_format_datetime(tenancy.started)] if tenancy.started else [], }, { "name": "Client is on lease", "answers": [tenancy.is_on_lease] }, ] people = [] people_info = [] if tenancy.agent: people.append(["Agent", tenancy.agent]) if tenancy.landlord: people.append(["Landlord", tenancy.landlord]) for title, person in people: if person.full_name: people_info.append({ "name": f"{title} name", "answers": [person.full_name] }) if person.email: people_info.append({ "name": f"{title} email", "answers": [person.email] }) if person.address: people_info.append({ "name": f"{title} address", "answers": [person.address] }) if person.phone_number: people_info.append({ "name": f"{title} phone number", "answers": [person.phone_number] }) sub_info = [] for name, answer in issue.answers.items(): sub_info.append({ "name": name.lower().replace("_", " ").capitalize(), "answers": answer if type(answer) is list else [answer], }) answers = [ *client_info, *tenancy_info, *people_info, *sub_info, ] context = { "issue": issue, "answers": answers, "uploads": uploads, } pdf_html_str = render_to_string("actionstep/client-intake.html", context=context) pdf_bytes = weasyprint.HTML(string=pdf_html_str).write_pdf() return pdf_bytes