[SalesForce] How to attach the visualforce page pdf

I have a visualforce page renderas="PDF".

But I need to attach this pdf to a record in custom object.

I have custom button to open this pdf but this is just enabled if the checkbox field in record=true.

How can I create this button just if checkbox = true and attach the pdf?

If can help me I appreciate.

Best Answer

On the attaching the PDF part of your question, you can connect your button to a controller method as described in e.g. Call Apex Class From A Custom Button.

To generate the PDF and attach it you can use the getContentAsPDF method and insert the Attachment:

global class MyClass {
    webservice static void attachPdf(Id customObjectId) {
        PageReference pr = Page.YourPageName;
        // Add parameters (if any) passed from the custom button or queried locally
        pr.getParameters().put('id', ...);
        insert new Attachment(
                ParentId = customObjectId,
                Name = 'Whatever Name You Want',
                Body = pr.getContentAsPDF(),
                ContentType = 'application/pdf'
                );
    }
}