def render_pdf_bytes(html: str) -> bytes: import weasyprint from weasyprint.fonts import FontConfiguration font_config = FontConfiguration() font_css_str = LOC_FONTS_CSS.read_text().replace( "url(./", f"url({LOC_FONTS_CSS.parent.as_uri()}/" ) font_css = weasyprint.CSS(string=font_css_str, font_config=font_config) return weasyprint.HTML(string=html).write_pdf(stylesheets=[font_css], font_config=font_config)
def _write_pdf_report(self): """Convert the markdown report to html, then pdf""" LOGGER.info('Generating HTML for writing pdf report...') pypandoc.convert_file(self.path, 'html', outputfile=self._REPORT_TMP_HTML_PATH, extra_args=['-V', 'geometry:margin=1.5cm']) LOGGER.info('Metamorphosising HTML to PDF...') weasyprint.HTML(self._REPORT_TMP_HTML_PATH) \ .write_pdf(self.path_pdf, stylesheets=[weasyprint.CSS(self._REPORT_CSS_PATH)])
def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string("order/admin/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.STATICFILES_DIRS[0] + "/css/pdf.css")], ) return response
def get_css(self, base_url, url_fetcher): tmp = [] for value in self._stylesheets: #TODO test with missing or invalid css css = weasyprint.CSS(value, base_url=base_url, url_fetcher=url_fetcher) if css: tmp.append(css) return tmp
def admin_order_pdf(request: HttpRequest, order_id): order: Order = get_object_or_404(Order, pk=order_id) html = render_to_string('orders/order/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename={order.pk}.pdf' stylesheet = weasyprint.CSS( os.path.join(settings.STATIC_ROOT, 'css/pdf.css')) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[stylesheet]) return response
def write_pdf(self, fname, html_text, css_text): tmphtml = weasyprint.HTML(string=html_text) tmpcss = weasyprint.CSS(string=css_text) fname = "./output/" + fname htmlname = fname.replace('.pdf', '.html') with open(htmlname, 'w', encoding='utf-8') as f: f.write(html_text) print('Generating pdf,please wait patiently') tmphtml.write_pdf(fname, stylesheets=[tmpcss]) print('Generated')
def print_to_pdf(request, *args, **kwargs): order_id = kwargs.get('pk') orderinstance = get_object_or_404(Order, pk=order_id) html = render_to_string('order/order_pdf.html', {'order': orderinstance}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(orderinstance.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + 'css/' 'pdf_print.css')]) return response
def admin_order_pdf(request, order_id): order = get_object_or_404(Order, 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
def render_doc(content, base_url, styles): import weasyprint doc = weasyprint.HTML( string=content, base_url=base_url, url_fetcher=url_fetcher, ).render(stylesheets=[ weasyprint.CSS(string=styles), ]) return doc
def admin_order_pdf(request, receipt_id): receipt = get_object_or_404(Receipts, id=receipt_id) html = render_to_string('daily_sales/pdf.html', {'receipt': receipt}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename = \"receipt_{}.pdf"'.format( receipt.id) weasyprint.HTML(string=html).write_pdf( response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) 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"] = f"filename=order_{order.id}.pdf" weasyprint.HTML(string=html).write_pdf( response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + "css/pdf.css")]) return response
def pdf(request, order_id): order = get_object_or_404(Order, id=order_id) company = CompanyInfo.objects.latest("id") html = render_to_string("pdf.html", {"order": order, "company": company}) response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = f"filename=order {order.id}.pdf" weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf( response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + "/css/pdf.css")] ) return response
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() 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 generate_pdf(request): files = Poll.objects.filter(author_id=request.user.id) html_string = render_to_string('pollgram/pdf_list.html', {'files': files}) # Rendered response = HttpResponse( content_type='application/pdf;') # Creating http response response['Content-Disposition'] = 'filename=poll_list_{}.pdf'.format( request.user) weasyprint.HTML(string=html_string).write_pdf( response, stylesheets=[weasyprint.CSS('static/css/pdf.css')]) return response
def to_pdf_raw(basic_markdown: str, css_paths: Optional[List[str]] = None) -> bytes: """Convert RAW markdown with specified CSS paths into bytes of a PDF.""" css_paths = css_paths or [] as_html = to_html(basic_markdown) directory = tempfile.mkdtemp('gxmarkdown') index = os.path.join(directory, "index.html") try: output_file = codecs.open(index, "w", encoding="utf-8", errors="xmlcharrefreplace") output_file.write(as_html) output_file.close() html = weasyprint.HTML(filename=index) stylesheets = [weasyprint.CSS(string=resource_string(__package__, "markdown_export_base.css"))] for css_path in css_paths: with open(css_path) as f: css_content = f.read() css = weasyprint.CSS(string=css_content) stylesheets.append(css) return html.write_pdf(stylesheets=stylesheets) finally: shutil.rmtree(directory)
def get_css(self, base_url, url_fetcher): tmp = [] for value in self._stylesheets: css = weasyprint.CSS( value, base_url=base_url, url_fetcher=url_fetcher, ) if css: tmp.append(css) return tmp
def result_pdf(request): """View that allows student to print their result""" student = Student.objects.get(user__pk=request.user.id) current_semester = Semester.objects.get(is_current_semester=True) current_session = Session.objects.get(is_current_session=True) courses = TakenCourse.objects.filter(student__user__pk=request.user.id, course__level=student.level, course__semester=current_semester) result = Result.objects.filter(student__user__pk=request.user.id, semester=current_semester) current_CGPA = 0 try: a = Result.objects.get(student__user__pk=request.user.id, level=student.level, semester="Second") current_CGPA = a.cgpa except: current_CGPA = 0 point = 0 cp = 0 # cps = 0 t = () for i in courses: t += (i.course.pk, ) registered_courses = Course.objects.filter(level=student.level).filter( id__in=t) total_registered_unit = 0 for i in registered_courses: total_registered_unit += int(i.courseUnit) html = render_to_string( 'result/resultpdf.html', { "student": student, "courses": courses, "result": result, "current_CGPA": current_CGPA, "registered_courses": registered_courses, "total_registered_unit": total_registered_unit, "current_semester": current_semester, "current_session": current_session, # "point": point, # "cp": cp }) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = f'filname=student_{student.id_number}.pdf' weasyprint.HTML( string=html, base_url=request.build_absolute_uri()).write_pdf( response, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + '/css/resultpdf.css') ]) return response
def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('order/admin/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf( response, stylesheets=[ weasyprint.CSS(settings.STATICFILES_DIRS[0] + '/css/pdf.css') ]) return response
def to_pdf(trans, basic_markdown, css_paths=[]): as_html = to_html(basic_markdown) directory = tempfile.mkdtemp('gxmarkdown') index = os.path.join(directory, "index.html") try: output_file = codecs.open(index, "w", encoding="utf-8", errors="xmlcharrefreplace") output_file.write(as_html) output_file.close() html = weasyprint.HTML(filename=index) stylesheets = [weasyprint.CSS(string=pkg_resources.resource_string(__name__, 'markdown_export_base.css'))] for css_path in css_paths: with open(css_path, "r") as f: css_content = f.read() css = weasyprint.CSS(string=css_content) stylesheets.append(css) return html.write_pdf(stylesheets=stylesheets) # font_config = FontConfiguration() # stylesheets=[css], font_config=font_config finally: shutil.rmtree(directory)
def pdf_response(html: str, filename: str): import weasyprint from weasyprint.fonts import FontConfiguration font_config = FontConfiguration() font_css_str = LOC_FONTS_CSS.read_text().replace( 'url(./', f'url({LOC_FONTS_CSS.parent.as_uri()}/') font_css = weasyprint.CSS(string=font_css_str, font_config=font_config) pdf_bytes = weasyprint.HTML(string=html).write_pdf(stylesheets=[font_css], font_config=font_config) return FileResponse(BytesIO(pdf_bytes), filename=filename)
def admin_order_pdf(request, pk): order = get_object_or_404(SalesOrder, id=pk) html = render_to_string('sales/salesorder_pdf.html', {'object': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}"'.format(order.id) weasyprint.HTML(string=html).write_pdf( response, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + '/css/materialize.css') ]) return response
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) # Создание и сохранение транзакции result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_cost()), '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, '*****@*****.**', [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() return redirect('payment:done') else: return redirect('payment:canceled') else: # Формирование одноразоваого токена для JS SDK client_token = braintree.ClientToken.generate() return render(request, 'payment/process.html', { 'order': order, 'client_token': client_token })
def payment_completed(order_id): order = Order.objects.get(id=order_id) subject = f'My Shop - EE Invoice no. {order.id}' message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, 'admin@my_shop.com', [order.email]) html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'shop/css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) email.attach(f'order_{order.id}.pdf', out.getvalue(), 'application/pdf') email.send()
def render(self, stylesheet=None): import weasyprint template_dir = pkg_resources.resource_filename('stoq', 'template') if platform.system() == 'Windows': # FIXME: Figure out why this is breaking # On windows, weasyprint is eating the last directory of the path template_dir = os.path.join(template_dir, 'foobar') html = weasyprint.HTML(string=self.get_html(), base_url=template_dir) return html.render(stylesheets=[weasyprint.CSS(string=stylesheet)])
def _write_pdf_report(self): """Convert the markdown report to html, then pdf""" LOGGER.info('Generating HTML for writing pdf report...') md_file = self._report_prefix + '.md' pypandoc.convert_file(md_file, 'html', outputfile=self._REPORT_TMP_HTML_PATH, extra_args=['-V', 'geometry:margin=1.5cm', '--columns', '1000']) LOGGER.info('Metamorphosising HTML to PDF...') html_writer = weasyprint.HTML(self._REPORT_TMP_HTML_PATH) pdf_file = self._report_prefix + '.pdf' html_writer.write_pdf(pdf_file, stylesheets=[weasyprint.CSS(self._REPORT_CSS_PATH)])
def html_to_pdf(html, stylesheet_paths=[]): if not weasyprint: raise Problem(_("Could not create PDF since Weasyprint is not available. Please contact support.")) stylesheets = [] for stylesheet_path in stylesheet_paths: stylesheets.append(weasyprint.CSS(string=_fetch_static_resource_str(stylesheet_path))) return weasyprint.HTML( string=html, url_fetcher=_custom_url_fetcher ).write_pdf( stylesheets=stylesheets )
def search_pdf(request): file_filter = Slife.objects.filter(author=request.user.username) html_string = render_to_string('lifegram/pdf_search.html', {'filter': file_filter}) # Rendered response = HttpResponse( content_type='application/pdf;') # Creating http response response['Content-Disposition'] = 'filename=life_search_{}.pdf'.format( request.user) weasyprint.HTML(string=html_string).write_pdf( response, stylesheets=[weasyprint.CSS('static/css/pdf.css')]) return response
def detail_pdf(request, pk): files = Life.objects.filter(id=pk) # Model data html_string = render_to_string('lifegram/pdf_detail.html', {'files': files}) # Rendered response = HttpResponse( content_type='application/pdf;') # Creating http response response['Content-Disposition'] = 'filename=life_detail_{}_{}.pdf'.format( request.user, pk) weasyprint.HTML(string=html_string).write_pdf( response, stylesheets=[weasyprint.CSS('static/css/pdf.css')]) return response
def get(self, request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string(self.template_name, {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf( response, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + '/css/style.css') ]) return response
def generate_pdf(request): group_name = request.user.groups.values_list('name', flat=True).first() files = User.objects.filter(groups__name=group_name) html_string = render_to_string('accounts/pdf_list.html', {'files': files}) # Rendered response = HttpResponse( content_type='application/pdf;') # Creating http response response['Content-Disposition'] = 'filename=account_list_{}.pdf'.format( request.user) weasyprint.HTML(string=html_string).write_pdf( response, stylesheets=[weasyprint.CSS('static/css/pdf.css')]) return response