How to attach a print format to attachments upon saving the Doctype in ERPNext

I am new to ERPNext, I have created a custom print format in ErpNext from the Quotation Doctype.

it gets print and i can download it as pdf as well.

Now what I want is that whenever I save the Quotation Doctype, the pdf of that print format named as Scope of Work to attach in the attachments of Quotations (in the leftside bar of quotation).

Why I am doing this because when I send the quoation in the email, i downlaod the pdf manually when I print it and attach it to the email attachments so that quite and hectic process, everytime I will have to download the pdf and then attach to the email attachments.

Now when that print format will be attached to attachments upon saving the Quotation, and when I will send the email that attachement from quotation will automatically me attached to email attachments and that is what i want.

I was trying custom script but that did not worked as expected so I don’t know may be there is so some good way to achieve this.

My bench version is 14.

Please do this.

Thank you for the reply, but i can’t do this because the “Scope Of Work” is not my default print format, there are other formats I want to attach like “Scope of Work Arabic” another print format.
i need a script or function are whatever, even a custom button will do the job that when I click it, the formats will be attached to the attachments to doctype itlsef in this case the Quotation.

I have solved it by writing a function in quotation.py like below.

def attach_scope_of_work_to_attachments(doc, print_format, pdf_name):
	try:
		pdf_content = frappe.get_print(doc.doctype, doc.name, print_format, as_pdf=True)
			
		file_name = f"{doc.name}_{pdf_name}.pdf"
			
		existing_files = frappe.get_all("File",
            filters={
                "attached_to_doctype": doc.doctype,
                "attached_to_name": doc.name,
                "file_name": file_name
            },fields=["name"])
			
		if existing_files:
			for file_doc in existing_files:
				frappe.delete_doc("File", file_doc.name, force=True)

		file_doc = frappe.get_doc({
       		"doctype": "File",
       		"file_name": file_name,
       		"attached_to_doctype": doc.doctype,
       		"attached_to_name": doc.name,
       		"content": pdf_content,
       		"is_private": 0
   		})


		file_doc.save(ignore_permissions=True)

		doc.add_comment("Attachment", f"{file_doc.file_name} attached.")
			
		return True
	except Exception as e:
		frappe.throw(f"Error generating Scope of Work PDF: {str(e)}")
		return False

and wrote another function after_insert like below

def after_insert(self):
	self.attach_scope_of_work_to_attachments(print_format="Scope Of Work", pdf_name="scope_of_work")
1 Like