Edit Document
Purpose
To edit a document in Zoho Writer. Users can upload existing documents from their local drive or publicly accessible over a Web URL and edit online in Zoho Writer.
HTTP Request URL
https://{api.office-integrator_domain}/writer/officeapi/v1/documents
Request Parameters
Parameter | Value | Description |
Mandatory Parameter | ||
apikey | 423s***** | Uniquely identifies the web application in which the Writer editor is integrated. |
document or url | File or String | Method of providing the input file depending on its location. Note: You can also upload password protected files and edit them. As of now, it is supported only for docx file format. |
callback_settings | { "save_url_headers": { | 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 | { "track_changes": "disabled", "track_changes_mode":"all_markup", "language":"en-US", "date_format":"MM/DD/YY" } | Set document defaults such as custom date format, enable/disable track changes and control track changes mode. You can also set a desired language for the document. The document language set will affect the following;
|
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":"1973", "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.
Editor Customization Parameters
document_defaults
Parameter | Type | Possible Values | Default Value |
track_changes | boolean | enabled / disabled | disabled |
track_changes_mode | string | all_markup / no_markup / original | all_markup |
language | string | en-US / af / bn / ca / cs / et and more... | en-US |
date_format | string | For example: EEEE, MMMM DD, YYYY at HH:mm Output: Monday, July 15, 2024 at 21:06 | Date format will be displayed based on the document language value. |
editor_settings
Parameter | Type | Possible Values | Default Value |
unit | string | in/mm | in (inch) |
language | string | en / de / es / fr / ja / nl more... | en |
view | string | webview / pageview | pageview Note: "view" parameter is applicable only for new documents. |
permissions
Parameter | Type | Possible Values | Default Value | Description |
document.export | boolean | true / false | true | To enable or disable document download option |
document.print | boolean | true / false | true | To enable or disable document print option |
document.edit | boolean | true / false | false | Provide option to allow edit access to the document |
review.comment | boolean | true / false | false | Provide option to manage comments |
review.changes.resolve | boolean | true / false | false | Provide option to resolve track changes |
collab.chat | boolean | true / false | true | To enable or disable chat panel for the collaborators |
document.pausecollaboration | boolean | true / false | false | Provide option to manage collaboration |
document.fill | boolean | true / false | true | Provide option to allow edit access for the fillable fields |
callback_settings
Parameter | Type | Possible Values | Default Value |
Mandatory Keys | |||
save_format | string | zdoc / doc / docx / odt / html / pdf and more ... | zdoc |
save_url | string | URL - Maximum length -> 65535 | URL |
Optional Keys | |||
save_url_params | JSON |
| |
save_url_headers | string |
| |
http_method_type | string | post / put | post |
retries | integer | 0 to 3 | 0 |
timeout | integer | 1 to 120000 milliseconds | 120000 |
document_info
Parameter | Type | Possible Values | Default Value |
document_id | string | 13d4vh9eh | |
document_name | string | Sample | Untitled |
user_info
Parameter | Type | Possible Values | Default Value |
user_id | integer | 1973564 | |
display_name | string | Ken/James/Adam | Guest |
ui_options
Parameter | Type | Possible Values | Default Value |
save_button | string | show/hide | show |
chat_panel | string | show/hide | show |
dark_mode | string | show/hide | show |
file_menu | string | show/hide | show |
Edit Document - Error Codes
Code | Description |
1831 | Error occurred. Parameter value is either incorrect or invalid. |
1838 | Invalid method. Please use a valid method and try again. |
1842 | Import failed. File size limit exceeded. (Max 10 MB) |
1868 | Invalid parameter name for uploaded content. |
For a full list of error handling cases in Edit 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:
- 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.
- 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 Name | Type | Description |
content | File | Document content will be pushed back in the form of bytes. |
filename | String | Document name |
format | String | Specifies 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
Copiedcurl -X POST \
https://api.office-integrator.com/writer/officeapi/v1/documents \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-F apikey=423s***** \
-F document=@/Users/username/Documents/Sample.docx \
-F 'document_defaults={"track_changes":"disabled","language":"en-US","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'\'':'\''zdoc'\'','\''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'\''}' \
-F 'ui_options={"save_button":"show","chat_panel":"show","dark_mode":"hide","file_menu":"show"}'
Copied//Reference on how to run the 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 fs = require("fs");
const StreamWrapper = require("zoi-nodejs-sdk/utils/util/stream_wrapper").StreamWrapper;
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 EditDocument {
//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("2ae438cf864488657cc9754a*****”, 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("\nSDK 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();
createDocumentParameters.setUrl("https://demo.office-integrator.com/zdocs/Graphic-Design-Proposal.docx");
//var fileName = "Graphic-Design-Proposal.docx";
//var filePath = __dirname + "/sample_documents/Graphic-Design-Proposal.docx";
//var fileStream = fs.readFileSync(filePath);
//var streamWrapper = new StreamWrapper(fileName, fileStream, filePath);
//createDocumentParameters.setDocument(streamWrapper);
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("Graphic-Design-Proposal.docx");
createDocumentParameters.setDocumentInfo(documentInfo);
var userInfo = new UserInfo();
userInfo.setUserId("1000");
userInfo.setDisplayName("Prabakaran R");
createDocumentParameters.setUserInfo(userInfo);
var margin = new Margin();
margin.setTop("2in");
margin.setBottom("2in");
margin.setLeft("2in");
margin.setRight("2in");
var documentDefaults = new DocumentDefaults();
documentDefaults.setLanguage("ta");
documentDefaults.setTrackChanges("enabled");
createDocumentParameters.setDocumentDefaults(documentDefaults);
var editorSettings = new EditorSettings();
editorSettings.setUnit("mm");
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.setTimeout(10000);
callbackSettings.setSaveFormat("zdoc");
callbackSettings.setHttpMethodType("post");
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("Status 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);
}
}
}
EditDocument.execute();
Copied//Reference on how to run the 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.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 EditDocument {
private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(EditDocument.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 editDocumentParams = new CreateDocumentParameters();
//Either use url as document source or attach the document in request body use below methods
editDocumentParams.setUrl("https://demo.office-integrator.com/zdocs/Graphic-Design-Proposal.docx");
/*
String inputFilePath = "Absolute input file path"
File inputFile = new File(inputFilePath);
FileInputStream fileInputStream = new FileInputStream(inputFile);
StreamWrapper documentStreamWrapper = new StreamWrapper(fileInputStream);
editDocumentParams.setDocument(documentStreamWrapper); */
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());
editDocumentParams.setDocumentInfo(documentInfo);
UserInfo userInfo = new UserInfo();
userInfo.setUserId("1000");
userInfo.setDisplayName("John");
editDocumentParams.setUserInfo(userInfo);
DocumentDefaults documentDefault = new DocumentDefaults();
documentDefault.setTrackChanges("disabled");
editDocumentParams.setDocumentDefaults(documentDefault);
EditorSettings editorSettings = new EditorSettings();
editorSettings.setUnit("in");
editorSettings.setLanguage("en");
editorSettings.setView("pageview");
editDocumentParams.setEditorSettings(editorSettings);
UiOptions uiOptions = new UiOptions();
uiOptions.setChatPanel("show");
uiOptions.setDarkMode("show");
uiOptions.setFileMenu("show");
uiOptions.setSaveButton("show");
editDocumentParams.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);
editDocumentParams.setPermissions(permissions);
Map<String, Object> saveUrlParams = new HashMap<String, Object>();
saveUrlParams.put("id", 123456789);
saveUrlParams.put("auth_token", "oswedf32rk");
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
editDocumentParams.setCallbackSettings(callbackSettings);
APIResponse<WriterResponseHandler> response = sdkOperations.createDocument(editDocumentParams);
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("2ae438cf864488657cc9754a2*****”);
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 the 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\CreateDocumentParameters;
use com\zoho\officeintegrator\v1\CreateDocumentResponse;
use com\zoho\officeintegrator\v1\DocumentDefaults;
use com\zoho\officeintegrator\v1\DocumentInfo;
use com\zoho\officeintegrator\v1\EditorSettings;
use com\zoho\officeintegrator\v1\UiOptions;
use com\zoho\officeintegrator\v1\UserInfo;
use com\zoho\officeintegrator\v1\V1Operations;
use com\zoho\UserSignature;
use com\zoho\util\Constants;
use com\zoho\util\StreamWrapper;
class EditDocument {
//Refer API documentation - https://www.zoho.com/officeintegrator/api/v1/zoho-writer-edit-document.html
public static function execute() {
self::initializeSdk();
$v1Operations = new V1Operations();
$createDocumentParameters = new CreateDocumentParameters();
$url = "https://demo.office-integrator.com/zdocs/Graphic-Design-Proposal.docx";
$createDocumentParameters->setUrl($url);
// Either you can give the document as publicly downloadable url as above or add the file in request body itself using below code.
// $filePath = getcwd() . DIRECTORY_SEPARATOR . "sample_documents" . DIRECTORY_SEPARATOR . "Graphic-Design-Proposal.docx";
// $createDocumentParameters->setDocument(new StreamWrapper(null, null, $filePath));
# Optional Configuration - Add document meta in request to identify the file in Zoho Server
$documentInfo = new DocumentInfo();
$currentTime = time();
$documentInfo->setDocumentName("New Document");
$documentInfo->setDocumentId($currentTime);
$createDocumentParameters->setDocumentInfo($documentInfo);
# Optional Configuration - Add User meta in request to identify the user in document session
$userInfo = new UserInfo();
$userInfo->setUserId(100);
$userInfo->setDisplayName("John");
$createDocumentParameters->setUserInfo($userInfo);
# Optional Configuration - Set default settings for document while creating document itself.
# It's applicable only for new documents.
$documentDefaults = new DocumentDefaults();
$documentDefaults->getTrackChanges("enabled");
$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();
$saveUrlParams = array();
$saveUrlHeaders["param1"] = "value1";
$saveUrlHeaders["param2"] = "value2";
$callbackSettings->setSaveUrlParams($saveUrlParams);
$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);
$response = $v1Operations->createDocument($createDocumentParameters);
if($response != null)
{
//Get the status code from response
echo("Status code " . $response->getStatusCode() . "\n");
//Get object from response
$responseHandler = $response->getObject();
if($responseHandler instanceof CreateDocumentResponse)
{
echo("\nDocument ID - " . $responseHandler->getDocumentId() . "\n");
echo("Document Session ID - " . $responseHandler->getSessionId() . "\n");
echo("Document Session URL - " . $responseHandler->getDocumentUrl() . "\n");
echo("Document Session Delete URL - " . $responseHandler->getSessionDeleteUrl() . "\n");
echo("Document Save URL - " . $responseHandler->getSaveUrl() . "\n");
echo("Document Delete URL - " . $responseHandler->getDocumentDeleteUrl() . "\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("2ae438cf864488657cc9754a2&******, 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";
}
}
EditDocument::execute();
?>
Copied//Reference on how to run the 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 EditDocument
{
static void execute(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();
createDocumentParams.Url = "https://demo.office-integrator.com/zdocs/Graphic-Design-Proposal.docx";
//String inputFilePath = "/Users/praba-2086/Desktop/writer.docx";
//StreamWrapper documentStreamWrapper = new StreamWrapper(inputFilePath);
//createDocumentParams.Document = documentStreamWrapper;
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("Document 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("2ae438cf864488657cc9754a27d*****”, 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 the 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, CallbackSettings, DocumentDefaults, \
EditorSettings, UiOptions, 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
import os
from zohosdk.src.com.zoho.util import StreamWrapper
class EditDocument:
# Refer API documentation - https://www.zoho.com/officeintegrator/api/v1/zoho-writer-edit-document.html
@staticmethod
def execute():
EditDocument.init_sdk()
createDocumentParams = CreateDocumentParameters()
createDocumentParams.set_url('https://demo.office-integrator.com/zdocs/Graphic-Design-Proposal.docx')
# ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# filePath = ROOT_DIR + "/sample_documents/Graphic-Design-Proposal.docx"
# print('Path for source file to be edited : ' + filePath)
# createDocumentParams.set_document(StreamWrapper(file_path=filePath))
# 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("User 1")
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'] = '12dweds32r42wwds34'
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 default settings for document while creating document itself.
# It's applicable only for new documents.
documentDefaults = DocumentDefaults()
documentDefaults.set_track_changes("enabled")
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('Edit Document 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("2ae438cf864488657cc9754a27d*****”, 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)
EditDocument.execute()
Sample Response
Copied{
"document_url": "https://api.office-integrator.com/writer/officeapi/v1/documents/d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d0erouae4667dcbcfb7ac1d/edit",
"document_id": "1349",
"save_url": "https://api.office-integrator.com/writer/officeapi/v1/documents/d26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbcfb7ac1d/save",
"session_id": "axxrd26aa7b8029bf4f8d34c7dd0013939234a6e15dac88646f02a69582375b8da130efffac249d086aae4667dcbac9p",
"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",
}