0

On a quick action button click(on Account), I have some logic that involves some calculation in apex (not getting stored anywhere as I am not supposed to store it anywhere in the system). Once calculations are done, I am trying to pass on that data as a serialized wrapper to a VF page and get its content and save it as a PDF file. (I can't pass any Id to the VF page as a URL parameter and then try to query it in the VF controller as it's happening within a for loop of child accounts of the selected Parent Account) Since the data getting passed to the VF is hitting the URL parameter character limit.

(I am getting the error 'URL starting with 'https://devorg--devii--c.visualforce.com/apex/oa_statement?data=%7B%22statementTotal%22%3'... is longer than the maximum allowed length of 4,096.' if I try to pass the wrapper data in the URL )

So instead of passing it in the URL, now I am using the post method to pass the data to the VF. Now as a result of the post request, I am not getting the actual VF page content, But instead, I am getting the below as response body and it's getting saved as a corrupted file on the account record.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head></head><body onload="document.forms['workerForm'].submit()">
    <form  accept-charset="UTF-8" action="https://devorg-- 
    devii.my.salesforce.com/visualforce/session" enctype="application/x-www-form-urlencoded" 
       id="workerForm" method="post" name="workerForm" ><input type="hidden" name="url" id="url" 
     value="https://devorg--devii--c.visualforce.com/apex/oa_statement" />
    </form>
    </body>
    </html>

Does anybody have any thought on how to get achieve that?

Here is a simplified version of the VF page that I have. (It's a pretty lengthy one. So I am trying to show only one value from the JSON at first.)

    <apex:page Controller="OA_StatementController" >

<apex:form>

    Hi {!owner}
</apex:form> </apex:page>

Here is the controller of the VF page global class OA_StatementController {

global List<OA_Statement__c> statements  { get; set; }
global List<OA_Property_Transaction__c> expenses  { get; set; }
global Account property { get; set; }
global string owner { get; set; }
global String previousMonthBalance  { get; set; }
global String paymentMade   { get; set; }
global String collectionReceived    { get; set; }
global String netBalance    { get; set; }

global String netSubTotal   { get; set; }
global String statementSubtotal { get; set; }
global String rentalReserve { get; set; }

global String rentalReserveDistribution { get; set; }
global String statementTotal { get; set; }
global String startingBalance { get; set; }
global String endingBalance { get; set; }

global CreateStatement.StatementData data { get; set; }

global string jsonData { get; set; }
global OA_StatementController(){
    Map<String, object> parametersMap=new Map<String, object>();
    parametersMap   =  ApexPages.currentPage().getParameters();
    system.debug('parametersMap '+parametersMap);
    for(String key: parametersMap.keyset()){
        
        if(key=='postDataForm'){
            jsonData = parametersMap.get(key)+'';
        }
        
    }
    data = (CreateStatement.StatementData)System.JSON.deserialize(jsonData, CreateStatement.StatementData.class);
    owner = data.owner;
    endingBalance = data.endingBalance;
     startingBalance = data.startingBalance;
     rentalReserveDistribution = data.rentalReserveDistribution;
     startingBalance = data.startingBalance;
    system.debug(' endingBalance'+endingBalance);
    system.debug(' startingBalance'+startingBalance);
    system.debug(' rentalReserveDistribution'+rentalReserveDistribution);
    system.debug(' startingBalance'+startingBalance);
    system.debug(' owner'+owner);
}

}

Here is the piece of code where I am trying to post the request to the VF page and get the content as a blob and saving it as a PDF file.

        Http http = new Http();
      HttpRequest req = new HttpRequest();
      req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + Page.oa_statement.getUrl());
      
      req.setMethod('POST');
      req.setHeader('content-type', 'application/pdf');
      req.setHeader('Authorization', 'Bearer '+UserInfo.getSessionId());
      req.setHeader('Cookie','sid='+UserInfo.getSessionId()); 
      req.setBody('postDataForm=' + JSON.serialize(data));
      
      HTTPResponse res = http.send(req);
      //get the list of header names (keys)
      string[] headerkeys = res.getHeaderKeys();
      
      //create an object to store your header key-value pairs
      Map<string, string> headers = new map<string, string>();
      
      //iterate through they keys, and populate your map
      for(string s : headerkeys){
          headers.put(s,res.getHeader(s));
         system.debug('header: ' + s + ' value: ' + res.getHeader(s));
      }
     
      boolean redirect = false;
      if(res.getStatusCode() >=300 && res.getStatusCode() <= 307 && res.getStatusCode() != 306) {
        do {
            redirect = false; // reset the value each time
            String loc = res.getHeader('Location'); // get location of the redirect
            system.debug('loc===='+loc);
            if(loc == null) {
                redirect = false;
                continue;
            }
            req = new HttpRequest();
              req.setHeader('content-type', 'application/pdf');
            req.setEndpoint(loc);
            req.setMethod('POST');
            req.setTimeout(12000);
             req.setBody('postDataForm=' + JSON.serialize(data));
              req.setHeader('Cookie','sid='+UserInfo.getSessionId());
            res = http.send(req);
            system.debug('========='+res.getbody());
                                        // Parse entire JSON response.
        }while (redirect && Limits.getCallouts() != Limits.getLimitCallouts());

      }
            
      system.debug(' res '+res);
      Blob body = res.getBodyAsBlob();
       system.debug(' data '+data);
      system.debug(' body'+body);
    
      ContentVersion file = new ContentVersion();
      file.ContentLocation = 'S'; 
      file.PathOnClient = data.owner+'_'+month + year + '.pdf'; 
      file.Title =  data.owner+'_'+month + year ; 
      file.VersionData = body; 
      insert file; 

Any help would be appreciated. Thanks in advance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.