def record_pdf_download(request, pk): response = HttpResponse(content_type="application/pdf") record = DailyRecord.objects.get(pk=pk) response[ 'Content-Disposition'] = "attachment; filename={date}-record-detail-{count}.pdf".format( date=record.date.strftime('%Y-%m-%d'), count=slugify(record.customers.all().count()), ) html = render_to_string("records/record_pdf.html", { 'record': record, }) stylesheets = [ settings.BASE_DIR + '/pdf-css/form.css', settings.BASE_DIR + '/pdf-css/bootstrap.min.css', ] font_config = FontConfiguration() HTML(string=html).write_pdf(response, stylesheets=stylesheets, font_config=font_config) return response
def generate_ticket_pdf(request, order): """ Generates a pdf of the tickets in a given order Parameters: request (Request): The request object order (Order): The order to generate tickets for Returns: A byte buffer of the generated pdf """ # Get tickets for this order tickets = Ticket.objects.filter(order=order) # Generate a html template for the ticket context = { 'order': order, 'tickets': tickets, 'request': request, } html = render_to_string('tickets/ticket.html', context) # Generate a pdf from the HTML font_config = FontConfiguration() ticket_pdf = HTML(string=html, base_url=request.build_absolute_uri()).write_pdf( font_config=font_config) return ticket_pdf
def export_pdf(pdf_filename, html_string, css_string): font_config = FontConfiguration() html = HTML(string=html_string) css = CSS(string=css_string, font_config=font_config) html.write_pdf(target=pdf_filename, stylesheets=[css], font_config=font_config)
def idea_handout_pdf(request, pk): ## for macOS requires: ## brew install python3 cairo pango gdk-pixbuf libffi from django.template.loader import render_to_string from django.utils.timezone import now as timezone_now from django.utils.text import slugify from django.http import HttpResponse from weasyprint import HTML from weasyprint.fonts import FontConfiguration idea = get_object_or_404(Idea, pk=pk) context = {"idea": idea} html = render_to_string("ideas/idea_handout_pdf.html", context) response = HttpResponse(content_type="application/pdf") response[ "Content-Disposition"] = "inline; filename={date}-{name}-handout.pdf".format( date=timezone_now().strftime("%Y-%m-%d"), name=slugify(idea.translated_title)) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response
def render_pdf(request, app_id): applicant = position_has_applicant(request, app_id) answers = FormAnswer.objects.filter( parent_applicant=applicant).order_by("parent_question") for answer in answers: answer.qualifier_set = Qualifier.objects.filter( parent_answer=answer).order_by( 'qualifier_type') if Qualifier.objects.filter( parent_answer=answer).count() > 0 else None answer.extract_set = NlpExtract.objects.filter( parent_answer=answer).order_by( 'next_extract_index', '-extract_type') if NlpExtract.objects.filter( parent_answer=answer).count() > 0 else None answer.note_set = Note.objects.filter( parent_answer=answer).order_by('created') if Note.objects.filter( parent_answer=answer).count() > 0 else None if applicant is not None: response = HttpResponse(content_type="application/pdf") html = render_to_string("sbr_pdf.html", { 'applicant': applicant, 'answers': answers }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response return redirect('home')
def print_birth_certificate(request, id): applicant = get_object_or_404(BirthRegistration, id=id) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = "inline; filename={first_name}-{surname}-{birth_cert_no}-certificate.pdf".format( first_name=applicant.first_name, surname=applicant.surname, birth_cert_no=applicant.birth_cert_no, ) if request.user.is_staff: current_user = request.user birth_date = applicant.date_of_birth.strftime("%d/%m/%Y") add_date = applicant.birth_reg_date.strftime("%d/%m/%Y") update_date = applicant.birth_reg_updated.strftime("%d/%m/%Y") html = render_to_string( "cert_management/birth_certificate.html", { 'applicant': applicant, 'current_user': current_user, 'birth_date': birth_date, 'add_date': add_date, 'update_date': update_date }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response else: e = 'You are not authorized to access this page' h = render(request, "cert_management/birth_error.html", { 'applicant': applicant, 'e': e }) return h
def extract(self, ordered): if ordered: text = self._unifyTextOrdered() else: text = self._unifyTextUnordered() first_page = '<h1 class="session-name">{}</h1>\n'.format( self.title) + '<p class="date">{}</p>\n'.format( self.date) + '<p class="author">{}</p>\n\n'.format(self.author) font_config = FontConfiguration() html = markdown.markdown( text, extensions=[ 'markdown_katex', ], extension_configs={ 'markdown_katex': { 'no_inline_svg': True, # fix for WeasyPrint 'insert_fonts_css': False, }, }) html = first_page + html css = CSS(filename=path.join(self.appPath, 'style.css'), font_config=font_config) katexCss = CSS(filename=path.join(self.appPath, 'katex.min.css'), font_config=font_config) HTML(string=html).write_pdf(self.exportPath, stylesheets=[katexCss, css], font_config=font_config)
def convert_html_to_pdf(source_html, output_filename): # open output file for writing (truncated binary) # result_file = open(output_filename, "w+b") font_config = FontConfiguration() # HTML(string=source_html).write_pdf(output_filename,stylesheets=[CSS(string='@font-face {font-family: grb;src: url(./resources/Bariol.ttf);}#header_content {left: 50pt; width: 512pt; top: 50pt; height: 40pt;}#footer_content {left: 50pt; width: 512pt; top: 772pt; height: 20pt;}#main_content {left: 50pt; width: 512pt; top: 90pt; height: 632pt;}margin: 2cm;body { font-family: grb; font-size: 120%; }h1 { color: #3f6fb4; }tr.final { border-bottom: 1px solid #eee; padding: 3px 0; }tr.footer { padding: 5px; text-align: center; }div#footer_content { text-align: center; }h1 { font-family: Gentium }', font_config=font_config)]) x = HTML(string=source_html) x.write_pdf(output_filename, stylesheets=[ CSS(string=''' @font-face { font-family: bariol; src: url(Bariol.ttf); } h1 { color: #3f6fb4; } body { font-family: sans-serif; font-size: 80%; } #main_content { margin: 0 auto; text-align: left; width: 75%; } table{ width: 100%; border-bottom: 1px solid #ddd; padding-bottom: 20px; } tr.final { border-bottom: 1px solid #eee; padding: 3px 0; } tr.footer { padding: 5px; text-align: center; } tr.tr_header { font-weight: bold; } div#footer_content { text-align: center; margin-top: 20px; } ''', font_config=font_config) ]) sys.exit()
def quotation_to_pdf_view(request, id): quote = get_object_or_404(Quotation, pk=id) rates = QuotationRatesAndTerms.objects.all().filter(quotation=quote) rates = enumerate(rates) context = { 'quote': quote, 'rates': rates, } html_string = render_to_string('commerce/quote.html', context) html = HTML(string=html_string) html.write_pdf(target=f'media/Quotations/pdf-{id}.pdf') # fs = FileSystemStorage('/media/pdfs') with open(f'media/Quotations/pdf-{id}.pdf', 'rb') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="quotation.pdf"' font_config = FontConfiguration() HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf( response, font_config=font_config) msg = EmailMessage('Subject of the Email', 'Body of the email', '*****@*****.**', ['*****@*****.**']) msg.content_subtype = "html" msg.attach_file(f'media/Quotations/pdf-{id}.pdf') msg.send() return response return response
def get(self, request, id): obj = get_object_or_404(Event, id=id) event_participant = EventParticipant.objects.filter(user=request.user, event=obj) event_name = obj.event_type.replace(" ", "_") # template = get_template('ticket.html') context = {'object': obj, 'event_participant': event_participant} # html = template.render(context) html = render_to_string("ticket.html", context) # pdf = render_to_pdf("ticket.html", context) if event_participant.count() > 0: if event_participant[0].invoice: if event_participant[0].invoice.pay_status: filename = "Ticket_%s_%s.pdf" % (event_name, request.user.username) content = "inline; filename='%s'" % (filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" % (filename) font_config = FontConfiguration() html_response = HTML( string=html, base_url=request.build_absolute_uri()).write_pdf( font_config=font_config, presentational_hints=True) response = HttpResponse(html_response, content_type='application/pdf') response['Content-Disposition'] = content return response return HttpResponseRedirect( reverse('ticketing:event_detail_view', kwargs={'id': id}))
def generate_pdf(self, path, raw_html): ''' Generate PDF file from raw_html using Weasyprint. Parameters: path: Where to save the output PDF file raw_html: String of HTML to convert ''' font_config = FontConfiguration() HTML(string=raw_html).write_pdf('{0}.pdf'.format(path), stylesheets=[ self.font_css(), self.page_css(), self.table_block_css(), self.table_css(), self.img_css(), self.td_css(), self.th_css(), self.body_css(), self.company_block_css(), self.company_description_css() ], font_config=font_config)
def bill_to_pdf_view(request, id): bill = get_object_or_404(Bill, pk=id) context = {'bill': bill} html_string = render_to_string('commerce/bill.html', context) html = HTML(string=html_string) html.write_pdf(target=f'media/bills/pdf-{id}.pdf') # fs = FileSystemStorage('/media/pdfs') with open(f'media/bills/pdf-{id}.pdf', 'rb') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="bill.pdf"' font_config = FontConfiguration() HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf( response, font_config=font_config) msg = EmailMessage('Subject of the Email', 'Body of the email', '*****@*****.**', ['*****@*****.**']) msg.content_subtype = "html" msg.attach_file(f'media/bills/pdf-{id}.pdf') msg.send() return response return response
def idea_handout_pdf(request, pk): from django.template.loader import render_to_string from django.utils.timezone import now as timezone_now from django.utils.text import slugify from django.http import HttpResponse from weasyprint import HTML, CSS from weasyprint.fonts import FontConfiguration idea = get_object_or_404(Idea, pk=pk) context = {"idea": idea} html = render_to_string("ideas/idea_handout_pdf.html", context) response = HttpResponse(content_type="application/pdf") response[ "Content-Disposition"] = "inline; filename={date}-{name}-handout.pdf".format( date=timezone_now().strftime("%Y-%m-%d"), name=slugify(idea.translated_title), ) font_config = FontConfiguration() css = CSS( settings.WEBSITE_URL + settings.STATIC_URL + 'site/css/bootstrap.min.css', ) HTML(string=html).write_pdf(response, font_config=font_config, stylesheets=[css]) return response
def report_pdf(company, record_list, total__paid, new_report, paid_employee, record, host_url): salary = get_object_or_404(Salary, user=paid_employee) employee = [] employee.append(record_list[0].id) html = render_to_string(template_name="report_pdf.html", context={ 'company': company, 'record_list': record_list, 'total_paid': total__paid, 'new_report': new_report, 'payslip': paid_employee, 'salary': salary, 'record': record, 'employee': employee, }) css = CSS(host_url + settings.STATIC_ROOT + 'report_pdf.css') font_config = FontConfiguration() pdf_file = HTML(string=html).write_pdf(stylesheets=[css], font_config=font_config) new_report.reportfiles = SimpleUploadedFile( f'Payperiod Report-{record.date_paid.strftime("%d-%m-%Y")}.pdf', pdf_file, content_type='application/pdf') new_report.save()
def __init__(self, save_as: t.Optional[str] = 'ksc-letter.pdf', view: str = 'inline'): self.documents = [] self.font_configuration = FontConfiguration() # https://fastapi.tiangolo.com/advanced/response-headers/ self.header = {'Content-Disposition': f'{view};filename={save_as}'}
def generatePdf(content, filename): from weasyprint import HTML, CSS from weasyprint.fonts import FontConfiguration font_conf = FontConfiguration() html = HTML(string=content) html.write_pdf(filename, font_config=font_conf)
def pdf_generator(content, filename): from weasyprint import HTML from weasyprint.fonts import FontConfiguration font_config = FontConfiguration() html = HTML(string=content) html.write_pdf(filename, font_config=font_config)
def css_for_extra_fonts(): font_config = FontConfiguration() return CSS(string=''' @font-face { font-family: 'BC Sans Regular'; src: local('BCSans-Regular'); } @font-face { font-family: 'BC Sans Bold'; src: local('BCSans-Bold'); } @font-face { font-family: 'BC Sans Bold Italic'; src: local('BCSans-BoldItalic'); } @font-face { font-family: 'BC Sans Italic'; src: local('BCSans-Italic'); } @font-face { font-family: 'Noto Sans Light'; src: local('NotoSans-Light'); } @font-face { font-family: 'Noto Sans Light Italic'; src: local('NotoSans-LightItalic'); } ''', font_config=font_config), font_config
def to_pdf_cv(request, cv_lang, cv_id): ''' Generata pdf for CVs ''' context = query_student(request.user.id) letter = get_object_or_404(Letter, id=cv_id, user_id=request.user.id) context.update({ 'cv_lang': cv_lang, 'cv_id': cv_id, 'letter': letter, 'is_pdf_view': True }) html_file = ''.join(['resumeApp/cv_', cv_lang, '.html']) font_config = FontConfiguration() html_string = render_to_string(html_file, context) html = HTML(string=html_string, base_url=request.build_absolute_uri()) css = [ CSS(css_dir + '/screens/common_style.css'), CSS(fonts_dir + '/thsarabunnew.css', font_config=font_config), CSS(css_dir + '/screens/cv_screen.css'), ] pdf_file = html.write_pdf(stylesheets=css, font_config=font_config) response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="cv.pdf"' return response
def CotizacionPDF(request, id): from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.text import slugify from django.contrib.auth.decorators import login_required from weasyprint import HTML from weasyprint.fonts import FontConfiguration from weasyprint import CSS bou = get_object_or_404(CotizacionCabecera, id=id) cuerpo = CuerpoCotizacion.objects.filter(cabecera=bou) print(bou.id) sum = 0 for a in cuerpo: total = a.precio * a.cantidad sum = sum + total #response = HttpResponse(content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document") response = HttpResponse(content_type="application/pdf") # response['Content-Disposition'] = "attachment; response[ 'Content-Disposition'] = "attachment; filename=VLF.{}.{}.{}.pdf".format( bou.FechaCreacion.year, str(bou.ContSerializeQtn).zfill(4), str(bou.SerializeQtn).zfill(2)) font_config = FontConfiguration() html = render_to_string("vil/tpl/cotizacion.html", { 'bou': bou, 'cuerpo': cuerpo, 'request': request, "subtotal": sum }) css = CSS(string=''' @page { @bottom-center { content: string(title); font-size:12px; border-top:1px solid black; color:#186a43; width:100%; height:50px; } } header { width: 0; height: 0; visibility: hidden; string-set: title content(); } @font-face { font-family: "calibrilight"; } body{ font-family: 'calibrilight'; font-size: 12px; }''', font_config=font_config) HTML(string=html).write_pdf(response, stylesheets=[css], font_config=font_config) return response
def get(self, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) font_config = FontConfiguration() html = HTML( string=render_to_string(self.template_name, context=context)) css_files = ['css/bootstrap.min.css', 'css/print.css'] css_files = [ 'css/print.css', ] css_str = "" for f in css_files: with open(finders.find(f), 'r') as fh: css_str += fh.read() css = CSS(string=css_str) # Create a PDF response and use Weasy to print to it response = HttpResponse(content_type="application/pdf") response[ 'Content-Disposition'] = 'filename="relief_sale_receipt_{}.pdf"'.format( slugify(self.object.name)) html.write_pdf(target=response, stylesheets=[ css, ], font_config=font_config) return response
def generate_pdf(request, id_passageiro_passagem): """Generate pdf.""" # Model data font_config = FontConfiguration() passageiro_passagem = get_object_or_404(PassageiroPassagem, pk=id_passageiro_passagem) remarcacoes = RemarcacaoPassagem.objects.filter(passageiro_passagem=passageiro_passagem) css = CSS(string=''' .box-trecho { background-color:#F0F8FF; border: 1px solid; margin: 3px; font-size: 12px; padding: 8px; }''', font_config=font_config) # Rendered html_string = render_to_string('passagem_emitida.html', {'passageiro_passagem': passageiro_passagem, 'remarcacoes': remarcacoes}) html = HTML(string=html_string) result = html.write_pdf(stylesheets=[css], font_config=font_config) # Creating http response response = HttpResponse(content_type='application/pdf; charset=utf-8') #response['Content-Disposition'] = 'inline; filename=list_people.pdf' #response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response
def export_pdf(html_string, filename): """Export the equipment inventory in PDF.""" css_path = os.path.join(settings.PHARMASHIP_REPORTS, filename) try: with open(css_path, "r") as fdesc: css_string = fdesc.read() except IOError as error: log.error("CSS file not readable: %s", error) return None # Create a temporary file tmp_file = tempfile.NamedTemporaryFile(prefix="pharmaship_", suffix=".pdf", delete=False) font_config = FontConfiguration() html = HTML(string=html_string) css = CSS(string=css_string, font_config=font_config) html.write_pdf(target=tmp_file.name, stylesheets=[css], font_config=font_config) query_count_all() return tmp_file.name
def convert_html_to_pdf(source_html, output_filename): ''' utility function for converting HTML to PDF this could be done "in-line" but has been made a function in case it needs to be repeated later ''' # open output file for writing (truncated binary) font_config = FontConfiguration() pdf_output = HTML(string=source_html) pdf_output.write_pdf( output_filename, stylesheets=[ CSS( string=''' h1 { color: #3f6fb4; } body { font-family: sans-serif; font-size: 80%; line-height: 1.2em; } #main_content { margin: 0 auto; text-align: left; width: 75%; } table{ width: 100%; border-bottom: 1px solid #ddd; padding-bottom: 20px; } tr.final { border-bottom: 1px solid #eee; padding: 3px 0; } tr.footer { padding: 5px; text-align: center; } tr.tr_header { font-weight: bold; } td,p { padding: 3px; } div#footer_content { text-align: center; margin-top: 20px; } ''', font_config=font_config, ) ], )
def make_pdf_response(html, filename='reports.pdf'): font_config = FontConfiguration() pdf = HTML(string=html).write_pdf(font_config=font_config) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response
def writepdf(file_data): global global_root_dir, image_base font_config = FontConfiguration() css = read_css() image_base_url() html = HTML(string=file_data, base_url=image_base, encoding="utf8") # print(css) html.write_pdf(filename + '.pdf', stylesheets=css, font_config=font_config)
def generate_pdf_weasy(request, template, file_name, context): response = HttpResponse(content_type="application/pdf") response['Content-Disposition'] = "inline; filename=%s.pdf" % (file_name) html = render_to_string(template, context) font_config = FontConfiguration() pdf = HTML(string=html, base_url=request.build_absolute_uri()).write_pdf( response, font_config=font_config) return response
def pdf(request): response = HttpResponse(content_type="application/pdf") response[ 'Content-Disposition'] = "inline; filename=donation-receipt.pdf".format( ) html = render_to_string("index.html") font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response
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 get(self, request, *args, **kwargs): status = "" if self.kwargs['value']: print("self.kwargs['value'] ==> ", self.kwargs['value']) status = self.kwargs['value'] user = Profile.objects.latest('id') # print(user,'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy') answers = Answer.objects.filter(user=user.id) # print("user.id ==> ", user.id) # print("Answer ==> ", answers) # print("Answer ==> ", answers[0].answer) # print("Answer ==> ", answers[0].question) font_config = FontConfiguration() date = datetime.datetime.today().date() time = datetime.datetime.today().time() # print("date ==> ", date) # print("time ==> ", time) pdf_string = render_to_string('pdf.html', locals()) html = HTML(string=pdf_string, base_url=request.build_absolute_uri()) pdf_file = html.write_pdf(target="/tmp/" + user.firstname + '_result.pdf', font_config=font_config) print(" ********** PDF Generated ************** ") subject = "Survey Result email !!" recipients = [ '[email protected] ', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] #'*****@*****.**'] #[user.email] message = "" if (len(answers) < 200): #200 if status == "inactivity": message = user.firstname + " was inactive for 10 minutes, Here are the answers gotten" if status == "quit": message = user.firstname + " did not complete the survey with 200 questions and quit the survey in between." #200 else: message = user.firstname + " completed the survey with 200 questions." #200 try: # file = open( './' +user.firstname+'_result.pdf', "rb") mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, recipients) mail.attach_file("/tmp/" + user.firstname + '_result.pdf') mail.send() except Exception as e: print(str(e)) raise e return HttpResponseRedirect('/completion/')