Create Document

Purpose 

To create a new document in Zoho Writer.  

HTTP Request URL

https://{api.office-integrator_domain}/writer/officeapi/v1/documents

Request Parameters

ParameterValueDescription
Mandatory Parameter
apikey423s*****Uniquely identifies the web application in which the Writer editor is integrated.
callback_settings

{
 "save_format":"zdoc",
 "save_url":<Your Save URL>,
 "http_method_type": "post",
 "retries": <Integer>,
 "timeout": <Integer>,
 "save_url_params": {
                ....
         },

"save_url_headers": {
                <header_key1>: <value1>,
                <header_key2>: <value2>,
                 ….
        }
}

Using 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.

save_url_headers -> Specify the header key values that needs to be pushed back as request headers when the save is triggered.

Optional Parameters - Editor Customization
document_defaults{
 "orientation":"portrait",
 "paper_size":"Letter",
 "font_name":"Lato",
 "font_size":14,
 "track_changes":"disabled",
 "track_changes_mode":"all_markup",
 "margin": {"left":"1.5in","right":"1.5in","top":"0.25in","bottom":"0.25in"}
 "language":"en-US"
}

Set document defaults such as font name and size; paper size / orientation; enable/disable track changes; control track changes mode; apply custom margins.

You can also set a desired language for the document. The document language set will affect the following;

  • Spelling and Grammar suggestions
  • Currency and Number formats
editor_settings{
  "unit":"in", 
  "language":"en",
  "view":"webview"
}
Set 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
}

Define document permissions for the users.
document_info{
 "document_name":"New",
 "document_id":"1349"
}
Set a unique id and specify display name of the new document.
user_info{
  "user_id":"9173",
  "display_name":"Ken"
}
Identify 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"
}
Specify whether the "Save button", "Chat panel", "File menu" and the "Dark mode" option needs to be shown or hidden.

Note

Editor customization parameters and their values are case-sensitive.
Custom margin is applicable to new documents only. 

Editor Customization Parameters

document_defaults

ParameterTypePossible ValuesDefault Value
font_namestringTrebuchetArial
font_sizeinteger9 / 10 / 11 /13 / 16 / 18 (in pixels)12 (in pixels)
orientationstringportrait / landscapeportrait
paper_sizestringLetter, A4, Legal, ExecutiveLetter
track_changesbooleanenabled / disableddisabled
track_changes_modestringall_markup / no_markup / originalall_markup
marginstringin / mm1in
languagestringen-US / af / bn / ca / cs / et and more... en-US

editor_settings

ParameterTypePossible ValuesDefault Value
unitstringin/mmin (inch)
languagestringen/de/es/fr/ja/nl and more... en
viewstringwebview/pageviewpageview
Note: "view" parameter is applicable only for new documents.

permissions

ParameterTypePossible ValuesDefault ValueDescription
document.export   booleantrue / falsetrueTo enable or disable document download option
document.printbooleantrue / falsetrueTo enable or disable document print option
document.editbooleantrue / falsefalseProvide option to allow edit access to the document
review.commentbooleantrue / falsefalseProvide option to manage comments
review.changes.resolvebooleantrue / falsefalseProvide option to resolve track changes
collab.chatbooleantrue / falsetrueTo enable or disable chat panel for the collaborators
document.pausecollaborationbooleantrue / falsefalseProvide option to manage collaboration
document.fillbooleantrue / falsetrueProvide option to allow edit access for the fillable fields

callback_settings

ParameterTypePossible ValuesDefault Value
Mandatory Keys
save_formatstringzdoc / doc / docx / odt / html / pdf and more ...zdoc
save_urlstringURL - Maximum length -> 65535URL
Optional Keys
save_url_paramsJSON
  • Maximum key count - 10
  • Allowed characters for <additional_user_key> - Alphabets, Numbers, Hyphen, Underscore and Dot. Maximum Length - 100 characters
  • Maximum length of <value> - 1000 characters
 
save_url_headersstring
  • Maximum key count - 10
  • Allowed characters for <additional_header_key> - Alphabets, Numbers, Hyphen, Underscore and Dot. Maximum Length - 100 characters
  • Maximum length of <value> - 500 characters
 
http_method_typestringpost / putpost
retriesinteger0 to 30
timeoutinteger1 to 120000 milliseconds120000

document_info

ParameterTypePossible ValuesDefault Value
document_idstring24eru24960v 
document_namestringSampleUntitled

user_info

ParameterTypePossible ValuesDefault Value
user_idinteger03588563264 
display_namestringKen/James/AdamGuest

ui_options

ParameterTypePossible ValuesDefault Value
save_buttonstringshow/hideshow
chat_panelstringshow/hideshow
dark_modestringshow/hideshow
file_menustringshow/hideshow

Create Document - Error Codes

CodeDescription
1831Error occurred. Parameter value is either incorrect or invalid.
1846Invalid API key
1868Invalid parameter name for uploaded content.
1870Margin values exceed page size limit

For a full list of error handling cases in Create Document, refer here.

save_url usage:

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

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

In order to use the saveurl method, partners should fulfill the below requirements:

  1. Partner's remote servers need to expose one of their ports - port 443 (https) or port 80 (http) - from their location, for Zoho Writer to push the data back.
  2. The saveurl value specified in the HTTPS/HTTP POST 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 the 'Save' is performed, we will be pushing back the information with the following key names:

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. 

If you wish to customize the above key names that you need to send back during save call, you can make use of the 'save_url_params' key inside 'callback_settings' parameter.

Once the 'save_url_params' key is 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. To include them, you need to define your own keys for format, filename and session_id by using the system variable $format$filename and $session_id respectively.

If the '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,
      <custom_sessionId_key>: $session_id,
      <additional_user_key>: <value>,
      <additional_user_key>: <value>,
      ....
      <additional_user_key>: <value>
      },

Example:

"save_url_params": {
      file: $content,
      extension: $format,
      document_name: $filename,
      session_id: $session_id,
      <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', document filename in the key name 'document_name' and document session id in the key name 'session_id'

Sample Request

Copied  curl -X POST \
  'https://api.office-integrator.com/writer/officeapi/v1/documents' \
  -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","language":"en-US","margin": {"left":"1.5in","right":"1.5in","top":"0.25in","bottom":"0.25in"}}' \
  -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":"zdoc","save_url":"https://domain.com/save.php"}' \
  -F 'document_info={"document_name":"New","document_id":1349}' \
  -F 'user_info={"user_id":"9173","display_name":"Ken"}' \
  -F 'ui_options={"save_button":"show","chat_panel":"show","dark_mode":"hide","file_menu":"show"}'
Copied//Reference on how to run below sample code: http://zco.to/run-nodejs

const Levels = require("zoi-nodejs-sdk/routes/logger/logger").Levels;
const Constants = require("zoi-nodejs-sdk/utils/util/constants").Constants;
const APIKey = require("zoi-nodejs-sdk/models/authenticator/apikey").APIKey;
const Environment = require("zoi-nodejs-sdk/routes/dc/environment").Environment;
const LogBuilder = require("zoi-nodejs-sdk/routes/logger/log_builder").LogBuilder;
const UserSignature = require("zoi-nodejs-sdk/routes/user_signature").UserSignature;
const InitializeBuilder = require("zoi-nodejs-sdk/routes/initialize_builder").InitializeBuilder;

const Margin = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/margin").Margin;
const UserInfo = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/user_info").UserInfo;
const UiOptions = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/ui_options").UiOptions;
const DocumentInfo = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/document_info").DocumentInfo;
const EditorSettings = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/editor_settings").EditorSettings;
const DocumentDefaults = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/document_defaults").DocumentDefaults;
const CallbackSettings = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/callback_settings").CallbackSettings;
const CreateDocumentResponse = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/create_document_response").CreateDocumentResponse;
const CreateDocumentParameters = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/create_document_parameters").CreateDocumentParameters;
const InvaildConfigurationException = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/invaild_configuration_exception").InvaildConfigurationException;
const V1Operations = require("zoi-nodejs-sdk/core/com/zoho/officeintegrator/v1/v1_operations").V1Operations;

class CreateDocument {

    //Include zoi-nodejs-sdk package in your package json and the execute this code.

    static async initializeSdk() {
        let user = new UserSignature("john@zylker.com");
        let environment = new Environment("https://api.office-integrator.com", null, null);
        let apikey = new APIKey("2ae438c******”, Constants.PARAMS);
        let logger = new LogBuilder()
            .level(Levels.INFO)
            .filePath("./app.log")
            .build();
        let initialize = await new InitializeBuilder();

        await initialize.user(user).environment(environment).token(apikey).logger(logger).initialize();

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

    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 V1Operations();
            var createDocumentParameters = new CreateDocumentParameters();

            var documentInfo = new DocumentInfo();

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

            createDocumentParameters.setDocumentInfo(documentInfo);

            var userInfo = new UserInfo();

            userInfo.setUserId("1000");
            userInfo.setDisplayName(“John”);

            createDocumentParameters.setUserInfo(userInfo);

            var margin = new Margin();

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

            var documentDefaults = new DocumentDefaults();

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

            documentDefaults.setMargin(margin);
            documentDefaults.setLanguage("ta");

            createDocumentParameters.setDocumentDefaults(documentDefaults);

            var editorSettings = new EditorSettings();

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

            createDocumentParameters.setEditorSettings(editorSettings);

            var uiOptions = new UiOptions();

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

            createDocumentParameters.setUiOptions(uiOptions);

            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);

            createDocumentParameters.setPermissions(permissions);

            var callbackSettings = new 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.setRetries(1);
            callbackSettings.setSaveFormat("zdoc");
            callbackSettings.setHttpMethodType("post");
            callbackSettings.setTimeout(100000);
            callbackSettings.setSaveUrl("https://domain.com/save.php"); 
// To implement your save callback url, refer here: https://github.com/iampraba/zoi-nodejs-sdk-examples/tree/e922ddcd9ae425e521aa2465dda614116d0f205f/save-callback-implementation/express-js

            createDocumentParameters.setCallbackSettings(callbackSettings);

            var responseObject = await sdkOperations.createDocument(createDocumentParameters);

            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 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 InvaildConfigurationException) {
                        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);
        }
    }
}

CreateDocument.execute();
Copied//Reference on how to run below sample code: http://zco.to/run-java

package com.zoho.officeintegrator.v1.examples.writer;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import com.zoho.Initializer;
import com.zoho.UserSignature;
import com.zoho.api.authenticator.APIKey;
import com.zoho.api.logger.Logger;
import com.zoho.api.logger.Logger.Levels;
import com.zoho.dc.ZOIEnvironment;
import com.zoho.officeintegrator.v1.CallbackSettings;
import com.zoho.officeintegrator.v1.CreateDocumentParameters;
import com.zoho.officeintegrator.v1.CreateDocumentResponse;
import com.zoho.officeintegrator.v1.DocumentDefaults;
import com.zoho.officeintegrator.v1.DocumentInfo;
import com.zoho.officeintegrator.v1.EditorSettings;
import com.zoho.officeintegrator.v1.InvaildConfigurationException;
import com.zoho.officeintegrator.v1.Margin;
import com.zoho.officeintegrator.v1.UiOptions;
import com.zoho.officeintegrator.v1.UserInfo;
import com.zoho.officeintegrator.v1.V1Operations;
import com.zoho.officeintegrator.v1.WriterResponseHandler;
import com.zoho.util.APIResponse;

public class CreateDocument {

	private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(CreateDocument.class.getName());

	public static void main(String args[]) {
		
		try {
			//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. 
			initializeSdk();

			V1Operations sdkOperations = new V1Operations();
			CreateDocumentParameters createDocumentParams = new CreateDocumentParameters();
			
			DocumentInfo documentInfo = new DocumentInfo();
			
			documentInfo.setDocumentName("Untilted Document");
			//System time value used to generate unique document everytime. You can replace based on your application.
			documentInfo.setDocumentId("" + System.currentTimeMillis());
			
			createDocumentParams.setDocumentInfo(documentInfo);
			
			UserInfo userInfo = new UserInfo();
			
			userInfo.setUserId("1000");
			userInfo.setDisplayName("John");
			
			createDocumentParams.setUserInfo(userInfo);

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

			DocumentDefaults documentDefault = new DocumentDefaults();
			
			documentDefault.setFontSize(14);
			documentDefault.setFontName("Arial");
			documentDefault.setPaperSize("Letter");
			documentDefault.setOrientation("portrait");
			documentDefault.setTrackChanges("disabled");
			
			documentDefault.setMargin(margin);
			createDocumentParams.setDocumentDefaults(documentDefault);
			
			EditorSettings editorSettings = new EditorSettings();
			
			editorSettings.setUnit("in");
			editorSettings.setLanguage("en");
			editorSettings.setView("pageview");
			
			createDocumentParams.setEditorSettings(editorSettings);
			
			UiOptions uiOptions = new UiOptions();
			
			uiOptions.setChatPanel("show");
			uiOptions.setDarkMode("show");
			uiOptions.setFileMenu("show");
			uiOptions.setSaveButton("show");
			
			createDocumentParams.setUiOptions(uiOptions);
			
			Map<String, Object> permissions = new HashMap<String, Object>();
			
			permissions.put("collab.chat", false);
                       permissions.put("document.edit", true);
                       permissions.put("review.comment", false);
                       permissions.put("document.export", true);
			permissions.put("document.print", false);
			permissions.put("document.fill", false);
                       permissions.put("review.changes.resolve", false);
                       permissions.put("document.pausecollaboration", false);
            
			createDocumentParams.setPermissions(permissions);
			
			Map<String, Object> saveUrlParams = new HashMap<String, Object>();
			
			saveUrlParams.put("id", 123456789);
			saveUrlParams.put("auth_token", "oswedf32ru”);
			
			
			CallbackSettings callbackSettings = new CallbackSettings();
			
			callbackSettings.setRetries(2);
			callbackSettings.setTimeout(10000);
			callbackSettings.setSaveFormat("docx");
			callbackSettings.setHttpMethodType("post");
			callbackSettings.setSaveUrlParams(saveUrlParams);
			callbackSettings.setSaveUrl("https://domain.com/save.php");  // Enter your server location
			
			createDocumentParams.setCallbackSettings(callbackSettings);
			
			APIResponse<WriterResponseHandler> response =  sdkOperations.createDocument(createDocumentParams);
			int responseStatusCode = response.getStatusCode();
			
			if ( responseStatusCode >= 200 && responseStatusCode <= 299 ) {
				CreateDocumentResponse documentResponse = (CreateDocumentResponse) response.getObject();

				LOGGER.log(Level.INFO, "Document id - {0}", new Object[] { documentResponse.getDocumentId() }); //No I18N
				LOGGER.log(Level.INFO, "Document session id - {0}", new Object[] { documentResponse.getSessionId() }); //No I18N
				LOGGER.log(Level.INFO, "Document session url - {0}", new Object[] { documentResponse.getDocumentUrl() }); //No I18N
			} else {
				InvaildConfigurationException invalidConfiguration = (InvaildConfigurationException) response.getObject();
				String errorMessage = invalidConfiguration.getMessage();
				
				/*Long errorCode = invalidConfiguration.getCode();
				String errorKeyName = invalidConfiguration.getKeyName();
				String errorParameterName = invalidConfiguration.getParameterName();*/
				
				LOGGER.log(Level.INFO, "Document configuration error - {0}", new Object[] { errorMessage }); //No I18N
			}
			
		} catch (Exception e) {
			LOGGER.log(Level.INFO, "Exception in creating document session url - ", e); //No I18N
		}
	}
	
	public static boolean initializeSdk() {
		boolean status = false;

		try {
			APIKey apikey = new APIKey("2ae438cf864488657cc9******);
	        UserSignature user = new UserSignature("john@zylker.com"); //No I18N
	        Logger logger = new Logger.Builder()
						        .level(Levels.INFO)
						        //.filePath("<file absolute path where logs would be written>") //No I18N
						        .build();

	        ZOIEnvironment.setProductionUrl("https://api.office-integrator.com/");

			new Initializer.Builder()
				.user(user)
				.environment(ZOIEnvironment.PRODUCTION)
				.token(apikey)
				.logger(logger)
				.initialize();
			
			status = true;
		} catch (Exception e) {
			LOGGER.log(Level.INFO, "Exception in creating document session url - ", e); //No I18N
		}
		return status;
	}
}
Copied#Reference on how to run below sample code: http://zco.to/run-php

<?php
namespace com\zoho\officeintegrator\v1\writer;

require_once dirname(__FILE__) . '/../vendor/autoload.php';

use com\zoho\api\authenticator\APIKey;
use com\zoho\api\logger\Levels;
use com\zoho\api\logger\LogBuilder;
use com\zoho\dc\DataCenter;
use com\zoho\InitializeBuilder;
use com\zoho\officeintegrator\v1\CallbackSettings;
use com\zoho\officeintegrator\v1\CreateDocumentResponse;
use com\zoho\officeintegrator\v1\InvalidConfigurationException;
use com\zoho\UserSignature;
use com\zoho\util\Constants;
use com\zoho\officeintegrator\v1\CreateDocumentParameters;
use com\zoho\officeintegrator\v1\DocumentDefaults;
use com\zoho\officeintegrator\v1\DocumentInfo;
use com\zoho\officeintegrator\v1\EditorSettings;
use com\zoho\officeintegrator\v1\Margin;
use com\zoho\officeintegrator\v1\UiOptions;
use com\zoho\officeintegrator\v1\UserInfo;
use com\zoho\officeintegrator\v1\V1Operations;
use Exception;

class CreateDocument {

    // Refer API documentation - https://www.zoho.com/officeintegrator/api/v1/zoho-writer-create-document.html
    public static function execute() {
        // Initializing SDK once is enough. Calling here since the code sample will be tested standalone. 
        // You can place SDK initializer code in your application and call it once while your application starts up.
        self::initializeSdk();

        try {
            $sdkOperations = new V1Operations();
            $createDocumentParameters = new CreateDocumentParameters();

            # Optional Configuration - Add document meta in request to identify the file in Zoho Server
            $documentInfo = new DocumentInfo();

            // Time value used to generate a unique document every time. You can replace it based on your application.
            $documentInfo->setDocumentId(strval(time()));
            $documentInfo->setDocumentName("New Document");

            $createDocumentParameters->setDocumentInfo($documentInfo);

            # Optional Configuration - Add User meta in request to identify the user in document session
            $userInfo = new UserInfo();

            $userInfo->setUserId("1000");
            $userInfo->setDisplayName(“John”);

            $createDocumentParameters->setUserInfo($userInfo);

            # Optional Configuration 
            $margin = new Margin();

            $margin->setTop("2in");
            $margin->setBottom("2in");
            $margin->setLeft("2in");
            $margin->setRight("2in");

            # Optional Configuration 
            $documentDefaults = new DocumentDefaults();

            $documentDefaults->setFontSize(12);
            $documentDefaults->setPaperSize("A4");
            $documentDefaults->setFontName("Arial");
            $documentDefaults->setTrackChanges("enabled");
            $documentDefaults->setOrientation("landscape");

            $documentDefaults->setMargin($margin);
            $documentDefaults->setLanguage("ta");

            $createDocumentParameters->setDocumentDefaults($documentDefaults);

            # Optional Configuration 
            $editorSettings = new EditorSettings();

            $editorSettings->setUnit("in");
            $editorSettings->setLanguage("en");
            $editorSettings->setView("pageview");

            $createDocumentParameters->setEditorSettings($editorSettings);

            # Optional Configuration 
            $uiOptions = new UiOptions();

            $uiOptions->setDarkMode("show");
            $uiOptions->setFileMenu("show");
            $uiOptions->setSaveButton("show");
            $uiOptions->setChatPanel("show");

            $createDocumentParameters->setUiOptions($uiOptions);

            # Optional Configuration 
            $permissions = array();

            $permissions["document.export"] = true;
            $permissions["document.print"] = false;
            $permissions["document.edit"] = true;
            $permissions["review.comment"] = false;
            $permissions["review.changes.resolve"] = false;
            $permissions["collab.chat"] = false;
            $permissions["document.pausecollaboration"] = false;
            $permissions["document.fill"] = false;

            $createDocumentParameters->setPermissions($permissions);

            # Optional Configuration - Add callback settings to configure.
            # how file needs to be received while saving the document
            $callbackSettings = new CallbackSettings();

            # Optional Configuration - configure additional parameters
            # which can be received along with document while save callback
            $saveUrlParams = array();

            $saveUrlParams["param1"] = "value1";
            $saveUrlParams["param2"] = "value2";

            $callbackSettings->setSaveUrlParams($saveUrlParams);
            
            # Optional Configuration - configure additional headers
            # which could be received in callback request headers while saving document
            $saveUrlHeaders = array();

            $saveUrlHeaders["header1"] = "value1";
            $saveUrlHeaders["header2"] = "value2";

            $callbackSettings->setSaveUrlHeaders($saveUrlHeaders);

            $callbackSettings->setRetries(1);
            $callbackSettings->setSaveFormat("zdoc");
            $callbackSettings->setHttpMethodType("post");
            $callbackSettings->setTimeout(100000);
            $callbackSettings->setSaveUrl("https://domain.com/save.php"); 
// To implement your save callback url, refer here: https://github.com/iampraba/zoi-php-sdk-examples/tree/eeb5994f70125d264aa98091c1efdd547219b615/save_callback_implementation

            $createDocumentParameters->setCallbackSettings($callbackSettings);

            $responseObject = $sdkOperations->createDocument($createDocumentParameters);

            if ($responseObject != null) {
                // Get the status code from response
                echo "\nStatus Code: " . $responseObject->getStatusCode() . "\n";

                // Get the api response object from responseObject
                $writerResponseObject = $responseObject->getObject();

                if ($writerResponseObject != null) {
                    // Check if the expected CreateDocumentResponse instance is received
                    if ($writerResponseObject instanceof CreateDocumentResponse) {
                        echo "\nDocument ID - " . $writerResponseObject->getDocumentId() . "\n";
                        echo "\nDocument session ID - " . $writerResponseObject->getSessionId() . "\n";
                        echo "\nDocument session URL - " . $writerResponseObject->getDocumentUrl() . "\n";
                        echo "\nDocument save URL - " . $writerResponseObject->getSaveUrl() . "\n";
                        echo "\nDocument delete URL - " . $writerResponseObject->getDocumentDeleteUrl() . "\n";
                        echo "\nDocument session delete URL - " . $writerResponseObject->getSessionDeleteUrl() . "\n";
                    } elseif ($writerResponseObject instanceof InvalidConfigurationException) {
                        echo "\nInvalid configuration exception." . "\n";
                        echo "\nError Code - " . $writerResponseObject->getCode() . "\n";
                        echo "\nError Message - " . $writerResponseObject->getMessage() . "\n";
                        if ( $writerResponseObject->getKeyName() ) {
                            echo "\nError Key Name - " . $writerResponseObject->getKeyName() . "\n";
                        }
                        if ( $writerResponseObject->getParameterName() ) {
                            echo "\nError Parameter Name - " . $writerResponseObject->getParameterName() . "\n";
                        }
                    } else {
                        echo "\nRequest not completed successfully\n";
                    }
                }
            }
        } catch (Exception $error) {
            echo "\nException while running sample code: " . $error . "\n";
        }
    }

    public static function initializeSdk() {
        // Replace email address associated with your apikey below
        $user = new UserSignature("john@zylker.com");
        # Update the api domain based on in which data center user register your apikey
        # To know more - https://www.zoho.com/officeintegrator/api/v1/getting-started.html
        $environment = DataCenter::setEnvironment("https://api.office-integrator.com", null, null, null);
        # User your apikey that you have in office integrator dashboard
        $apikey = new APIKey("2ae438cf864488657cc9******”, Constants::PARAMS);
        # Configure a proper file path to write the sdk logs
        $logger = (new LogBuilder())
            ->level(Levels::INFO)
            ->filePath("./app.log")
            ->build();
        
        (new InitializeBuilder())
            ->user($user)
            ->environment($environment)
            ->token($apikey)
            ->logger($logger)
            ->initialize();

        echo "SDK initialized successfully.\n";
    }
}

CreateDocument::execute();
?>
Copied//Reference on how to run below sample code: http://zco.to/run-csharp

using System;
using Com.Zoho.Util;
using Com.Zoho.Officeintegrator.V1;
using Com.Zoho;
using Com.Zoho.Dc;
using Com.Zoho.API.Authenticator;
using Com.Zoho.API.Logger;
using static Com.Zoho.API.Logger.Logger;
using System.Collections.Generic;

namespace Documents
{
    class CreateDocument
    {
        static void Main(String[] args)
        {
            try
            {
                // Initializing SDK once is enough. Calling here since code sample will be tested standalone. 
                // You can place SDK initializer code in your application and call once while your application start-up.
                initializeSdk();

                V1Operations sdkOperations = new V1Operations();
                CreateDocumentParameters createDocumentParams = new CreateDocumentParameters();

                DocumentInfo documentInfo = new DocumentInfo();

                documentInfo.DocumentName = "Untilted Document";
                // System time value used to generate unique document every time. You can replace based on your application.
                documentInfo.DocumentId = $"{DateTimeOffset.Now.ToUnixTimeMilliseconds()}";

                createDocumentParams.DocumentInfo = documentInfo;

                UserInfo userInfo = new UserInfo();

                userInfo.UserId = "1000";
                userInfo.DisplayName = "John";

                createDocumentParams.UserInfo = userInfo;

                Margin margin = new Margin();

                margin.Top = "2in";
                margin.Bottom = "2in";
                margin.Left = "2in";
                margin.Right = "2in";

                DocumentDefaults documentDefault = new DocumentDefaults();

                documentDefault.FontSize = 14;
                documentDefault.FontName = "Arial";
                documentDefault.PaperSize = "Letter";
                documentDefault.Orientation = "portrait";
                documentDefault.TrackChanges = "disabled";

                documentDefault.Margin = margin;
                createDocumentParams.DocumentDefaults = documentDefault;

                EditorSettings editorSettings = new EditorSettings();

                editorSettings.Unit = "in";
                editorSettings.Language = "en";
                editorSettings.View = "pageview";
                createDocumentParams.EditorSettings = editorSettings;

                UiOptions uiOptions = new UiOptions();

                uiOptions.ChatPanel = "show";
                uiOptions.DarkMode = "show";
                uiOptions.FileMenu = "show";
                uiOptions.SaveButton = "show";

                createDocumentParams.UiOptions = uiOptions;

                Dictionary<string, object> permissions = new Dictionary<string, object>();

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

                createDocumentParams.Permissions = permissions;

                Dictionary<string, object> saveUrlParams = new Dictionary<string, object>();

                saveUrlParams.Add("id", 123456789);
                saveUrlParams.Add("auth_token", "oswedf32rk");

                Dictionary<string, object> saveUrlHeaders = new Dictionary<string, object>();

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

                CallbackSettings callbackSettings = new CallbackSettings();

                callbackSettings.Retries = 2;
                callbackSettings.Timeout = 10000;
                callbackSettings.SaveFormat = "docx";
                callbackSettings.HttpMethodType = "post";
                callbackSettings.SaveUrlParams = saveUrlParams;
                callbackSettings.SaveUrlHeaders = saveUrlHeaders;
                callbackSettings.SaveUrl = "https://domain.com/save.php"); 
// To implement your save callback url, refer here: https://github.com/iampraba/zoi-csharp-sdk-examples/blob/f71b0e1fe3b45052ad1365ec32c3e09a22113aa6/SaveCallbackHandler.cs

                createDocumentParams.CallbackSettings = callbackSettings;

                APIResponse<WriterResponseHandler> response = sdkOperations.CreateDocument(createDocumentParams);
                int responseStatusCode = response.StatusCode;

                if (responseStatusCode >= 200 && responseStatusCode <= 299)
                {
                    CreateDocumentResponse documentResponse = (CreateDocumentResponse)response.Object;

                    Console.WriteLine("Document id - {0}", documentResponse.DocumentId);
                    Console.WriteLine("Document session id - {0}", documentResponse.SessionId);
                    Console.WriteLine("Document session url - {0}", documentResponse.DocumentUrl);
                }
                else
                {
                    InvalidConfigurationException invalidConfiguration = (InvalidConfigurationException)response.Object;
                    string errorMessage = invalidConfiguration.Message;

                    /*long errorCode = invalidConfiguration.Code;
                    string errorKeyName = invalidConfiguration.KeyName;
                    string errorParameterName = invalidConfiguration.ParameterName;*/

                    Console.WriteLine("configuration error - {0}", errorMessage);
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Exception in creating document session url - ", e);
            }
        }

        static Boolean initializeSdk()
        {
            Boolean status = false;

            try
            {
                Apikey apikey = new Apikey("2ae438cf864488657cc975*****”*, Com.Zoho.Util.Constants.PARAMS);
                UserSignature user = new UserSignature("john@zylker.com"); //No I18N
                Logger logger = new Logger.Builder()
                                    .Level(Levels.INFO)
                                    .FilePath("./log.txt") //No I18N
                                    .Build();

                Com.Zoho.Dc.DataCenter.Environment environment = new DataCenter.Environment("", "https://api.office-integrator.com", "", "");

                new Initializer.Builder()
                    .User(user)
                    .Environment(environment)
                    .Token(apikey)
                    .Logger(logger)
                    .Initialize();
                status = true;
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Exception in Init SDK", e);
            }
            return status;
        }
    }
}
Copied#Reference on how to run below sample code: http://zco.to/run-python

from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
from zohosdk.src.com.zoho.user_signature import UserSignature
from zohosdk.src.com.zoho.dc.data_center import DataCenter
from zohosdk.src.com.zoho.api.authenticator.api_key import APIKey
from zohosdk.src.com.zoho.util.constants import Constants
from zohosdk.src.com.zoho.api.logger import Logger
from zohosdk.src.com.zoho import Initializer

from zohosdk.src.com.zoho.officeintegrator.v1 import DocumentInfo, UserInfo, Margin, DocumentDefaults, EditorSettings, \
    UiOptions, CallbackSettings, InvalidConfigurationException
from zohosdk.src.com.zoho.officeintegrator.v1.create_document_parameters import CreateDocumentParameters
from zohosdk.src.com.zoho.officeintegrator.v1.create_document_response import CreateDocumentResponse
from zohosdk.src.com.zoho.officeintegrator.v1.v1_operations import V1Operations

import time


class CreateDocument:

    # Refer API documentation - https://www.zoho.com/officeintegrator/api/v1/zoho-writer-create-document.html
    @staticmethod
    def execute():
        CreateDocument.init_sdk()
        createDocumentParams = CreateDocumentParameters()

        # Optional Configuration - Add document meta in request to identify the file in Zoho Server
        documentInfo = DocumentInfo()
        documentInfo.set_document_name("New Document")
        documentInfo.set_document_id((round(time.time() * 1000)).__str__())

        createDocumentParams.set_document_info(documentInfo)

        # Optional Configuration - Add User meta in request to identify the user in document session
        userInfo = UserInfo()
        userInfo.set_user_id("1000")
        userInfo.set_display_name(“John)

        createDocumentParams.set_user_info(userInfo)

        # Optional Configuration - Add callback settings to configure.
        # how file needs to be received while saving the document
        callbackSettings = CallbackSettings()

        # Optional Configuration - configure additional parameters
        # which can be received along with document while save callback
        saveUrlParams = {}

        saveUrlParams['id'] = '123131'
        saveUrlParams['auth_token'] = '1234'
        # Following $<> values will be replaced by actual value in callback request
        # To know more - https://www.zoho.com/officeintegrator/api/v1/zoho-writer-create-document.html#saveurl_params
        saveUrlParams['extension'] = '$format'
        saveUrlParams['document_name'] = '$filename'
        saveUrlParams['session_id'] = '$session_id'

        callbackSettings.set_save_url_params(saveUrlParams)

        # Optional Configuration - configure additional headers
        # which could be received in callback request headers while saving document
        saveUrlHeaders = {}

        saveUrlHeaders['access_token'] = '12dweds32r42wwds24'
        saveUrlHeaders['client_id'] = '12313111'

        callbackSettings.set_save_url_headers(saveUrlHeaders)

        callbackSettings.set_retries(1)
        callbackSettings.set_timeout(10000)
        callbackSettings.set_save_format("zdoc")
        callbackSettings.set_http_method_type("post")
        callbackSettings.set_save_url(
            "https://domain.com/save.php”)
// To implement your save callback url, refer here: https://github.com/iampraba/zoi-python-sdk-examples/tree/b74e1f5f08ca6841dc5bbf31f2049b66bf2a7d72/save-callback-implementation/Flask

        createDocumentParams.set_callback_settings(callbackSettings)

        # Optional Configuration - Set margin while creating document itself.
        # It's applicable only for new documents.
        margin = Margin()

        margin.set_top("1in")
        margin.set_bottom("1in")
        margin.set_left("1in")
        margin.set_right("1in")

        # Optional Configuration - Set default settings for document while creating document itself.
        # It's applicable only for new documents.
        documentDefaults = DocumentDefaults()

        documentDefaults.set_font_size(12)
        documentDefaults.set_paper_size("A4")
        documentDefaults.set_font_name("Arial")
        documentDefaults.set_track_changes("enabled")
        documentDefaults.set_orientation("landscape")

        documentDefaults.set_margin(margin)
        documentDefaults.set_language("ta")

        createDocumentParams.set_document_defaults(documentDefaults)

        # Optional Configuration
        editorSettings = EditorSettings()

        editorSettings.set_unit("in")
        editorSettings.set_language("en")
        editorSettings.set_view("pageview")

        createDocumentParams.set_editor_settings(editorSettings)

        # Optional Configuration
        uiOptions = UiOptions()

        uiOptions.set_dark_mode("show")
        uiOptions.set_file_menu("show")
        uiOptions.set_save_button("show")
        uiOptions.set_chat_panel("show")

        createDocumentParams.set_ui_options(uiOptions)

        # Optional Configuration - Configure permission values for session
        # based of you application requirement
        permissions = {}

        permissions["document.export"] = True
        permissions["document.print"] = True
        permissions["document.edit"] = True
        permissions["review.comment"] = True
        permissions["review.changes.resolve"] = True
        permissions["document.pausecollaboration"] = True
        permissions["document.fill"] = False

        createDocumentParams.set_permissions(permissions)

        v1Operations = V1Operations()
        response = v1Operations.create_document(createDocumentParams)

        if response is not None:
            print('Status Code: ' + str(response.get_status_code()))
            responseObject = response.get_object()

            if responseObject is not None:
                if isinstance(responseObject, CreateDocumentResponse):
                    print('Document Id : ' + str(responseObject.get_document_id()))
                    print('Document Session ID : ' + str(responseObject.get_session_id()))
                    print('Document Session URL : ' + str(responseObject.get_document_url()))
                    print('Document Session Delete URL : ' + str(responseObject.get_session_delete_url()))
                    print('Document Delete URL : ' + str(responseObject.get_document_delete_url()))
                elif isinstance(responseObject, InvalidConfigurationException):
                    print('Invalid configuration exception.')
                    print('Error Code  : ' + str(responseObject.get_code()))
                    print("Error Message : " + str(responseObject.get_message()))
                    if responseObject.get_parameter_name() is not None:
                        print("Error Parameter Name : " + str(responseObject.get_parameter_name()))
                    if responseObject.get_key_name() is not None:
                        print("Error Key Name : " + str(responseObject.get_key_name()))
                else:
                    print('Document Creation Request Failed')

    @staticmethod
    def init_sdk():
        try:
            # Replace email address associated with your apikey below
            user = UserSignature("john@zylker.com")
            # Update the api domain based on in which data center user register your apikey
            # To know more - https://www.zoho.com/officeintegrator/api/v1/getting-started.html
            environment = DataCenter.Environment("https://api.office-integrator.com", None, None, None)
            # User your apikey that you have in office integrator dashboard
            apikey = APIKey("2ae438cf864488657cc9754a*****”, Constants.PARAMS)
            # Configure a proper file path to write the sdk logs
            logger = Logger.get_instance(Logger.Levels.INFO, "./logs.txt")

            Initializer.initialize(user, environment, apikey, None, None, logger, None)

        except SDKException as ex:
            print(ex.code)


CreateDocument.execute()

Sample Response

Copied{ 
"document_url": "https://api.office-integrator.com/writer/officeapi/v1/documents/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/sessions/d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbcfb7ac1d", 
"document_delete_url": "https://api.office-integrator.com/writer/officeapi/v1/documents/1349",
 }