Customize create PDF on Quote by Apex

Hi Folks,

Recently I’ve a requirement to create a quote and their quote line items when a opportunity is created with opportunity line items. Along with quote record I need to create “Quote Pdf” in apex code.  And I’ve three quote templates so template selection should be based on some criteria.

Some points to remember :

1) Quote should be enable in your org.

2) Quote template should be in your org and it should be active. You can use standard  and custom template.

3) We can’t get the id of quote template by “Apex code” (as I think) so we need to store the ids of quote template in our custom setting so we can get the id from custom setting.

4) Important: If the creation of  “Quote”,  “Quote line items” and “Quote Pdf “in a single context than you will get error. So we need to break the thread/context and than we can create “Quote Pdf” . So basically first we have to create “Quote” reocrd and then in second thread we can create “Quote Pdf”.  If you already have “Quote”  record than you can easily create “Quote Pdf”.

5) You can get the id of template by Setup–> Customize –>Quotes –> Templates –> Now you can see the templates and click on edit link before the template name and you can get the id of template from URL.(template id will start from “0EH” prefix.

6) The Pdf name will be the name of  Quote Name, we can’t provide it by code.

Now below is your code.

//Id of Quote record.
String QuoteID = '0Q0XXXXXXXXXXX';

//Id of quote Template
String templateID = '0EHXXXXXXXXX';

//This Url create the pdf for quote
String quoteUrl = '/quote/quoteTemplateDataViewer.apexp?id=';

quoteUrl +=QuoteID;

quoteUrl +='&headerHeight=190&footerHeight=188&summlid=';

quoteUrl +=templateID ;

quoteUrl +='#toolbar=1&navpanes=0&zoom=90';

//Create pdf content
PageReference pg = new PageReference(quoteUrl) ;

//Document object of quote which hold the quote pdf
QuoteDocument quotedoc = new QuoteDocument(); 

//Get the content of Pdf.
Blob b = pg.getContentAsPDF() ;

//content assign to document
quotedoc.Document = b;

//assign quote id where pdf should attach
quotedoc.QuoteId = QuoteID ;

//insert the quotdoc
 insert quotedoc; 

I hope this will help you and save your time.


Ashlekh Gera.

Certified Developer.