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
p999_dfsp999_dfs 

PDF Attachment error - File does not begin with '%PDF-'

We want to create a custom button to add PDF Attachement to the object record. We havea visuaforce page which generates a PDF document. We are creating another button on the details page to add this PDf document as a attachment. We want this attachment to be added automatically when user clicks on this button. We do not want to include another intermediate page to get user confirmation.

 

Inititially our page was working when we created a page by just calling the attach method from action on <apex:page> it self.

 

In order to avoid Cross-Site Request Forgery (CSRF), we are trying out the action poler or java script to auto execute the action when detail page button is clicked.

 

It is generating folloiwng error when we try to open the attachment in notes & attachment section

 

File does not begin with '%PDF-'

 

Following is the apex controller code

 

public with sharing class WorkOrderPDFExtensionCon {
	ApexPages.StandardController controller;
	Id id;
	public WorkOrderPDFExtensionCon (ApexPages.StandardController c) {
		 id = ApexPages.currentPage().getParameters().get('id');
		 controller = c;
	}
	public PageReference attachWorkOrder() {
		   WorkOrder__c WO = [Select id, name from WorkOrder__c where id = :id];
		   PageReference pdfPage = Page.gii__WorkOrderPDFDocument;
			PageReference WOPage = new PageReference('/' + id) ;
			WOPage.setRedirect(true);

		   //  set the Work Order id on the page definition 
			pdfPage.getParameters().put('id',id);

			// generate the pdf blob 
			Blob pdfBlob = pdfPage.getContent();
			
			// create the attachment against the Work Order
			Attachment a = new Attachment(parentId = id, name=WO.name + '.pdf', body = pdfBlob);
			// insert the attachment 
			insert a;
			return WOPage;
	  }
}

 

 

Follwoing is the Vf page for with action poler. It is generating error File does not begin with '%PDF-' when attachment is viewed.

 

 

<apex:page standardController="WorkOrder__c"  extensions="WorkOrderPDFExtensionCon" setup="false" sidebar="false">
     <apex:sectionHeader Subtitle="{!WorkOrder__c.name}" title="Attach Work Order"/>                
      <apex:form id="mainform">   
      <apex:actionFunction name="executeAction" action="{!attachWorkOrder}"/>
      <script>window.setTimeout(executeAction,500)</script> 
    </apex:form>
</apex:page>

Gives Error - File does not begin with '%PDF-'

<apex:page standardController="WorkOrder__c"  extensions="WorkOrderPDFExtensionCon" setup="false" sidebar="false">
     <apex:sectionHeader Subtitle="{!WorkOrder__c.name}" title="Attach Work Order"/>                
      <apex:form id="mainform">   
      <apex:actionPoller id="executeAction" action="{!attachWorkOrder}" interval="5"/>
     
    </apex:form>
</apex:page>

Gives Error - File does not begin with '%PDF-'

 

 

And Following code works perfectly when attachment is created by clicking on a button

 

<apex:page standardController="WorkOrder__c"  extensions="WorkOrderPDFExtensionCon" setup="false" sidebar="false">
     <apex:sectionHeader Subtitle="{!WorkOrder__c.name}" title="Attach Work Order"/>                
    <apex:form id="mainform">   
        <apex:pageBlock >
		    Are You Sure :
           <apex:pageBlockSection collapsible="false" title="Attach" columns="2">
                    <br/> Are You Sure ?
           </apex:pageBlockSection>
           <apex:pageBlockButtons location="bottom">  
               <apex:commandButton id="confirm" style="btn" value="{!$Label.Attach}"  action="{!attachWorkOrder}" />&nbsp;&nbsp;
               <apex:commandButton id="cancel" style="btn" value="{!$Label.Cancel}" action="{!cancel}" />
           </apex:pageBlockButtons> 
        </apex:pageBlock>     
    </apex:form>
</apex:page>

 

 

I want to know how we can avoid a intermediate confirmation page witout getting error File does not begin with '%PDF-'. and also what actually this error is and why we are getting this error.

 

Any ideas,, any help is much appreciated.

 

thanks

 

 

 

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
ahab1372ahab1372

so are you getting the error in the test method only or also when you are trying in the UI?

I just ran into a similar problem with testMethod and getContent() which somehow doesn't work. The VF page workes fine invoked in the UI, but fails when called from a testMethod. Only workaround is either

not to test it, or

wrap the getContent() in a try - catch and silently ignore, or

change API to 17 (API 17 ignores all errors regarding getContent)

 

I think this is probably a bug. See my post here:

http://community.salesforce.com/t5/Visualforce-Development/getContent-fails-when-called-from-testMethod/m-p/182645

All Answers

aballardaballard

The error message is coming from the pdf viewer and means that the attachment does not contain a valid pdf.   I suspect if you download it and view it with a plain text editor, you'll find it actually contains an error message or html page containing an error message. 

 

What is the api version of your controller code?  With the latest api version,  errors in pdf generation should get reflected to the original request instead of creating an invalid pdf file. 

 

 

p999_dfsp999_dfs

PI version is 15.0

 

I changed it to 18.0 for VF page and APex controller.

 

I am still getting same error when I am trying to view the attachment. It is a run time error when you try to view then only this error happens.

 

It works fine when I call this action from a button or <apex:page  action="{!AttachPdf}">.

 

I dont know why it does noit work with action poler or java script execute (

<script>window.setTimeout(executeAction,500)</scri pt>

.

ahab1372ahab1372

insert debug statements in your action method and check for the value of the variable id and the pdfPage PageReference. Maybe the context of the Id gets lost because you are calling the method with a delay? Let us know what values these variables have.

 

And you did notice that you a a typo in actionPoller (you are missing one "l")? Also, in your constructor, shouldn't the lines be the other way around?

p999_dfsp999_dfs

Id value is not lost and I can see the id value in debug log.


I had a typo for action poller, I have fixed it, I had type it in manually here.


Also in my test method also I am getting this error

PageReference WOattach = new PageReference('Page.AttachWO');
WOattach.getParameters().put('id',WO.id);    
Test.setCurrentPage(WOattach);
ApexPages.StandardController cont1= new ApexPages.StandardController(WO);
WorkOrderPDFExtensionCon  controller2 = new WorkOrderPDFExtensionCon (cont1);
controller2.attachWODocument();


System.VisualforceException: List has no rows for assignment to SObject


Class.gii.WorkOrderPDFExtensionCon.attachWODocument : line 17, column 24

Line 17 in my controller is

Blob pdfBlob = pdfPage.getContent();

ahab1372ahab1372

so are you getting the error in the test method only or also when you are trying in the UI?

I just ran into a similar problem with testMethod and getContent() which somehow doesn't work. The VF page workes fine invoked in the UI, but fails when called from a testMethod. Only workaround is either

not to test it, or

wrap the getContent() in a try - catch and silently ignore, or

change API to 17 (API 17 ignores all errors regarding getContent)

 

I think this is probably a bug. See my post here:

http://community.salesforce.com/t5/Visualforce-Development/getContent-fails-when-called-from-testMethod/m-p/182645

This was selected as the best answer
p999_dfsp999_dfs

I am getting the erro in testMethod.

But when I call the attach method from VF page with actionPoller then it creates the PDF attachment byt when I try to open the attachment it gives error.

I have changed the API to 17.0 and now it is ignoring the erros.

My test coverage is more than 75% so for time being I am not calling the attach methods. But definitely it looks like a bug with getContent()..

thanks

ahab1372ahab1372

if you cannot open the attachment, then something is still wrong. What happens if you call the pdfPage directly in the browser with a valid record id? Does the PDF come up?

What does the debug log say?

p999_dfsp999_dfs

The visuaforce page shows up correctly when accesses through the browser with record id in the URL.