+ Start a Discussion
BellaBella 

Attach VF generated PDF

I have a pdf document generated from fields on an opportunity. I need to then attach it to the opportunity it came from. So far I have code that looks like this:

 

 

Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://c.cs2.visual.force.com/apex/PDF?Id=' + o.Id);
req.setMethod('GET');
HttpResponse res = h.send(req);
Attachment a = new Attachment(Name = 'Attachment Name', ParentId = o.Id, Body = Blob.valueOf(res.getBody()));
insert a;

 

 

When I run it, it clreates an attachment and attaches to the right opportunity, but the attachment itself is not the pdf but rather some small text file that reads:

 

The URL has moved <a href="https://cs2.salesforce.com/visualforce/session?url=https%3A%2F%2Fc.cs2.visual.force.com%2Fapex%2FPDF%3FId%o.Id">here</a>

 

 

Can anyone help me figure out what's going on? Again, all I need to do is take a pdf generated by a vf page and attach it to the coresponding opportunity. Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
ahab1372ahab1372

why so complicated with the http requests? Here is an example from the VF docu:

 

VF PDF attachments

 

in this example they create an email attachment, but you can do the same with an attachment to the opportunity

All Answers

ahab1372ahab1372

why so complicated with the http requests? Here is an example from the VF docu:

 

VF PDF attachments

 

in this example they create an email attachment, but you can do the same with an attachment to the opportunity

This was selected as the best answer
BellaBella

Oh wow that was easy! Just two lines and it works. Thank you!