[SalesForce] Existing file as attachment in visualforce component

This time I would like to ask if anyone was able to add existing document/attachment(PDF) to visualforce template as file attachment?
Of course I mean add as part of logic in template(component). This file must be picked dynamically(there is query for this) but the problem is:
How add it as attachment?
Did any of you implemented something like this?

Best Answer

In Visualforce email template you can use below tag to render content into a PDF attachment in final email.

<messaging:attachment renderAs="PDF" filename="fileName.pdf">
    email attachment content goes here.
</messaging:attachment>

But if you are trying to render an already existing PDF document from say "Documents" in salesforce, you can try below steps

1) Get the content of the document by querying document. 2) Assign this document body to a property(String type) in the controller of visualforce email template. Then use the property inside above mentioned tags.

Generally if you want more control over this kind of scenario, we go for an apex trigger and from trigger we send apex generated email. In this case you can query documents or any other object or even multiple objects and control attachment contents more precisely.

Please try below code to encode the Document body as string suitable for email attachment.It worked for me while reading text Document into apex and rendering as PDF in email,

Public class pdfContentController {
public String pdfBody{get;set;}
    public pdfContentController(){
        Document doc = [select body from document where Id = '01590000008P7xs'];
        pdfBody = EncodingUtil.urlEncode(doc.body.toString(), 'UTF-8');

    }
}

It looks like, if we are reading a PDF document into string, it may not render property because of encryption. But there are some work arounds, please check below, https://developer.salesforce.com/forums/ForumsMain?id=906F00000009DKQIA2