# Batch SDK Doc Generation Using Batch Apex

> This class models generating documents in Batch using the SDOC.DocumentSDK.generateDocsInBatch method. To test functionality, open Developer Console > Debug > Execute Anonymous Window > Add:
>
> CallableBatchSolution obj = new CallableBatchSolution();\
> obj.generateBatchDocuments();
>
> Execute

{% stepper %}
{% step %}
**1. Query the Opportunities based on your criteria**

In the example code this is:

```
List<Opportunity> opportunities = [
    SELECT Id 
    FROM Opportunity 
    LIMIT 5
];
```

{% endstep %}

{% step %}
**2. Extract the Opportunity IDs**

In the example code this is:

```
List<Id> oppIDs = new List<Id>();
for (Opportunity opp : opportunities) {
    oppIDs.add(opp.Id);
}
```

{% endstep %}

{% step %}
**3. Set up the S-Docs Template IDs**

In the example code this is:

```
List<SDOC__SDTemplate__c> templates = [
    SELECT Id 
    FROM SDOC__SDTemplate__c 
    WHERE SDOC__Base_Object__c = 'Opportunity' AND SDOC__E_Sign_Vendor__c = NULL AND SDOC__Template_Format__c = 'PDF'
    LIMIT 2 Offset 20
];
```

{% endstep %}

{% step %}
**4. Extract the Template IDs**

In the example code this is:

```
Set<Id> templateIDs = new Set<Id>();
for (SDOC__SDTemplate__c sdtemp : templates) {
    templateIDs.add(sdtemp.Id);
}
```

{% endstep %}

{% step %}
**5. Execute the S-Docs SDK Batch Generation**

In the example code this is:

```
String generatedDocumentAsString = SDOC.DocumentSDK.generateDocsInBatch(
    oppIDs,
    templateIDs, 
    1
    //					REMOVE COMMENTS FROM THIS SECTION TO ENABLE BATCHACTIONS
    //,
    //new List<SDOC.BatchAction> {
    //    new SDOC.CombinedDocumentHandler()
    //}
);
return generatedDocumentAsString;
```

The method signature is generateDocsInBatch(baseRecords, templateIds, n) where:

* baseRecordIds (Type: Id): The list of the records used for generating documents.
* templateIds (Type: Id): The set of IDs of templates to generate.
* batchSize (Type: Integer): The size of each batch in a job. (Default value is 5)
* batchActions (Type: List): List of batch actions to perform on the generated documents.
* CombinedDocumentHandler: Built-in functionality that combines all generated documents into one PDF.
  {% endstep %}
  {% endstepper %}

```java
public class CallableBatchSolution implements System.Callable {
    /**
     * The standard call method for the Callable interface
     * @param action The name of the action to perform
     * @param args A map of arguments passed to the action
     * @return An Object (in this case, the result String from S-Docs)
     */
    public Object call(String action, Map<String, Object> args) {
        switch on action {
            when 'generateBatchDocuments' {
                return this.generateBatchDocuments();
            }
            when else {
                throw new ExtensionMalformedException('Method not implemented');
            }
        }
    }
    public String generateBatchDocuments() {
        // 1. Query the Opportunities based on your criteria
        List<Opportunity> opportunities = [
            SELECT Id 
            FROM Opportunity 
            LIMIT 5
        ];
        // 2. Extract the Opportunity IDS
        List<Id> oppIDs = new List<Id>();
        for (Opportunity opp : opportunities) {
            oppIDs.add(opp.Id);
        }
        // 3. Set up the S-Docs Template IDs
        List<SDOC__SDTemplate__c> templates = [
            SELECT Id 
            FROM SDOC__SDTemplate__c 
            WHERE SDOC__Base_Object__c = 'Opportunity' AND SDOC__E_Sign_Vendor__c = NULL AND SDOC__Template_Format__c = 'PDF'
            LIMIT 2 Offset 20
        ];
        // 4. Extract the Template IDs
        Set<Id> templateIDs = new Set<Id>();
        for (SDOC__SDTemplate__c sdtemp : templates) {
            templateIDs.add(sdtemp.Id);
        }
        // 5. Execute the S-Docs SDK Batch Generation
        // Method Takes in 5 total Params, signature in the form generateDocsInBatch(baseRecords, templateIds, n)
        // baseRecordIds (Type: Id): The list of the records used for generating documents.
        // templateIds (Type: Id): The set of IDs of templates to generate.
        // batchSize (Type: Integer): The size of each batch in a job. (Default value is 5)
        // batchActions (Type: List): List of batch actions to perform on the generated documents.
        // CombinedDocumentHandler The CombinedDocumentHandler is built-in functionality that combines all generated documents into one PDF.
        String generatedDocumentAsString = SDOC.DocumentSDK.generateDocsInBatch(
            oppIDs,
            templateIDs, 
            1
            //					REMOVE COMMENTS FROM THIS SECTION TO ENABLE BATCHACTIONS
            //,
            //new List<SDOC.BatchAction> {
            //    new SDOC.CombinedDocumentHandler()
            //}
        );
        return generatedDocumentAsString;
    }
    public class ExtensionMalformedException extends Exception {}
}
```

### Handling Errors:

To see any errors, Navigate to Setup > Apex Jobs

| **Error**                                  | **Resolution**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Too many queueable jobs added to the queue | Remove the document action from the related list or clone and use a new template. Document Actions within the Template are not supported by the SDK                                                                                                                                                                                                                                                                                                                                                                                                           |
| Apex Heap Size Too Large: ########         | Limit the size of the batch that is processed, limit the number of records that are processed                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| SDOC:Too many SOQL queries: 201            | <p>Salesforce Asynchronous Governor Limit Encountered, limit the number of queries per transaction by limiting the number of records in a single batch.<br><br>Salesforce Governor Limits:<br><br><a href="https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_apexgov.htm"><https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_apexgov.htm></a></p> |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.sdocs.com/developer-hub/document-generation-workflows/apex-and-programmatic-automation/software-development-kit/batch-sdk/batch-sdk-doc-generation-using-batch-apex.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
