def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'quiet': None, 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") try: pdfkit.from_string(html, fname, options=options or {}) except IOError, e: if "ContentNotFoundError" in e.message: frappe.throw(_("PDF generation failed because of broken image links")) else: raise
def get_formatted_html(subject, message, footer=None, print_html=None, email_account=None): message = scrub_urls(message) if not email_account: email_account = get_outgoing_email_account(False) rendered_email = frappe.get_template( "templates/emails/standard.html").render({ "content": message, "signature": get_signature(email_account), "footer": get_footer(email_account, footer), "title": subject, "print_html": print_html, "subject": subject }) return rendered_email
def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None, doc=None, lang=None, print_letterhead=True): from frappe.utils import scrub_urls if not file_name: file_name = name file_name = file_name.replace(' ','').replace('/','-') print_settings = db.get_singles_dict("Print Settings") _lang = local.lang #set lang as specified in print format attachment if lang: local.lang = lang local.flags.ignore_print_permissions = True no_letterhead = not print_letterhead if int(print_settings.send_print_as_pdf or 0): out = { "fname": file_name + ".pdf", "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True, doc=doc, no_letterhead=no_letterhead) } else: out = { "fname": file_name + ".html", "fcontent": scrub_urls(get_print(doctype, name, print_format=print_format, style=style, html=html, doc=doc, no_letterhead=no_letterhead)).encode("utf-8") } local.flags.ignore_print_permissions = False #reset lang to original local lang local.lang = _lang return out
def attach_print(doctype, name, file_name=None): from frappe.utils import scrub_urls if not file_name: file_name = name print_settings = db.get_singles_dict("Print Settings") local.flags.ignore_print_permissions = True if int(print_settings.send_print_as_pdf or 0): out = { "fname": file_name + ".pdf", "fcontent": get_print(doctype, name, as_pdf=True) } else: out = { "fname": file_name + ".html", "fcontent": scrub_urls(get_print(doctype, name)).encode("utf-8") } print print_settings, out local.flags.ignore_print_permissions = False return out
def get_formatted_html(subject, message, footer=None, print_html=None, email_account=None, header=None): if not email_account: email_account = get_outgoing_email_account(False) rendered_email = frappe.get_template( "templates/emails/standard.html").render({ "header": get_header(header), "content": message, "signature": get_signature(email_account), "footer": get_footer(email_account, footer), "title": subject, "print_html": print_html, "subject": subject }) sanitized_html = scrub_urls(rendered_email) transformed_html = inline_style_in_html(sanitized_html) return transformed_html
def write_html_to_pdf(file_info,html): import time import pdfkit, os, frappe from frappe.utils import scrub_urls fname = 'HLSNP-{filename}.pdf'.format(filename=str(int(round(time.time() * 1000)))) fpath = os.path.join(file_info.get('path'),fname) options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) html = scrub_urls(html) pdfkit.from_string(html, fpath, options=options or {}) return { "path":fpath, "fname":fname }
def get_pdf(html, options=None, output=None): html = scrub_urls(html) html, options = prepare_options(html, options) fname = os.path.join("/tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) try: pdfkit.from_string(html, fname, options=options or {}) if output: append_pdf(PdfFileReader(file(fname, "rb")), output) else: with open(fname, "rb") as fileobj: filedata = fileobj.read() except IOError, e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): # allow pdfs with missing images if file got created if os.path.exists(fname): with open(fname, "rb") as fileobj: filedata = fileobj.read() else: frappe.throw( _("PDF generation failed because of broken image links")) else: raise
def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None): from frappe.utils import scrub_urls if not file_name: file_name = name file_name = file_name.replace(" ", "").replace("/", "-") print_settings = db.get_singles_dict("Print Settings") local.flags.ignore_print_permissions = True if int(print_settings.send_print_as_pdf or 0): out = { "fname": file_name + ".pdf", "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True), } else: out = { "fname": file_name + ".html", "fcontent": scrub_urls(get_print(doctype, name, print_format=print_format, style=style, html=html)).encode( "utf-8" ), } local.flags.ignore_print_permissions = False return out
def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = set_portal_link(sent_via, d) send_print_in_body = frappe.db.get_value("Outgoing Email Settings", None, "send_print_in_body_and_attachment") if not send_print_in_body: d.content += "<p>Please see attachment for document details.</p>" mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer, print_html=print_html if send_print_in_body else None) if send_me_a_copy: mail.cc.append(frappe.db.get_value("User", frappe.session.user, "email")) if print_html: print_html = scrub_urls(print_html) mail.add_attachment(name.replace(' ','').replace('/','-') + '.html', print_html) for a in json.loads(attachments): try: mail.attach_file(a) except IOError: frappe.throw(_("Unable to find attachment {0}").format(a)) send(mail)
def get_formatted_html(subject, message, footer=None, print_html=None, email_account=None, header=None, unsubscribe_link=None, sender=None, with_container=False): if not email_account: email_account = get_outgoing_email_account(False, sender=sender) signature = None if "<!-- signature-included -->" not in message: signature = get_signature(email_account) rendered_email = frappe.get_template("templates/emails/standard.html").render({ "brand_logo": get_brand_logo(email_account) if with_container or header else None, "with_container": with_container, "site_url": get_url(), "header": get_header(header), "content": message, "signature": signature, "footer": get_footer(email_account, footer), "title": subject, "print_html": print_html, "subject": subject }) html = scrub_urls(rendered_email) if unsubscribe_link: html = html.replace("<!--unsubscribe link here-->", unsubscribe_link.html) html = inline_style_in_html(html) return html
def write_html_to_pdf(file_info, html): import time import pdfkit, os, frappe from frappe.utils import scrub_urls fname = 'HLSNP-{filename}.pdf'.format( filename=str(int(round(time.time() * 1000)))) fpath = os.path.join(file_info.get('path'), fname) options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) html = scrub_urls(html) pdfkit.from_string(html, fpath, options=options or {}) return {"path": fpath, "fname": fname}
def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'quiet': None, 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value( "Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") try: pdfkit.from_string(html, fname, options=options or {}) except IOError, e: if "ContentNotFoundError" in e.message: frappe.throw( _("PDF generation failed because of broken image links")) else: raise
def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'quiet': None, 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value( "Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
def get_pdf(html, options=None, output=None): html = scrub_urls(html) html, options = prepare_options(html, options) fname = os.path.join("/tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) try: pdfkit.from_string(html, fname, options=options or {}) if output: append_pdf(PdfFileReader(file(fname, "rb")), output) else: with open(fname, "rb") as fileobj: filedata = fileobj.read() except IOError, e: if ( "ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message ): # allow pdfs with missing images if file got created if os.path.exists(fname): with open(fname, "rb") as fileobj: filedata = fileobj.read() else: frappe.throw(_("PDF generation failed because of broken image links")) else: raise
def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = set_portal_link(sent_via, d) send_print_in_body = frappe.db.get_value("Email Settings", None, "send_print_in_body_and_attachment") if not send_print_in_body: d.content += "<p>Please see attachment for document details.</p>" mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer, print_html=print_html if send_print_in_body else None) if send_me_a_copy: mail.cc.append(frappe.db.get_value("Profile", frappe.session.user, "email")) if print_html: print_html = scrub_urls(print_html) mail.add_attachment(name.replace(' ','').replace('/','-') + '.html', print_html) for a in json.loads(attachments): try: mail.attach_file(a) except IOError, e: frappe.msgprint("""Unable to find attachment %s. Please resend without attaching this file.""" % a, raise_exception=True)
def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'quiet': None, 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
def test_scrub_urls(self): html = ''' <p>You have a new message from: <b>John</b></p> <p>Hey, wassup!</p> <div class="more-info"> <a href="http://test.com">Test link 1</a> <a href="/about">Test link 2</a> <a href="login">Test link 3</a> <img src="/assets/frappe/test.jpg"> </div> <div style="background-image: url('/assets/frappe/bg.jpg')"> Please mail us at <a href="mailto:[email protected]">email</a> </div> ''' html = scrub_urls(html) url = get_url() self.assertTrue('<a href="http://test.com">Test link 1</a>' in html) self.assertTrue( '<a href="{0}/about">Test link 2</a>'.format(url) in html) self.assertTrue( '<a href="{0}/login">Test link 3</a>'.format(url) in html) self.assertTrue( '<img src="{0}/assets/frappe/test.jpg">'.format(url) in html) self.assertTrue( 'style="background-image: url(\'{0}/assets/frappe/bg.jpg\') !important"' .format(url) in html) self.assertTrue('<a href="mailto:[email protected]">email</a>' in html)
def get_pdf(html, options=None, output=None): html = scrub_urls(html) html, options = prepare_options(html, options) options.update({ "disable-javascript": "", "disable-local-file-access": "", "disable-smart-shrinking": "" }) filedata = '' try: # Set filename property to false, so no file is actually created filedata = pdfkit.from_string(html, False, options=options or {}) # https://pythonhosted.org/PyPDF2/PdfFileReader.html # create in-memory binary streams from filedata and create a PdfFileReader object reader = PdfFileReader(io.BytesIO(filedata)) except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): # allow pdfs with missing images if file got created if filedata: if output: # output is a PdfFileWriter object output.appendPagesFromReader(reader) else: frappe.throw( _("PDF generation failed because of broken image links")) else: raise if "password" in options: password = options["password"] if six.PY2: password = frappe.safe_encode(password) if output: output.appendPagesFromReader(reader) return output writer = PdfFileWriter() writer.appendPagesFromReader(reader) if "password" in options: writer.encrypt(password) filedata = get_file_data_from_writer(writer) return filedata
def get_pdf(html, options=None, output=None): html = scrub_urls(html) html, options = prepare_options(html, options) options.update({"disable-javascript": "", "disable-local-file-access": ""}) filedata = '' if LooseVersion(get_wkhtmltopdf_version()) > LooseVersion('0.12.3'): options.update({"disable-smart-shrinking": ""}) try: # Set filename property to false, so no file is actually created filedata = pdfkit.from_string(html, False, options=options or {}) # https://pythonhosted.org/PyPDF2/PdfFileReader.html # create in-memory binary streams from filedata and create a PdfFileReader object reader = PdfFileReader(io.BytesIO(filedata)) except OSError as e: if any([error in str(e) for error in PDF_CONTENT_ERRORS]): if not filedata: frappe.throw( _("PDF generation failed because of broken image links")) # allow pdfs with missing images if file got created if output: # output is a PdfFileWriter object output.appendPagesFromReader(reader) else: frappe.throw( _("PDF generation failed because of broken image links")) else: raise if "password" in options: password = options["password"] if six.PY2: password = frappe.safe_encode(password) if output: output.appendPagesFromReader(reader) return output writer = PdfFileWriter() writer.appendPagesFromReader(reader) if "password" in options: writer.encrypt(password) filedata = get_file_data_from_writer(writer) return filedata
def get_formatted_html(subject, message, footer=None, print_html=None): # imported here to avoid cyclic import message = scrub_urls(message) rendered_email = frappe.get_template("templates/emails/standard.html").render({ "content": message, "footer": get_footer(footer), "title": subject, "print_html": print_html, "subject": subject }) return rendered_email
def get_formatted_html(subject, message, footer=None, print_html=None): message = scrub_urls(message) rendered_email = frappe.get_template("templates/emails/standard.html").render({ "content": message, "footer": get_footer(footer), "title": subject, "print_html": print_html }) # if in a test case, do not inline css if frappe.local.flags.in_test: return rendered_email return inlinestyler.utils.inline_css(rendered_email)
def get_formatted_html(subject, message, footer=None, print_html=None, email_account=None): if not email_account: email_account = get_outgoing_email_account(False) rendered_email = frappe.get_template("templates/emails/standard.html").render({ "content": message, "signature": get_signature(email_account), "footer": get_footer(email_account, footer), "title": subject, "print_html": print_html, "subject": subject }) return scrub_urls(rendered_email)
def attach_print(doctype, name, file_name): from frappe.utils import scrub_urls print_settings = db.get_singles_dict("Print Settings") if int(print_settings.send_print_as_pdf or 0): return { "fname": file_name + ".pdf", "fcontent": get_print_format(doctype, name, as_pdf=True) } else: return { "fname": file_name + ".html", "fcontent": scrub_urls(get_print_format(doctype, name)).encode("utf-8") }
def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'quiet': None, 'no-outline': None, }) if frappe.session and frappe.session.sid: options['cookie'] = [('sid', '{0}'.format(frappe.session.sid))] if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value( "Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") try: pdfkit.from_string( html, fname, options=options or {}, ) with open(fname, "rb") as fileobj: filedata = fileobj.read() except IOError, e: if "ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message: # allow pdfs with missing images if file got created if os.path.exists(fname): with open(fname, "rb") as fileobj: filedata = fileobj.read() else: frappe.throw( _("PDF generation failed because of broken image links")) else: raise
def get_pdf_custom(html, doc, options=None, output = None): html = scrub_urls(html) fname = os.path.join("/tmp", "custom-pdf-{0}.pdf".format(frappe.generate_hash())) options = { 'page-size': 'A4', 'margin-top': '3mm', #to have some top margin in new-page breaks inside table have to set some margin top 'margin-right': '0mm', 'margin-bottom': '5mm', 'margin-left': '0mm', 'encoding': "UTF-8", } #update with header and footer: options.update(prepare_header_footer(doc)) print(options) try: pdfkit.from_string(html, fname, options=options or {}) #no need for append in our case: #if output: # append_pdf(PdfFileReader(file(fname,"rb")),output) #else: with open(fname, "rb") as fileobj: filedata = fileobj.read() except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): # allow pdfs with missing images if file got created if os.path.exists(fname): #if output: # append_pdf(PdfFileReader(file(fname,"rb")),output) #else: with open(fname, "rb") as fileobj: filedata = fileobj.read() else: frappe.throw(_("PDF generation failed because of broken image links")) else: raise finally: cleanup(fname, options) if output: return output return filedata
def get_formatted_html(subject, message, footer=None, print_html=None): message = scrub_urls(message) rendered_email = frappe.get_template( "templates/emails/standard.html").render({ "content": message, "footer": get_footer(footer), "title": subject, "print_html": print_html }) # if in a test case, do not inline css if frappe.local.flags.in_test: return rendered_email return inline_css(rendered_email)
def get_pdf(profile_id, options=None): import pdfkit, os, frappe from frappe.utils import scrub_urls if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) user = get_user_details(profile_id) html = """<div style='border:1px solid black;width:400px;height:238px;align:center'> <div width=100%% ><tr width=100%% > <td width=30%% >Logo</td> <td width=70%% >Name of Application</td></tr><table><hr> </div><table width=100%% ><tr width=100%% ><td width=20%% > <img class='user-picture' src='%(user_image)s' style='min-width:25px;max-width: 70px; min-width:25px; max-height: 70px; border-radius: 4px;margin-top:0%%;margin-left:20%%'/></td> <td width=60%% >Name:%(name)s </br>Blood Group: %(blood_group)s </br>Contact No: %(contact)s </br>Emer Contact:%(emergency_contact)s <br><img src="%(barcode)s"> </td></tr></table></div></div>""" % user if not options.get("page-size"): options['page-size'] = "A4" html = scrub_urls(html) #fname=os.path.join(os.getcwd(), get_site_path().replace('.',"").replace('/', ""), 'public', 'files', profile_id, profile_id +"ed"+ ".pdf") # pdfkit.from_string(html, fname, options=options or {}) fname = os.path.join(get_files_path(), profile_id, profile_id + "ed" + ".pdf") print fname pdfkit.from_string(html, fname, options=options or {}) li = fname.split('/') print li url = get_url() + "/".join(["", li[-3], li[-2], li[-1]]) print url return url
def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None, doc=None): from frappe.utils import scrub_urls if not file_name: file_name = name file_name = file_name.replace(' ', '').replace('/', '-') print_settings = db.get_singles_dict("Print Settings") local.flags.ignore_print_permissions = True if int(print_settings.send_print_as_pdf or 0): out = { "fname": file_name + ".pdf", "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True, doc=doc) } else: out = { "fname": file_name + ".html", "fcontent": scrub_urls( get_print(doctype, name, print_format=print_format, style=style, html=html, doc=doc)).encode("utf-8") } local.flags.ignore_print_permissions = False return out
def get_pdf(html, options=None, output=None): html = scrub_urls(html) html, options = prepare_options(html, options) fname = os.path.join("/tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) options.update({"disable-javascript": "", "disable-local-file-access": ""}) if LooseVersion(get_wkhtmltopdf_version()) > LooseVersion('0.12.3'): options.update({"disable-smart-shrinking": ""}) try: pdfkit.from_string(html, fname, options=options or {}) if output: append_pdf(PdfFileReader(fname), output) else: with open(fname, "rb") as fileobj: filedata = fileobj.read() except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): # allow pdfs with missing images if file got created if os.path.exists(fname): if output: append_pdf(PdfFileReader(file(fname, "rb")), output) else: with open(fname, "rb") as fileobj: filedata = fileobj.read() else: frappe.throw( _("PDF generation failed because of broken image links")) else: raise finally: cleanup(fname, options) if output: return output return filedata
def get_formatted_html(subject, message, footer=None, print_html=None): # imported here to avoid cyclic import message = scrub_urls(message) email_account = get_outgoing_email_account(False) rendered_email = frappe.get_template("templates/emails/standard.html").render( { "content": message, "signature": get_signature(email_account), "footer": get_footer(email_account, footer), "title": subject, "print_html": print_html, "subject": subject, } ) return rendered_email
def attach_print(mail, sent_via, print_html, print_format): name = sent_via.name if not print_html and print_format: print_html = frappe.get_print_format(sent_via.doctype, sent_via.name, print_format) print_settings = frappe.db.get_singles_dict("Print Settings") send_print_as_pdf = cint(print_settings.send_print_as_pdf) if send_print_as_pdf: try: mail.add_pdf_attachment(name.replace(" ", "").replace("/", "-") + ".pdf", print_html) except Exception: frappe.msgprint(_("Error generating PDF, attachment sent as HTML")) frappe.errprint(frappe.get_traceback()) send_print_as_pdf = 0 if not send_print_as_pdf: print_html = scrub_urls(print_html) mail.add_attachment(name.replace(" ", "").replace("/", "-") + ".html", print_html, "text/html")
def attach_print(mail, sent_via, print_html, print_format): name = sent_via.name if not print_html and print_format: print_html = frappe.get_print_format(sent_via.doctype, sent_via.name, print_format) print_settings = frappe.db.get_singles_dict("Print Settings") send_print_as_pdf = cint(print_settings.send_print_as_pdf) if send_print_as_pdf: try: mail.add_pdf_attachment(name.replace(' ','').replace('/','-') + '.pdf', print_html) except Exception: frappe.msgprint(_("Error generating PDF, attachment sent as HTML")) frappe.errprint(frappe.get_traceback()) send_print_as_pdf = 0 if not send_print_as_pdf: print_html = scrub_urls(print_html) mail.add_attachment(name.replace(' ','').replace('/','-') + '.html', print_html, 'text/html')
def get_formatted_letter(title, message, letterhead=None): no_letterhead = True if letterhead: letter_head = frappe.db.get_value("Letter Head", letterhead, "content") no_letterhead = False rendered_letter = frappe.get_template( "templates/letters/standard.html").render({ "content": message, "title": title, "letter_head": letter_head, "no_letterhead": no_letterhead }) html = scrub_urls(rendered_letter) return html
def get_formatted_html(subject, message, footer=None, print_html=None, email_account=None, header=None, unsubscribe_link=None, sender=None): if not email_account: email_account = get_outgoing_email_account(False, sender=sender) rendered_email = frappe.get_template("templates/emails/standard.html").render({ "header": get_header(header), "content": message, "signature": get_signature(email_account), "footer": get_footer(email_account, footer), "title": subject, "print_html": print_html, "subject": subject }) html = scrub_urls(rendered_email) if unsubscribe_link: html = html.replace("<!--unsubscribe link here-->", unsubscribe_link.html) html = inline_style_in_html(html) return html
def test_scrub_urls(self): html = ''' <p>You have a new message from: <b>John</b></p> <p>Hey, wassup!</p> <div class="more-info"> <a href="http://test.com">Test link 1</a> <a href="/about">Test link 2</a> <a href="login">Test link 3</a> <img src="/assets/frappe/test.jpg"> </div> <div style="background-image: url('/assets/frappe/bg.jpg')"> Please mail us at <a href="mailto:[email protected]">email</a> </div> ''' html = scrub_urls(html) url = get_url() self.assertTrue('<a href="http://test.com">Test link 1</a>' in html) self.assertTrue('<a href="{0}/about">Test link 2</a>'.format(url) in html) self.assertTrue('<a href="{0}/login">Test link 3</a>'.format(url) in html) self.assertTrue('<img src="{0}/assets/frappe/test.jpg">'.format(url) in html) self.assertTrue('style="background-image: url(\'{0}/assets/frappe/bg.jpg\') !important"'.format(url) in html) self.assertTrue('<a href="mailto:[email protected]">email</a>' in html)
def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = "<hr>" + set_portal_link(sent_via, d) mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer) if send_me_a_copy: mail.cc.append( frappe.db.get_value("User", frappe.session.user, "email")) if print_html: print_html = scrub_urls(print_html) outgoing_email_settings = frappe.get_doc("Outgoing Email Settings", "Outgoing Email Settings") send_print_as_pdf = cint(outgoing_email_settings.send_print_as_pdf) if send_print_as_pdf: try: options = { 'page-size': outgoing_email_settings.pdf_page_size or 'A4' } mail.add_pdf_attachment( name.replace(' ', '').replace('/', '-') + '.pdf', print_html, options=options) except Exception: frappe.msgprint( _("Error generating PDF, attachment sent as HTML")) send_print_as_pdf = 0 if not send_print_as_pdf: mail.add_attachment( name.replace(' ', '').replace('/', '-') + '.html', print_html, 'text/html') for a in json.loads(attachments): try: mail.attach_file(a) except IOError: frappe.throw(_("Unable to find attachment {0}").format(a)) send(mail)
def get_pdf(profile_id, options=None): import pdfkit, os, frappe from frappe.utils import scrub_urls from phr.templates.pages.dashboard import get_user_details if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) from phr.templates.pages.dashboard import get_user_details user = get_user_details(profile_id) html = """<html lang="en"> <head> <title>Healthsnapp</title> <link rel="stylesheet" href="assets/phr/css/styles.css"> </head> <body> <div class="row"> <div class="card-container"> <div class="card-main"> <div class="card-top"> <div class="card-top-left"> <p class="patient-name">%(name)s</p> <p ><span>%(profile_id)s</span></p> <p class="patient-blood-grp">Blood Group: %(blood_group)s</p> <p class="patient-contact">Contact: %(contact)s</p> <p class="patient-emergncy-contact">Emergency Contact: %(emergency_contact)s</p> <div class="clearfix"></div> </div> <div class="card-top-right"> <div class="card-photo"><img src="%(user_image)s"></div> </div><div class="clearfix"></div> </div> <div class="card-bottom"> <div class="card-logo"> <img src="assets/phr/images/card-logo.png"></div> <div class="card-barcode"><img src="%(barcode)s"> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div> </div> </div> </body> </html>""" % user if not options.get("page-size"): options['page-size'] = "A4" import os, hashlib random_data = os.urandom(128) fname = hashlib.md5(random_data).hexdigest()[:30] html = scrub_urls(html) fname = os.path.join(get_files_path(), profile_id, fname + "ed" + ".pdf") pdfkit.from_string(html, fname, options=options or {}) li = fname.split('/') import time url = get_url() + "/".join(["", li[-3], li[-2], li[-1]]) + '?id=' + str( int(round(time.time() * 1000))) return url
def get_pdf(profile_id,options=None): import pdfkit, os, frappe from frappe.utils import scrub_urls from phr.templates.pages.dashboard import get_user_details if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) from phr.templates.pages.dashboard import get_user_details user = get_user_details(profile_id) html="""<html lang="en"> <head> <title>Healthsnapp</title> <link rel="stylesheet" href="assets/phr/css/styles.css"> </head> <body> <div class="row"> <div class="card-container"> <div class="card-main"> <div class="card-top"> <div class="card-top-left"> <p class="patient-name">%(name)s</p> <p ><span>%(profile_id)s</span></p> <p class="patient-blood-grp">Blood Group: %(blood_group)s</p> <p class="patient-contact">Contact: %(contact)s</p> <p class="patient-emergncy-contact">Emergency Contact: %(emergency_contact)s</p> <div class="clearfix"></div> </div> <div class="card-top-right"> <div class="card-photo"><img src="%(user_image)s"></div> </div><div class="clearfix"></div> </div> <div class="card-bottom"> <div class="card-logo"> <img src="assets/phr/images/card-logo.png"></div> <div class="card-barcode"><img src="%(barcode)s"> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div> </div> </div> </body> </html>"""%user if not options.get("page-size"): options['page-size'] = "A4" import os, hashlib random_data = os.urandom(128) fname = hashlib.md5(random_data).hexdigest()[:30] html = scrub_urls(html) fname = os.path.join(get_files_path(), profile_id, fname+"ed"+".pdf") pdfkit.from_string(html, fname, options=options or {}) li = fname.split('/') import time url = get_url()+"/".join(["",li[-3],li[-2],li[-1]]) +'?id='+str(int(round(time.time() * 1000))) return url
def createDoc(document, repo, path, alfresco_type, mapping_properties): html = frappe.get_print( document.doctype, document.name) fileName = "{name}.pdf".format(name=document.name.replace(" ", "-").replace("/", "-")) print fileName options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) #with open(fname, "rb") as fileobj: #filedata = fileobj.read() fileobj = open(fname, "rb") folder = repo.getObjectByPath("/" + path) #fileName = document.name + ".pdf" properties = {} properties['cmis:objectTypeId'] = "D:"+alfresco_type properties['cmis:name'] = document.name #docu = folder.createDocument(fileName, properties, contentFile=fileobj, contentType="application/pdf") # Hier muss noch die Verarbeitung der Aspects hin props = {} dict = {} default_key = "default" #print mapping_properties for map_det in mapping_properties: if map_det.alfresco_aspect is None or len(map_det.alfresco_aspect.strip()) < 1: props[map_det.alfresco_property] = document.__dict__[map_det.db_field] #properties[map_det.alfresco_property] = document.__dict__[map_det.db_field] if default_key in dict: act_props = dict[default_key] act_props[map_det.alfresco_property] = document.__dict__[map_det.db_field] else: act_props = {} act_props[map_det.alfresco_property] = document.__dict__[map_det.db_field] dict[default_key] = act_props else: alf_aspect_key = map_det.alfresco_aspect if alf_aspect_key in dict: act_props = dict[alf_aspect_key] act_props[map_det.alfresco_property] = document.__dict__[map_det.db_field] else: act_props = {} act_props[map_det.alfresco_property] = document.__dict__[map_det.db_field] dict[alf_aspect_key] = act_props #print frappe.session.user.name for key in dict: if key is default_key: list = dict[key] for listkey in list: #print listkey + ' : '+ list[listkey] properties[listkey] = list[listkey] print fileobj print properties docu = folder.createDocument(fileName, properties, contentFile=fileobj, contentType="application/pdf") #print docu #docu.updateProperties(props) for key in dict: if key is not default_key: print key docu.addAspect('P:'+key) list = dict[key] asp_props = {} for listkey in list: print listkey + ' : '+ list[listkey] asp_props[listkey] = list[listkey] docu.updateProperties(asp_props) os.remove(fname) return docu