def download_multi_pdf(doctype, name, format=None,no_letterhead=None): # name can include names of many docs of the same doctype. import json result = json.loads(name) # Concatenating pdf files output = PdfFileWriter() for i, ss in enumerate(result): output = frappe.get_print(doctype, ss, format, as_pdf = True, output = output, no_letterhead=no_letterhead) frappe.local.response.filename = "{doctype}.pdf".format(doctype=doctype.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = read_multi_pdf(output) frappe.local.response.type = "download"
def download_multi_pdf(doctype, name, format=None): # name can include names of many docs of the same doctype. totalhtml = "" # Pagebreak to be added between each doc html pagebreak = """<p style="page-break-after:always;"></p>""" options = {} import json result = json.loads(name) # Get html of each doc and combine including page breaks for i, ss in enumerate(result): html = frappe.get_print(doctype, ss, format) if i == len(result) - 1: totalhtml = totalhtml + html else: totalhtml = totalhtml + html + pagebreak frappe.local.response.filename = "{doctype}.pdf".format(doctype=doctype.replace(" ", "-").replace("/", "-")) # Title of pdf options.update({"title": doctype}) frappe.local.response.filecontent = get_pdf(totalhtml, options) frappe.local.response.type = "download"
def print_by_server(doctype, name, print_format=None, doc=None, no_letterhead=0): print_settings = frappe.get_doc("Print Settings") try: import cups except ImportError: frappe.throw("You need to install pycups to use this feature!") return try: cups.setServer(print_settings.server_ip) cups.setPort(print_settings.port) conn = cups.Connection() output = PdfFileWriter() output = frappe.get_print(doctype, name, print_format, doc=doc, no_letterhead=no_letterhead, as_pdf = True, output = output) file = os.path.join("/", "tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) output.write(open(file,"wb")) conn.printFile(print_settings.printer_name,file , name, {}) except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): frappe.throw(_("PDF generation failed")) except cups.IPPError: frappe.throw(_("Printing failed")) finally: cleanup(file,{})
def make_salary_slip(source_name, target_doc = None, employee = None, as_print = False, print_format = None): def postprocess(source, target): if employee: employee_details = frappe.db.get_value("Employee", employee, ["employee_name", "branch", "designation", "department"], as_dict=1) target.employee = employee target.employee_name = employee_details.employee_name target.branch = employee_details.branch target.designation = employee_details.designation target.department = employee_details.department target.run_method('process_salary_structure') doc = get_mapped_doc("Salary Structure", source_name, { "Salary Structure": { "doctype": "Salary Slip", "field_map": { "total_earning": "gross_pay", "name": "salary_structure" } } }, target_doc, postprocess, ignore_child_tables=True) if cint(as_print): doc.name = 'Preview for {0}'.format(employee) return frappe.get_print(doc.doctype, doc.name, doc = doc, print_format = print_format) else: return doc
def make_salary_slip(source_name, target_doc=None, employee=None, as_print=False, print_format=None): def postprocess(source, target): if employee: target.employee = employee target.run_method("process_salary_structure") doc = get_mapped_doc( "Salary Structure", source_name, { "Salary Structure": { "doctype": "Salary Slip", "field_map": {"total_earning": "gross_pay", "name": "salary_structure"}, } }, target_doc, postprocess, ignore_child_tables=True, ) if cint(as_print): doc.name = "Preview for {0}".format(employee) return frappe.get_print(doc.doctype, doc.name, doc=doc, print_format=print_format) else: return doc
def download_pdf(doctype, name, format=None): html = frappe.get_print(doctype, name, format) frappe.local.response.filename = "{name}.pdf".format(name=name.replace(" ", "-").replace("/", "-")) options = {} frappe.local.response.filecontent = get_pdf(html,options) frappe.local.response.type = "download"
def make_salary_slip(source_name, target_doc=None, employee=None, as_print=False, print_format=None, for_preview=0, ignore_permissions=False): def postprocess(source, target): if employee: employee_details = frappe.db.get_value( "Employee", employee, [ "employee_name", "branch", "designation", "department", "payroll_cost_center" ], as_dict=1) target.employee = employee target.employee_name = employee_details.employee_name target.branch = employee_details.branch target.designation = employee_details.designation target.department = employee_details.department target.payroll_cost_center = employee_details.payroll_cost_center if not target.payroll_cost_center and target.department: target.payroll_cost_center = frappe.db.get_value( "Department", target.department, "payroll_cost_center") target.run_method('process_salary_structure', for_preview=for_preview) doc = get_mapped_doc("Salary Structure", source_name, { "Salary Structure": { "doctype": "Salary Slip", "field_map": { "total_earning": "gross_pay", "name": "salary_structure", "currency": "currency" } } }, target_doc, postprocess, ignore_child_tables=True, ignore_permissions=ignore_permissions) if cint(as_print): doc.name = 'Preview for {0}'.format(employee) return frappe.get_print(doc.doctype, doc.name, doc=doc, print_format=print_format) else: return doc
def download_pdf(doctype, name, format=None, doc=None, no_letterhead=0): options = {} options.update({'footer-spacing': '0', 'header-spacing': '0'}) html = frappe.get_print(doctype, name, format, doc=doc, no_letterhead=no_letterhead) frappe.local.response.filename = "{name}.pdf".format( name=name.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html, options) frappe.local.response.type = "download"
def dpdf(dt, dn, ft=None, doc=None, nl=0, lh=None, on="Portrait", sn=None): html = frappe.get_print(dt, dn, ft, doc=doc, no_letterhead=nl, letterhead=lh, sign_type=sn) frappe.local.response.filename = "{name}.pdf".format( name=dn.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html, {"orientation": on}) frappe.local.response.type = "pdf"
def write_local_pdf(doctype, docname, print_format, target, language=None): # set language if language: frappe.local.lang = language # get pdf output pdf = get_print(doctype=doctype, name=docname, print_format=print_format, as_pdf=True) # save file with open(target, 'wb') as f: f.write(pdf) return
def create_pdf(doctype, docname, printformat): # create html html = frappe.get_print(doctype, docname, print_format=printformat) # create pdf pdf = frappe.utils.pdf.get_pdf(html) # save and attach pdf now = datetime.now() ts = "{0:04d}-{1:02d}-{2:02d}".format(now.year, now.month, now.day) file_name = "{0}_{1}.pdf".format( ts, docname.replace(" ", "_").replace("/", "_")) save_file(file_name, pdf, doctype, docname, is_private=1) return
def print_to_file(doctype, docname, print_format, dest): output = PdfFileWriter() output = frappe.get_print(doctype, docname, print_format, as_pdf=True, output=output) if dest != None: destdir = os.path.dirname(dest) if destdir != '' and not os.path.isdir(destdir): os.makedirs(destdir) with open(dest, "wb") as w: output.write(w) return
def download_print_at_home_pdf(name): doctype = "Gutschein" format = 'print@home' doc = None no_letterhead = 0 html = frappe.get_print(doctype, name, format, doc=doc, no_letterhead=no_letterhead) frappe.local.response.filename = "{name}.pdf".format( name=name.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html) frappe.local.response.type = "download"
def create_flyer_pdf(name): block = frappe.get_doc("Block", name) # create html html = frappe.get_print("Block", name, print_format=block.flyer_print_format) # create pdf pdf = frappe.utils.pdf.get_pdf(html) # clear attached files remove_all("Block", name) # save and attach pdf file_name = "{0}.pdf".format(name.replace(" ", "_").replace("/", "_")) save_file(file_name, pdf, "Block", name, is_private=0) return
def download_multi_pdf(doctype, name, format=None): # name can include names of many docs of the same doctype. import json result = json.loads(name) # Concatenating pdf files output = PdfFileWriter() for i, ss in enumerate(result): output = frappe.get_print(doctype, ss, format, as_pdf = True, output = output) frappe.local.response.filename = "{doctype}.pdf".format(doctype=doctype.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = read_multi_pdf(output) frappe.local.response.type = "download"
def download_vorschau_pdf(): doctype = "Gutschein" name = 'Gutschein-000001' format = 'Vorschau' doc = None no_letterhead = 0 html = frappe.get_print(doctype, name, format, doc=doc, no_letterhead=no_letterhead) frappe.local.response.filename = "{name}.pdf".format( name=name.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html) frappe.local.response.type = "download"
def download_multi_pdf(doctype, name, format=None, no_letterhead=0): output = PdfFileWriter() if isinstance(doctype, dict): for doctype_name in doctype: for doc_name in doctype[doctype_name]: try: console(doc_name) output = frappe.get_print( doctype_name, doc_name, format, as_pdf=True, output=output, no_letterhead=no_letterhead) except Exception: frappe.log_error("Permission Error on doc {} of doctype {}".format( doc_name, doctype_name)) frappe.local.response.filename = "{}.pdf".format(name) return read_multi_pdf(output)
def download_pdf(doctype, name, format=None, doc=None): opts = { "page-size": "A4", } if doctype in ("Orden de Produccion", ): opts = { "page-size": "Legal", } html = frappe.get_print(doctype, name, format, doc=doc) frappe.local.response.filename = "{name}.pdf".format( name=name.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html, opts) frappe.local.response.type = "download"
def build_long_fiscal_year_print(fiscal_year): fiscal_year = frappe.get_doc("Fiscal Year", fiscal_year) # clear attached files remove_all("Fiscal Year", fiscal_year.name) for c in fiscal_year.companies: # create html if not c.print_format: frappe.log_error( _("Please specify a print format for company {0}", _("Print Fiscal Year") ) ) html = frappe.get_print("Fiscal Year", fiscal_year.name, print_format=c.print_format) # create pdf pdf = frappe.utils.pdf.get_pdf(html) # save and attach pdf file_name = ("{0}_{1}.pdf".format(fiscal_year.name, c.company)).replace(" ", "_").replace("/", "_") save_file(file_name, pdf, "Fiscal Year", fiscal_year.name, is_private=1) return
def create_zugferd_pdf(docname, verify=True, format=None, doc=None, doctype="Sales Invoice", no_letterhead=0): try: html = frappe.get_print(doctype, docname, format, doc=doc, no_letterhead=no_letterhead) pdf = get_pdf(html) xml = create_zugferd_xml(docname) if xml: facturx_pdf = generate_facturx_from_binary(pdf, xml.encode('utf-8')) ## Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration. return facturx_pdf else: # failed to generate xml, fallback return get_pdf(html) except Exception as err: frappe.log_error("Unable to create zugferdPDF for {2}: {0}\n{1}".format(err, xml, docname), "ZUGFeRD") # fallback to normal pdf return get_pdf(html)
def upload_transaction_ts(doctype, docname, pf): dropbox_token = frappe.db.get_value("Dropbox Settings", None, "dropbox_access_token") local_url = "{0}{1}.txt".format(local_io_path, docname) f= open(local_url,"w+") html = frappe.get_print(doctype, docname, pf) html_en = html2text.html2text(html) f.write(html_en.encode('utf-8').strip()) f.close() dbx = dropbox.Dropbox(dropbox_settings['access_token']) conn = dbx.users_get_current_account() try: with open(local_url, "rb") as f: upl = dbx.files_upload(f.read(), '{0}{1}.IN'.format(dropbox_io_path, docname), mute = True) sleep(10) get_algo_signature(doctype, docname) except: return "Upload Failed!!! Something went wrong!!!!"
def get_invoice_merged(invoices, print_format="Sales Invoice SNS"): invoices = ['SINV-SNS-190227-1', 'SINV-SNS-190227-3'] # print_format = frappe.db.get_single_value("Delivery Settings", "dispatch_attachment") attachments = [] from PyPDF2 import PdfFileWriter, PdfFileReader output = PdfFileWriter() for invoice in invoices: output = frappe.get_print("Sales Invoice", invoice, print_format, as_pdf=True, output=output) from frappe.utils.print_format import read_multi_pdf return [{ "fname": "Internal Voucher.pdf", "fcontent": read_multi_pdf(output) }]
def download_multi_pdf(doctype, name, print_format=None, no_letterhead=0): output = PdfFileWriter() if isinstance(doctype, dict): for doctype_name in doctype: for doc_name in doctype[doctype_name]: try: output = frappe.get_print( doctype_name, doc_name, print_format, as_pdf=True, output=output, no_letterhead=no_letterhead, ) except Exception: frappe.log_error(frappe.get_traceback()) return read_multi_pdf(output)
def make_salary_slip(source_name, target_doc=None, employee=None, as_print=False, print_format=None): def postprocess(source, target): if employee: employee_name = frappe.db.get_value("Employee", employee, ["employee_name"], as_dict=1) employee_details = frappe.db.get_value( "Employee", employee, ["branch", "designation", "department"], as_dict=1) target.employee = employee target.employee_name = employee_name.employee_name target.branch = employee_details.branch target.designation = employee_details.designation target.department = employee_details.department target.run_method('process_salary_structure') doc = get_mapped_doc("Salary Structure", source_name, { "Salary Structure": { "doctype": "Salary Slip", "field_map": { "total_earning": "gross_pay", "name": "salary_structure" } } }, target_doc, postprocess, ignore_child_tables=True) if cint(as_print): doc.name = 'Preview for {0}'.format(employee) return frappe.get_print(doc.doctype, doc.name, doc=doc, print_format=print_format) else: return doc
def get_claim_pdf_file(doc): doctype = doc.doctype docname = doc.name default_print_format = frappe.db.get_value( "Property Setter", dict(property="default_print_format", doc_type=doctype), "value", ) if default_print_format: print_format = default_print_format else: print_format = "NHIF Form 2A & B" # print_format = "NHIF Form 2A & B" html = frappe.get_print(doctype, docname, print_format, doc=None, no_letterhead=1) filename = "{name}-claim".format( name=docname.replace(" ", "-").replace("/", "-")) pdf = get_pdf(html) if pdf: ret = frappe.get_doc({ "doctype": "File", "attached_to_doctype": doc.doctype, "attached_to_name": docname, "folder": "Home/Attachments", "file_name": filename + ".pdf", "file_url": "/private/files/" + filename + ".pdf", "content": pdf, "is_private": 1, }) ret.insert(ignore_permissions=True) ret.db_update() if not ret.name: frappe.throw("ret name not exist") base64_data = to_base64(pdf) return base64_data else: frappe.throw(_("Failed to generate pdf"))
def print_by_server(doctype, name, printer_setting, print_format=None, doc=None, no_letterhead=0, file_path=None): print_settings = frappe.get_doc("Network Printer Settings", printer_setting) try: import cups except ImportError: frappe.throw(_("You need to install pycups to use this feature!")) try: cups.setServer(print_settings.server_ip) cups.setPort(print_settings.port) conn = cups.Connection() output = PdfFileWriter() output = frappe.get_print(doctype, name, print_format, doc=doc, no_letterhead=no_letterhead, as_pdf=True, output=output) if not file_path: file_path = os.path.join( "/", "tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) output.write(open(file_path, "wb")) conn.printFile(print_settings.printer_name, file_path, name, {}) except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): frappe.throw(_("PDF generation failed")) except cups.IPPError: frappe.throw(_("Printing failed")) finally: return
def print_bind(sales_invoices, format=None, dest=None): # Concatenating pdf files output = PdfFileWriter() for sales_invoice in sales_invoices: output = frappe.get_print("Sales Invoice", sales_invoice, format, as_pdf = True, output = output) print("append to output") if dest != None: if isinstance(dest, str): # when dest is a file path destdir = os.path.dirname(dest) if destdir != '' and not os.path.isdir(destdir): os.makedirs(destdir) with open(dest, "wb") as w: output.write(w) else: # when dest is io.IOBase output.write(dest) print("first return") return else: print("second return") return output
def geschenk_print_bind(abos, format=None, dest=None): # Concatenating pdf files output = PdfFileWriter() for abo in abos: output = frappe.get_print("Pflanzenfreund Abo", abo, format, as_pdf = True, output = output) print("append to output") if dest != None: if isinstance(dest, str): # when dest is a file path destdir = os.path.dirname(dest) if destdir != '' and not os.path.isdir(destdir): os.makedirs(destdir) with open(dest, "wb") as w: output.write(w) else: # when dest is io.IOBase output.write(dest) print("first return") return else: print("second return") return output
def create_pdf(): doctype = "Sales Invoice" name = "ACC-SINV-2020-00001" format = None doc = None no_letterhead = 0 html = frappe.get_print(doctype, name, format, doc=doc, no_letterhead=no_letterhead) pdf = get_pdf(html) xml = create_zugferd_xml(name) facturxPDF = generate_facturx_from_binary(pdf, xml) newFile = open("filename.pdf", "wb") newFile.write(facturxPDF) return
def make_salary_slip(source_name, target_doc = None, employee = None, as_print = False, print_format = None): def postprocess(source, target): if employee: target.employee = employee target.run_method('process_salary_structure') doc = get_mapped_doc("Salary Structure", source_name, { "Salary Structure": { "doctype": "Salary Slip", "field_map": { "total_earning": "gross_pay", "name": "salary_structure" } } }, target_doc, postprocess, ignore_child_tables=True) if cint(as_print): doc.name = 'Preview for {0}'.format(employee) return frappe.get_print(doc.doctype, doc.name, doc = doc, print_format = print_format) else: return doc
def download_pdf(doctype, name, format=None, doc=None, no_letterhead=0, letterhead=None, orientation="Portrait", sign_type=None): html = frappe.get_print(doctype, name, format, doc=doc, no_letterhead=no_letterhead, letterhead=letterhead, sign_type=sign_type) frappe.local.response.filename = "{name}.pdf".format( name=name.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html, {"orientation": orientation}) frappe.local.response.type = "pdf"
def get_print_content(print_format, doctype, docname, is_escpos=False, is_raw=False): if is_escpos or is_raw: doc = frappe.get_doc(doctype, docname) template = frappe.db.get_value("Print Format", print_format, "html") content = render_template(template, {"doc": doc}) if is_escpos: content.replace("<br>", "<br/>") else: content = frappe.get_print(doctype, docname, print_format) if is_escpos: printer = IOPrinter() printer.receipt(content) raw = printer.get_content() elif is_raw: raw = content else: raw = get_pdf(content) #frappe.msgprint("<pre>%s</pre>" %raw) return b64encode(raw)
def download_mixed_pdf(doctype, name, format=None): # name can include names of many docs of the same doctype. # doctype can include all kind of doctypes import json from collections import OrderedDict doctype_result = json.loads(doctype, object_pairs_hook=OrderedDict) name_result = json.loads(name, object_pairs_hook=OrderedDict) # Concatenating pdf files output = PdfFileWriter() for i, ss in enumerate(name_result): output = frappe.get_print(doctype_result[i], ss, format, as_pdf=True, output=output) frappe.local.response.filename = "{doctype}.pdf".format( doctype=doctype.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = read_multi_pdf(output) frappe.local.response.type = "download"
def attach_print(mail, parent_doc, print_html, print_format): name = parent_doc.name if parent_doc else "attachment" if (not print_html) and parent_doc and print_format: print_html = frappe.get_print(parent_doc.doctype, parent_doc.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_pdf_data(doctype, name): """Document -> HTML -> PDF.""" html = frappe.get_print(doctype, name) return frappe.utils.pdf.get_pdf(html)
def direct_print_doc(doctype, name, print_format, printer_name): pdfcontent = frappe.get_print(doctype, name, print_format, as_pdf=True) direct_print_pdf(pdfcontent, printer_name)
def test_print_user(self, style=None): print_html = frappe.get_print("User", "Administrator", style=style) self.assertTrue("<label>First Name</label>" in print_html) self.assertTrue(re.findall('<div class="col-xs-7[^"]*">[\s]*administrator[\s]*</div>', print_html)) return print_html
def download_pdf(doctype, name, format=None, doc=None, no_letterhead=0): html = frappe.get_print(doctype, name, format, doc=doc, no_letterhead=no_letterhead) frappe.local.response.filename = "{name}.pdf".format(name=name.replace(" ", "-").replace("/", "-")) frappe.local.response.filecontent = get_pdf(html) frappe.local.response.type = "pdf"
def download_multi_pdf(doctype, name, format=None): """ Concatenate multiple docs as PDF . Returns a PDF compiled by concatenating multiple documents. The documents can be from a single DocType or multiple DocTypes Note: The design may seem a little weird, but it exists exists to ensure backward compatibility. The correct way to use this function is to pass a dict to doctype as described below NEW FUNCTIONALITY ================= Parameters: doctype (dict): key (string): DocType name value (list): of strings of doc names which need to be concatenated and printed name (string): name of the pdf which is generated format: Print Format to be used Returns: PDF: A PDF generated by the concatenation of the mentioned input docs OLD FUNCTIONALITY - soon to be deprecated ========================================= Parameters: doctype (string): name of the DocType to which the docs belong which need to be printed name (string or list): If string the name of the doc which needs to be printed If list the list of strings of doc names which needs to be printed format: Print Format to be used Returns: PDF: A PDF generated by the concatenation of the mentioned input docs """ import json output = PdfFileWriter() if not isinstance(doctype, dict): result = json.loads(name) # Concatenating pdf files for i, ss in enumerate(result): output = frappe.get_print(doctype, ss, format, as_pdf = True, output = output) frappe.local.response.filename = "{doctype}.pdf".format(doctype=doctype.replace(" ", "-").replace("/", "-")) else: for doctype_name in doctype: for doc_name in doctype[doctype_name]: try: output = frappe.get_print(doctype_name, doc_name, format, as_pdf = True, output = output) except Exception: frappe.log_error("Permission Error on doc {} of doctype {}".format(doc_name, doctype_name)) frappe.local.response.filename = "{}.pdf".format(name) frappe.local.response.filecontent = read_multi_pdf(output) frappe.local.response.type = "download"