Create Template

Purpose

Create a new template in Zoho Writer. Use this endpoint to launch a Writer editor session for building reusable templates with merge fields, customizable defaults, permissions, and save callbacks.

Quick Reference

PropertyValue
MethodPOST
Request URLhttps://{api.office-integrator_domain}/writer/officeapi/v1/templates
Content-Typemultipart/form-data

Parameters

Body Parameters

ParameterValueMandatory/OptionalDescription
apikey423s*****MandatoryUniquely identifies the web application in which the Writer editor is integrated.
merge_data_csv_contentFileMandatory (any one)Provide the required CSV content in your API request body.
merge_data_json_contentFileMandatory (any one)Provide the required JSON content in your API request body.
merge_data_csv_urlURLMandatory (any one)Provide the required CSV URL in your API request body.
merge_data_json_urlURLMandatory (any one)Provide the required JSON URL in your API request body.
documentFileOptionalInput file from your local drive or desktop.
urlStringOptionalInput file from a publicly accessible Web URL.
callback_settings{
  "save_format":"zdoc",
  "save_url":<Your Save URL>,
  "http_method_type": "post",
  "retries": <Integer>,
  "timeout": <Integer>,
  "save_url_params": {
                 ....
          }
}
OptionalUsing this param, you will be able to specify the following;
save_format -> Specify the output format in which the edited document needs to be saved.
save_url -> Provide your server location to which the latest content needs to be pushed back when the 'Save' is performed.
The below key values are optional;
http_method_type -> Specify the http method in which the save request has to be triggered.
retries -> Specify the number of retries required when the 'Save' fails.
timeout -> Specify the timeout for the given saveurl.
save_url_params -> To customize the output parameters in which the document details will be pushed from our end.
document_defaults{
  "orientation":"portrait",
  "paper_size":"Letter",
  "font_name":"Lato",
  "font_size":14,
  "track_changes": "disabled",
  "margin": {"left":"1.5in","right":"1.5in","top":"0.25in","bottom":"0.25in"},
  "date_format":"MM/DD/YY"
}
OptionalSet document defaults such as font name and size, custom date format, paper size / orientation, enable/disable track changes and apply custom margins.
editor_settings{
  "unit":"in",
  "language":"en",
  "view":"webview"
}
OptionalSet Editor preferences like Unit in inch/mm, interface language and view as pageview/webview for new documents.
permissions{
  "document.export":true,
  "document.print":true,
  "document.edit":true,
  "review.changes.resolve": false,
  "review.comment":true,
  "collab.chat":true,
  "document.pausecollaboration":false,
  "document.fill":true
}
OptionalDefine document permissions for the users.
document_info{
  "document_name":"New",
  "document_id":"1349"
}
OptionalSet a unique id and specify display name of the new document.
user_info{
  "user_id":"1973",
  "display_name":"Ken"
}
OptionalIdentify the user in the document with "user_id" and "display_name".
ui_options{
  "save_button":"show",
  "chat_panel":"show",
  "dark_mode":"show",
  "file_menu":"show"
}
OptionalSpecify whether the "Save button", "Chat panel", "File menu" and the "Dark mode" option needs to be shown or hidden.

callback_settings

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
save_formatStringMandatoryzdoc / doc / docx / odt / html / pdf and morezdoc
save_urlStringMandatoryURL (max length: 65535)
save_url_paramsJSONOptional

Max 10 keys.

Allowed characters for <additional_user_key> - Alphabets, Numbers, Hyphen, Underscore and Dot. Maximum length - 100 characters

Maximum length of <value> - 2500 characters

http_method_typeStringOptionalpost / putpost
retriesIntegerOptional0 to 30
timeoutIntegerOptional1 to 120000 (ms)120000

save_url Usage

Zoho Office Integrator allows partners and businesses to save the document content back to their specified storage server through the save_url method.

A save_url is a publicly accessible web URL/Service to which Zoho will push the updated document content from Writer editor to the partner's server.

Requirements:

  • Partner's remote servers need to expose one of their ports — port 443 (HTTPS) or port 80 (HTTP) — for Zoho Writer to push the data back.
  • The save_url value specified in the request should be a proper domain name and publicly accessible over the web. Example: https://yourdomain.com/save.php

save_url_params Usage

By default, when 'Save' is performed, the following key names are pushed back:

Key NameTypeDescription
contentFileDocument content will be pushed back in the form of bytes.
filenameStringDocument name
formatStringSpecifies the format in which the document has been exported.

To customize the above key names, use the save_url_params key inside the callback_settings parameter. Once configured, only the key values defined inside will be pushed back to your server. The default key names (like filename and format) will not be included unless you define your own keys using the system variables $format and $filename.

If save_url_params is passed as an empty JSON or the system variable $content is not configured, the document bytes will be pushed back with the multipart name content by default.

Syntax:

"save_url_params": {
    <custom_content_key>: $content,
    <custom_format_key>: $format,
    <custom_filename_key>: $filename,
    <additional_user_key>: <value>,
    <additional_user_key>: <value>,
    ....
    <additional_user_key>: <value>
}

Example:

"save_url_params": {
    file: $content,
    extension: $format,
    document_name: $filename,
    <additional_user_key>: <value>,
    <additional_user_key>: <value>
}

In the above example, the document bytes will be pushed back in the multipart name file, document format in the key name extension, and document filename in the key name document_name.

document_defaults

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
font_nameStringOptionale.g., TrebuchetArial
font_sizeIntegerOptional9 / 10 / 11 / 13 / 16 / 18 (px)12 (px)
orientationStringOptionalportrait / landscapeportrait
paper_sizeStringOptionalLetter / A4 / Legal / ExecutiveLetter
track_changesStringOptionalenabled / disableddisabled
marginJSONOptionalin / mm (e.g., {"left":"1.5in","right":"1.5in","top":"0.25in","bottom":"0.25in"})1in
date_formatStringOptionale.g., EEEE, MMMM DD, YYYY at HH:mmBased on document language

editor_settings

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
unitStringOptionalin / mmin
languageStringOptionalen / de / es / fr / ja / nl and moreen
viewStringOptionalwebview / pageviewpageview

permissions

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
document.exportBooleanOptionaltrue / falsetrue
document.printBooleanOptionaltrue / falsetrue
document.editBooleanOptionaltrue / falsefalse
review.commentBooleanOptionaltrue / falsefalse
review.changes.resolveBooleanOptionaltrue / falsefalse
collab.chatBooleanOptionaltrue / falsetrue
document.pausecollaborationBooleanOptionaltrue / falsefalse
document.fillBooleanOptionaltrue / falsetrue

document_info

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
document_idStringOptionale.g., 24eru24960v
document_nameStringOptionale.g., SampleUntitled

user_info

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
user_idStringOptionale.g., 03588563264
display_nameStringOptionale.g., Ken / James / AdamGuest

ui_options

Parameter/KeysTypeMandatory/OptionalPossible ValuesDefault Value
save_buttonStringOptionalshow / hideshow
chat_panelStringOptionalshow / hideshow
dark_modeStringOptionalshow / hideshow
file_menuStringOptionalshow / hideshow

Notes and Limits

  • Editor customization parameters and their values are case-sensitive.
  • Custom margin is applicable to new documents only.
  • The view parameter under editor_settings is applicable only for new documents.
  • You must provide the merge data in any one of the following formats: merge_data_csv_content, merge_data_json_content, merge_data_csv_url, or merge_data_json_url.
  • You can optionally provide the input file via the document parameter (local file) or url parameter (publicly accessible URL).
  • For possible error codes, refer to: Error Codes
  • For other server-side SDK sample code, refer to: Server-Side SDKs

Sample Request

Copiedcurl -X POST \
  'https://api.office-integrator.com/writer/officeapi/v1/templates' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F 'apikey=423s*****' \
  -F 'document_defaults={"font_size":"12","font_name":"Roboto","orientation":"portrait","paper_size":"A4","track_changes":"disabled","margin": 
       {"left":"1.5in","right":"1.5in","top":"0.25in","bottom":"0.25in"},"date_format":"MM/DD/YY"}' \
  -F 'editor_settings={"unit":"in","language":"en","view":"webview"}' \
  -F 'permissions={'\''document.export'\'':true,'\''document.print'\'':true,'\''document.edit'\'':true,'\''review.changes.resolve'\'':false,'\''review.comment'\'':true,'\''collab.chat'\'':true,'\''document.pausecollaboration'\'':false,'\''document.fill'\'':true }' \
  -F 'callback_settings={"save_format":"docx","save_url":"https://domain.com/save.php"}' \
  -F 'document_info={"document_name":"New","document_id":1349}' \
  -F 'user_info={"user_id":"1973","display_name":"Ken"}' \
  --form "document=@" \
  --form "merge_data_csv_content=@/Users/amelia-1200/Documents/test.csv" \
Copiedimport * as SDK from "@zoho-corp/office-integrator-sdk";
import { readFileSync } from 'fs';
const __dirname = import.meta.dirname;

class CreateMergeTemplate {

    static async execute() {
        
        //Initializing SDK once is enough. Calling here since code sample will be tested standalone. 
        //You can place SDK initializer code in you application and call once while your application start-up. 
        await this.initializeSdk();

        try {
            var sdkOperations = new SDK.V1.V1Operations();
            var templateParameters = new SDK.V1.MailMergeTemplateParameters();
            
            //Either use url as document source or attach the document in request body use below methods
            templateParameters.setUrl("https://demo.office-integrator.com/zdocs/Graphic-Design-Proposal.docx");
            templateParameters.setMergeDataJsonUrl("https://demo.office-integrator.com/data/candidates.json");

            // var fileName = "OfferLetter.zdoc";
            // var filePath = "./sample_documents/OfferLetter.zdoc";
            // var fileStream = readFileSync(filePath);
            // var streamWrapper = new SDK.StreamWrapper(fileName, fileStream, filePath);
            
            // templateParameters.setDocument(streamWrapper);

            // var jsonFileName = "candidates.json";
            // var jsonFilePath = "./sample_documents/candidates.json";
            // var jsonFileStream = readFileSync(jsonFilePath);
            // var jsonStreamWrapper = new SDK.StreamWrapper(jsonFileName, jsonFileStream, jsonFilePath);

            // templateParameters.setMergeDataJsonContent(jsonStreamWrapper);

            var documentInfo = new SDK.V1.DocumentInfo();

            //Time value used to generate unique document everytime. You can replace based on your application.
            documentInfo.setDocumentId("" + new Date().getTime());
            documentInfo.setDocumentName("Graphic-Design-Proposal.docx");

            templateParameters.setDocumentInfo(documentInfo);

            var userInfo = new SDK.V1.UserInfo();

            userInfo.setUserId("1000");
            userInfo.setDisplayName("Amelia");

            templateParameters.setUserInfo(userInfo);

            var margin = new SDK.V1.Margin();

            margin.setTop("2in");
            margin.setBottom("2in");
            margin.setLeft("2in");
            margin.setRight("2in");

            var documentDefaults = new SDK.V1.DocumentDefaults();

            documentDefaults.setFontName("Arial");
            documentDefaults.setFontSize(12);
            documentDefaults.setOrientation("landscape");
            documentDefaults.setPaperSize("A4");
            documentDefaults.setTrackChanges("enabled");
            documentDefaults.setMargin(margin);

            templateParameters.setDocumentDefaults(documentDefaults);

            var editorSettings = new SDK.V1.EditorSettings();

            editorSettings.setUnit("mm");
            editorSettings.setLanguage("en");
            editorSettings.setView("pageview");

            templateParameters.setEditorSettings(editorSettings);

            var permissions = new Map();

            permissions.set("document.export", true);
            permissions.set("document.print", false);
            permissions.set("document.edit", true);
            permissions.set("review.comment", false);
            permissions.set("review.changes.resolve", false);
            permissions.set("collab.chat", false);
            permissions.set("document.pausecollaboration", false);
            permissions.set("document.fill", false);

            templateParameters.setPermissions(permissions);

            var callbackSettings = new SDK.V1.CallbackSettings();
            var saveUrlParams = new Map();

            saveUrlParams.set("auth_token", "1234");
            saveUrlParams.set("id", "123131");

            var saveUrlHeaders = new Map();

            saveUrlHeaders.set("header1", "value1");
            saveUrlHeaders.set("header2", "value2");

            callbackSettings.setSaveUrlParams(saveUrlParams);
            callbackSettings.setSaveUrlHeaders(saveUrlHeaders);

            callbackSettings.setHttpMethodType("post");
            callbackSettings.setRetries(1);
            callbackSettings.setTimeout(100000);
            callbackSettings.setSaveUrl("https://officeintegrator.zoho.com/v1/api/webhook/savecallback/601e12157a25e63fc4dfd4e6e00cc3da2406df2b9a1d84a903c6cfccf92c8286");
            callbackSettings.setSaveFormat("pdf");

            templateParameters.setCallbackSettings(callbackSettings);

            var uiOptions = new SDK.V1.UiOptions();

            uiOptions.setDarkMode("show");
            uiOptions.setSaveButton("show");
            uiOptions.setChatPanel("show");
            uiOptions.setFileMenu("show");

            templateParameters.setUiOptions(uiOptions);

            var responseObject = await sdkOperations.createMailMergeTemplate(templateParameters);

            if(responseObject != null) {
                //Get the status code from response
                console.log("\nStatus Code: " + responseObject.statusCode);
    
                //Get the api response object from responseObject
                let writerResponseObject = responseObject.object;
    
                if(writerResponseObject != null){
    
                    //Check if expected CreateDocumentResponse instance is received
                    if(writerResponseObject instanceof SDK.V1.CreateDocumentResponse){
                        console.log("\nDocument ID - " + writerResponseObject.getDocumentId());
                        console.log("\nDocument session ID - " + writerResponseObject.getSessionId());
                        console.log("\nDocument session URL - " + writerResponseObject.getDocumentUrl());
                        console.log("\nDocument save URL - " + writerResponseObject.getSaveUrl());
                        console.log("\nDocument delete URL - " + writerResponseObject.getDocumentDeleteUrl());
                        console.log("\nDocument session delete URL - " + writerResponseObject.getSessionDeleteUrl());
                    } else if (writerResponseObject instanceof SDK.V1.InvalidConfigurationException) {
                        console.log("\nInvalid configuration exception. Exception json - ", writerResponseObject);
                    } else {
                        console.log("\nRequest not completed successfullly");
                    }
                }
            }
        } catch (error) {
            console.log("\nException while running sample code", error);
        }
    }

    //Include office-integrator-sdk package in your package json and the execute this code.

    static async initializeSdk() {

        // Refer this help page for api end point domain details -  https://www.zoho.com/officeintegrator/api/v1/getting-started.html
        let environment = await new SDK.DataCenter.Production("https://api.office-integrator.com");

        let auth = new SDK.AuthBuilder()
                        .addParam("apikey", "2ae438cf864488657c*******") //Update this apikey with your own apikey signed up in office integrator service
                        .authenticationSchema(await new SDK.V1.Authentication().getTokenFlow())
                        .build();

        let tokens = [ auth ];

        //Sdk application log configuration
        let logger = new SDK.LogBuilder()
            .level(SDK.Levels.INFO)
            //.filePath("<file absolute path where logs would be written>") //No I18N
            .build();

        let initialize = await new SDK.InitializeBuilder();

        await initialize.environment(environment).tokens(tokens).logger(logger).initialize();

        console.log("SDK initialized successfully.");
    }
}

CreateMergeTemplate.execute();

Sample Response

Copied{ 
"document_url": "https://api.office-integrator.com/writer/officeapi/v1/document/d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbcfb7ac1d/edit",
"document_id": "1349", 
"save_url": "https://api.office-integrator.com/writer/officeapi/v1/documents/d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbcfb7ac1d/save", 
"session_id": "d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbcfb7ac1d", 
"session_delete_url": "https://api.office-integrator.com/writer/officeapi/v1/session/d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbcfb7ac1d", 
"document_delete_url": "https://api.office-integrator.com/writer/officeapi/v1/document/1349",
 }