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
Shekhar DautpureShekhar Dautpure 

Generated PDF from VF page is corrupt and doesnt open

Dear All

I have VF page and custom controller. My requirement was to open the page (so that end user can preview the agreement) and then system also save the pdf as attachment on account agaist which it was open. . All goes good ,except the pdf is always currupt . and cannot be opened. Not sure what is missing. 

My Controller :
public with sharing class EAgreementPDFController 
{
    private final Account account;
    private String pdfName;

    public EAgreementPDFController()
    {   
        account = [SELECT Name,BillingStreet,BillingCity,BillingPostalCode,BillingCountry,E_Delivery_Contact_Signing_CP__c,E_Delivery_Pri_Invoice_Signing_CP__c,E_Delivery_Pri_Order_Confirma_Signing_CP__c,E_Delivery_Sec_Invoice_Signing_CP__c,E_Delivery_Sec_Order_Confirmation_CP__c FROM Account WHERE id =:ApexPages.currentPage().getParameters().get('id') LIMIT :(limits.getLimitQueryRows()-limits.getQueryRows())];
       
    }
    
	
    public void AttachAgreement()
    {
    	System.debug(LoggingLevel.FINEST,'Step1- Inside AttachAgreement');
    	 PageReference pdf = Page.EOrderConfirm_Invoice_GeneratedAgreement;
    	 Attachment attach = new Attachment();
    	 Blob body;
    	 try
    	 {
    	 	body = pdf.getContent();
    	 	//body = Blob.valueOf('Test 1233');
    	 }
    	 catch(VisualforceException e)
    	 {
    	 	body = Blob.valueOf('Error encountered while generating agreement. Contact Ecco customer care or your contact person for resolution.');
    	 }
    	 attach.Body = body;
	    // add the user entered name
	    attach.Name = 'Agreement for Edelivery of Invoices and Order Confirmation.pdf';
	    attach.IsPrivate = false;
	    // attach the pdf to the account
	    attach.ParentId = ApexPages.currentPage().getParameters().get('id');
	    insert attach;
    }
    
    public Account getAccount() 
    {
        return account;
    }
    
    public Contact getGeneral_Signature()
    {
    	System.debug(LoggingLevel.FINEST,'Step2- Inside getGeneral_Signature');
        return[Select FirstName,LastName,Title,Phone,Email from Contact where AccountId =:ApexPages.currentPage().getParameters().get('id') and E_ApprovalConfirmationFlag__c=true LIMIT :(limits.getLimitQueryRows()-limits.getQueryRows()) ];
    }
    
    public Contact getPri_Inv()
    {
        return[Select FirstName,LastName,Title,Phone,Email from Contact where AccountId =:ApexPages.currentPage().getParameters().get('id') and E_Invoice_Flag__c=true LIMIT :(limits.getLimitQueryRows()-limits.getQueryRows()) ];
    }
    
    public Contact getSec_Inv()
    {
        return[Select FirstName,LastName,Title,Phone,Email from Contact where AccountId =:ApexPages.currentPage().getParameters().get('id') and Secondary_E_Invoice_Email_Flag__c=true LIMIT :(limits.getLimitQueryRows()-limits.getQueryRows()) ];
    }
    
    public Contact getPri_OC()
    {
        return[Select FirstName,LastName,Title,Phone,Email from Contact where AccountId =:ApexPages.currentPage().getParameters().get('id') and E_Order_Confirmation_Flag__c=true LIMIT :(limits.getLimitQueryRows()-limits.getQueryRows()) ];
    }
    
    public Contact getSec_OC()
    {
        return[Select FirstName,LastName,Title,Phone,Email from Contact where AccountId =:ApexPages.currentPage().getParameters().get('id') and Secondary_E_Order_Confirmation_Email__c=true LIMIT :(limits.getLimitQueryRows()-limits.getQueryRows()) ];
    }
}

and my VF page is :
<apex:page controller="EAgreementPDFController" sidebar="False" renderAs="pdf" showHeader="false" id="AgreementPDF_page" cache="false" action="{!AttachAgreement}">
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"/>
    <apex:includeScript value="https://code.jquery.com/ui/1.12.0-rc.2/jquery-ui.min.js"/>
    <apex:stylesheet value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/themes/ui-lightness/jquery-ui.css" />
    
    
    <apex:form id="form1">
    	<html>
    		<head>
    			<title></title>
                <link rel="stylesheet" href="{!URLFOR($Resource.stylezip)}" />
                <style>
                	body
                	{
                		background:#f7f7f7;
                		height: 1000px;
                	}
                    .topbar1234 
                    {
                            background: #aabccf url('{!$Resource.TopBanner}') repeat-x;
                            height:42px;
                            width:100%;
                            padding-left:50px;
                            padding-top:10px;
                    }                   
                </style>
    		</head>
    		<body>
    		
    			
    			
    			<br/>
    			<br/>
    			<br/>
    				
					<h3>Subject : Agreement for Invoice and Order Confirmation Delivery by Email</h3>
				

    			<br/>
    			<br/>
    			<p>I ,  here by confirm that I on behalf of my employer mentioned below:</p>
    			<p>
    		
    						<apex:outputText value="{!account.Name}"/><br/>
    						<apex:outputText value="{!account.BillingStreet}"/><br/>
    						<apex:outputText value="{!account.BillingCity}"/><br/>
    						<apex:outputText value="{!account.BillingPostalCode}"/><br/>
    						<apex:outputText value="{!account.BillingCountry}"/><br/>
    				
    			</p>
				<p>to approve change in the way of Invoice and Order Confirmation delivery. I approve on behalf of my company that we would like to receive Invocie and Order confirmation by emails and pdf attachemnt, instead of printed copy delivered by postal service. </p>
				<p>For the same, I nominate following collegues are : </p>
				<ul type="circle">
					<li><b><apex:outputText value="{!Pri_Inv.FirstName} {!Pri_Inv.LastName}"/></b>&nbsp;(<apex:outputText value="{!Pri_Inv.Title}"/>)would be "Primary Invoice Receiver" and can be reach at &nbsp;<apex:outputText value="{!Pri_Inv.Email}"/>.<br/></li>
					<li><b><apex:outputText value="{!Sec_Inv.FirstName} {!Sec_Inv.LastName}"/></b>&nbsp;(<apex:outputText value="{!Sec_Inv.Title}"/>) would be "Secondary Invoice Receiver" and can be reach at  &nbsp;<apex:outputText value="{!Sec_Inv.Email}"/>.<br/></li>
					<li><b><apex:outputText value="{!Pri_OC.FirstName} {!Pri_OC.LastName}"/></b>&nbsp;(<apex:outputText value="{!Pri_OC.Title}"/>) would be "Primary Order Confirmation Receiver" and can be reach at  &nbsp;<apex:outputText value="{!Pri_OC.Email}"/>.<br/></li>
					<li><b><apex:outputText value="{!Sec_OC.FirstName} {!Sec_OC.LastName}"/></b>&nbsp;(<apex:outputText value="{!Sec_OC.Title}"/>) would be "Secondary Order Confirmation Receiver" and can be reach at  &nbsp;<apex:outputText value="{!Sec_OC.Email}"/>.<br/></li>
				</ul>
				
				Your Sincerely<br/>
				<b><apex:outputText value="{!General_Signature.FirstName} {!General_Signature.LastName}"/> </b>
				<b><apex:outputText value="{!General_Signature.Title}"/> </b>
				
			</body>  
    	</html>
    </apex:form>
</apex:page>

The whole flow is 

1. Landing page (which is not included above), has a checkbox. On checking the checkbox , from jquery i open the above VF page. In URL i have passed accountid (which works ok)
2. Then the above VF and Controller works

My requirement are 
1. PDF should open for preview --> which open as expected. 
2. PDF should be attached to account --> Which also happens , however when i try to open the attachd PDF , its say that the PDF is currupt. 

thus need you help to spot whats going wrong. 

thanks 
S
priyaSFDCpriyaSFDC
Hi ,

Looks like you are trying to attach the pdf automatically without an additional click of button and hence it looks like you have tried apex:page action method. But the order of action method , getter and setter methods on a page is not gauranteed. I believe thats corrupting your generated attachment.Could you try jquery document.ready event instead and call the AttachAgreement() controller method via an actionFunction.This ensures the pdf content you are trying to attach is completely loaded before you attach it to the record.

Please mark this answer if this resolved your issue.