function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rocks_SFDCRocks_SFDC 

How to do i insert pdf file generated by visualforce page into attachments related list.

Hello Everyone,

 

i have a button called "Generate PDF" on Account Detail page. 

Once we click on the button i want to generate a pdf file and want to insert into an attachments related list.

 

Any suggestions would be helpful.

 

Thanks,

Anil

Best Answer chosen by Admin (Salesforce Developers) 
Hengky IlawanHengky Ilawan

Hi,

 

You need to have a separate VF page for the PDF generation and one to put the PDF file into attachment related list.

To put the PDF into attachment, use the getContentAsPDF() method of PageReference class.

 

Assuming the page that generate the PDF file is GeneratePDF, then:

 

PageReference pdfPage = Page.GeneratePDF;
pdfPage.getParameters().put('id', <someid>);

Blob pdfBlob = pdfPage.getContentAsPDF();

Attachment a = new Attachment(
   parentId = <the account id>,
   name = <the attachment name>,
   body = pdfBlob
);
insert(a);

Note that the getContentAsPDF cannot be used in:

 

  • Triggers
  • Scheduled Apex
  • Batch jobs
  • Test methods
  • Apex email services

So when you write your test class, use the isRunningTest() method for checking.

 

Hope it helps.

-Hengky-

All Answers

Hengky IlawanHengky Ilawan

Hi,

 

You need to have a separate VF page for the PDF generation and one to put the PDF file into attachment related list.

To put the PDF into attachment, use the getContentAsPDF() method of PageReference class.

 

Assuming the page that generate the PDF file is GeneratePDF, then:

 

PageReference pdfPage = Page.GeneratePDF;
pdfPage.getParameters().put('id', <someid>);

Blob pdfBlob = pdfPage.getContentAsPDF();

Attachment a = new Attachment(
   parentId = <the account id>,
   name = <the attachment name>,
   body = pdfBlob
);
insert(a);

Note that the getContentAsPDF cannot be used in:

 

  • Triggers
  • Scheduled Apex
  • Batch jobs
  • Test methods
  • Apex email services

So when you write your test class, use the isRunningTest() method for checking.

 

Hope it helps.

-Hengky-

This was selected as the best answer
Rocks_SFDCRocks_SFDC

Thank you khaiwong. I got it.