XtremeDocumentStudio
.NET
PDFOne
.NET
XtremeDocumentStudio
(for Java)
PDFOne
(for Java)
XtremeDocumentStudio
Delphi
eDocEngine
VCL
PDFtoolkit
VCL
StarDocs
Web APIs

Getting started with Gnostice StarDocs Cloud and On-Premises APIs

Basics of working with StarDocs
by Santosh Patil

Select the language for the code snippets


If you are new to StarDocs, we suggest you read the introductory article first.
The API reference documentation can be found here.

In this article we cover the steps required to get started using the StarDocs APIs in your application by showing you the process of setting up the development environment, uploading a document, getting information about the uploaded document and finally downloading it back.

Before we begin, if you don't already have the trial keys for StarDocs Cloud API, obtain them by signing up for a free trial here. Also, if you don't want to mess with HTTP calls then you may want to grab our SDKs, available for JavaScript, .NET and Delphi platforms, from here. The code snippets shown in this article use the SDKs.

  1. Download the StarDocs SDK for JavaScript from GitHub.
  2. Include the JQuery library, URI.min.js and stardocs-sdk.min.js file in your web page.
    <script src="jquery-1.11.0.min.js"></script>
    <script src="URI.min.js"></script>
    <script src="stardocs-sdk.min.js"></script>
    
  3. Install the Gnostice StarDocs SDK for .NET package from NuGet into your project.
  4. Download the StarDocs SDK for Java JAR file and include it in your project.
  5. Download the StarDocs SDK for Delphi from GitHub and follow the instruction in the README.txt file to setup the SDK in your IDE. Note that the SDK only works on RAD Studio XE5 or higher.
  6. If you are using a secure connection to the StarDocs server (i.e. https) and you run into issues with this please ensure to copy the OpenSSL DLLs (libeay32.dll and ssleay32.dll) to your application directory. The latest build of these DLLs is available here. You can download the zip file of the latest version and either 32/64 bit based on your OS architecture.
  7. The following diagrams show the high-level sequence of operations required to accomplish a document viewing or processing task. However, in this article we will only perform few of the steps while other articles will cover the viewing and processing tasks.
  8. Setup the connection by providing the end-point URL and the API keys. Authenticate to the StarDocs server by calling loginApp method.
    // Set up connection details
    var starDocs = new Gnostice.StarDocs(
      new Gnostice.ConnectionInfo(
        'https://api.gnostice.com/stardocs/v1', 
        '<API Key>', 
        '<API Secret>'),
      new Preferences(
        // Force full permissions on PDF files protected 
        // with an permissions/owner/master password
        new DocPasswordSettings(true))
    );
    
    // Authenticate
    starDocs.auth.loginApp()
      .done(function(response) { /* Success */ })
      .fail(function(httpStatusCode, httpErrorMessage, response) { /* Handle error */ });
    
    //...
    using Gnostice.StarDocsSDK;
    //...
    
    // Set up connection details
    StarDocs starDocs = new StarDocs(
      new ConnectionInfo(
        new Uri("https://api.gnostice.com/stardocs/v1"),
        "<API Key>",
        "<API Secret>"), 
      new Preferences(
        // Force full permissions on PDF files protected 
        // with an permissions/owner/master password
        new DocPasswordSettings(true))
    );
    
    // Authenticate
    try
    {
      starDocs.Auth.loginApp();
    }
    catch (StarDocsException e)
    {
      // Handle error
      // e.HttpStatusCode contains the HTTP status code
      // e.ErrorCode contains the StarDocs error code (if any)
      // e.Documents contains the array of documents related to the error (
      // if applicable)
      // e.Message contains the error message
    }
    
    Note: From here on, exception handling will not be shown to retain brevity of code.
    //...
    import com.gnostice.stardocssdk.*;
    //...
    
    // Set up connection details
    StarDocs starDocs = new StarDocs(
      new ConnectionInfo(
        new java.net.URI("https://api.gnostice.com/stardocs/v1"),
        "<API Key>",
        "<API Secret>"), 
      new Preferences(
        // Force full permissions on PDF files protected 
        // with an permissions/owner/master password
        new DocPasswordSettings(true))
    );
    
    // Authenticate
    try
    {
      starDocs.auth.loginApp();
    }
    catch (StarDocsException e)
    {
      // Handle error
      // e.getHttpStatusCode() returns the HTTP status code
      // e.getErrorCode() returns the StarDocs error code (if any)
      // e.getDocuments() returns the array of documents related to the error (
      // if applicable)
      // e.getMessage() contains the error message
    }
    
    Note: From here on, exception handling will not be shown to retain brevity of code.
    var
      StarDocs: TgtStarDocsSDK;
    begin
      try
        // Set up connection details
        StarDocs := TgtStarDocsSDK.Create(nil);
        StarDocs.ConnectionInfo.ApiServerUri.URI :=
          'http://api.gnostice.com/stardocs/v1';
        StarDocs.ConnectionInfo.ApiKey := '<API Key>';
        StarDocs.ConnectionInfo.ApiSecret := '<API Secret>';
        // Whether to force full permissions on PDF files protected 
        // with an permissions/owner/master password
        StarDocs.Preferences.DocPasswordSettings.ForceFullPermission := True;
    
        // Authenticate
        try
          StarDocs.Auth.loginApp;
        except
          on E: EgtStarDocsException do
            // Handle error
            // E.HttpStatusCode contains the HTTP status code
            // E.ErrorCode contains the StarDocs error code (if applicable)
            // E.Documents contains the array of documents related to the 
            // error (if applicable)
            // E.Message contains the error message
        end;
      finally
        StarDocs.Free;
      end;
    end;
    
    Note: From here on, exception handling will not be shown to retain brevity of code.
  9. You can upload a file by passing the File object which is obtained from the HTML element
    <input type="file">
    after the user has selected a file. See here for details of the File object and here for explanation of how to obtain the file object. An optional password can be supplied if the PDF file is encrypted. After the file is uploaded save the document URL that the server returns.
    // Upload file
    var selectedFile = document.getElementById('input').files[0];
    starDocs.storage.upload(selectedFile, "password") 
      .done(function(response) {
        // Store document URL
        documentUrl = response.documents[0].url;
      })
      .fail(function(errorThrown, errorCode, errorMessage) { /* Handle error */ });
    
  10. You can upload files either by specifying the filename with path or by supplying an input stream. If a stream is used then you can supply a filename for it so the file is appropriately named on the server. An optional password can be supplied if the PDF file is encrypted.
    // Upload by passing file name with path
    DocObject docObjectBalanceSheet = starDocs.Storage.Upload(@"C:\Documents\BalanceSheet.pdf", 
      "password");
    // Upload by passing in stream
    DocObject docObjectAnnualReport = starDocs.Storage.Upload(
      new FileStream(@"C:\Documents\AnnualReport.pdf", FileMode.Open),
      "AnnualReport.pdf", "password");
    
    Note that the document operation and viewing APIs can be supplied a filename with path or an input stream directly, so it is not necessary to perform a separate upload operation before performing a document operation or requesting to view a document. The methods will first upload the file and then proceed with the requested operation.
  11. You can upload files either by specifying the filename with path or by supplying an input stream. If a stream is used then you can supply a filename for it so the file is appropriately named on the server. An optional password can be supplied if the PDF file is encrypted.
    // Upload by passing file name with path
    DocObject docObjectBalanceSheet = starDocs.storage.upload("C:\\Documents\\BalanceSheet.pdf", 
      "password");
    // Upload by passing an input stream
    DocObject docObjectAnnualReport = starDocs.storage.upload(
      new FileInputStream("C:\\Documents\\AnnualReport.pdf"),
      "AnnualReport.pdf", "password");
    
    Note that the document operation and viewing APIs can be supplied a filename with path or an input stream directly, so it is not necessary to perform a separate upload operation before performing a document operation or requesting to view a document. The methods will first upload the file and then proceed with the requested operation.
  12. You can upload files either by specifying the filename with path or by supplying an input stream. If a stream is used then you can supply the filename so that the file is appropriately named on the server. An optional password can be supplied if the PDF file is encrypted.
    var
      InFileStream: TFileStream;
      DocObjectBalanceSheet: TgtDocObject;  
      DocObjectAnnualReport: TgtDocObject;
    begin
      InFileStream := nil;
      DocObjectBalanceSheet := nil;
      DocObjectAnnualReport := nil;
      try
        // Upload by passing file name with path
        DocObjectBalanceSheet := StarDocs.Storage.Upload(
          'C:\Documents\BalanceSheet.pdf', 'password');
        // Upload by passing in stream
        InFileStream := TFileStream.Create(
          'C:\webapi_testing\datafiles\One-Page-SOPA.pdf', fmOpenRead);
        DocObjectAnnualReport := StarDocs.Storage.Upload(
          InFileStream, 'AnnualReport.pdf', 'password');
      finally
        if Assigned(DocObjectAnnualReport) then
          FreeAndNil(DocObjectAnnualReport);
        if Assigned(DocObjectBalanceSheet) then
          FreeAndNil(DocObjectBalanceSheet);
        if Assigned(InFileStream) then
          FreeAndNil(InFileStream);
      end;
    end;
    
    Note that the document operation and viewing APIs can be supplied a filename with path or an input stream directly, so it is not necessary to perform a separate upload operation before performing a document operation or requesting to view a document. The methods will first upload the file and then proceed with the requested operation.
  13. Having uploaded the document you can now pass the document object (URL) to other methods to perform further operation. Let us inspect the document by retrieving its information. It's a good idea to do this after upload to ensure the document is of the correct format, StarDocs is able to handle it, and that if it is password protected, the correct password is known.
    starDocs.docOperations.getDocInfo(documentUrl, "password")
      .done(function(response) {
        /*
        response has the following properties:
          url: URL of the document
          fileName: Filename of the document
          fileSize: The size of the file in bytes
          fileExpiry: The number of seconds since epoch when file will be 
            deleted from the server. Null if there is no expiry set 
          mimeType: MIME type of the document
          unsupportedMimeTypeOrCorrupt: True if the document is either 
            corrupted or if it is of a type not currently supported by 
            StarDocs. The remaining properties shown below of the response are 
            valid only if this property is set to false
          passwordProtected: True if the document requires a password to be 
            opened
          passwordCorrect: True if StarDocs has the correct password to open 
            the document. Valid only if passwordProtected is true. The other 
            properties shown below of the response are valid only if 
            passwordProtected is false or this property is set to true
          pageCount: Number of pages contained in the document. Note that this 
            property may not be valid for certain types of documents (ex. 
            flow-based documents such as DOCX)
        */
      })
      .fail(function(httpStatusCode, httpErrorMessage, response) { /* Handle error */ });
    
    GetDocumentInfoResponse response = starDocs.DocOperations.GetDocumentInfo(
      docObjectBalanceSheet, "password");
    /*
    response has the following properties:
      Url: URL of the document
      FileName: Filename of the document
      FileSize: The size of the file in bytes
      FileExpiry: The number of seconds since epoch when file will be 
        deleted from the server. Null if there is no expiry set 
      MimeType: MIME type of the document
      UnsupportedMimeTypeOrCorrupt: True if the document is either 
        corrupted or if it is of a type not currently supported by 
        StarDocs. The remaining properties shown below of the response are 
        valid only if this property is set to false
      PasswordProtected: True if the document requires a password to be 
        opened
      PasswordCorrect: True if StarDocs has the correct password to open 
        the document. Valid only if PasswordProtected is true. The other 
        properties shown below of the response are valid only if 
        PasswordProtected is false or this property is set to true
      PageCount: Number of pages contained in the document. Note that this 
        property may not be valid for certain types of documents (ex. 
        flow-based documents such as DOCX)
    */
    
    GetDocumentInfoResponse response = starDocs.docOperations.getDocumentInfo(
      docObjectBalanceSheet, "password");
    /*
    Following properties can be obtained from the response:
      getUrl(): URL of the document
      getFileName(): Filename of the document
      getFileSize(): The size of the file in bytes
      getFileExpiry(): The number of seconds since epoch when file will be 
        deleted from the server. Null if there is no expiry set 
      getMimeType(): MIME type of the document
      getUnsupportedMimeTypeOrCorrupt(): True if the document is either 
        corrupted or if it is of a type not currently supported by 
        StarDocs. The remaining properties shown below of the response are 
        valid only if this property is set to false
      getPasswordProtected(): True if the document requires a password to be 
        opened
      getPasswordCorrect(): True if StarDocs has the correct password to open 
        the document. Valid only if PasswordProtected is true. The other 
        properties shown below of the response are valid only if 
        PasswordProtected is false or this property is set to true
      getPageCount(): Number of pages contained in the document. Note that this 
        property may not be valid for certain types of documents (ex. 
        flow-based documents such as DOCX)
    */
    
    var
      GetDocumentInfoResponse: TgtGetDocumentInfoResponse;
    begin
      try
        GetDocumentInfoResponse := StarDocs.DocOperations.GetDocumentInfo(
          DocObjectAnnualReport, 'password');
      finally
        GetDocumentInfoResponse.Free;
      end;
    /*
    GetDocumentInfoResponse has the following properties:
      Url: URL of the document
      FileName: Filename of the document
      FileSize: The size of the file in bytes
      FileExpiry: The number of seconds since epoch when file will be 
        deleted from the server. Null if there is no expiry set 
      MimeType: MIME type of the document
      UnsupportedMimeTypeOrCorrupt: True if the document is either 
        corrupted or if it is of a type not currently supported by 
        StarDocs. The remaining properties shown below of the response are 
        valid only if this property is set to false
      PasswordProtected: True if the document requires a password to be 
        opened
      PasswordCorrect: True if StarDocs has the correct password to open 
        the document. Valid only if PasswordProtected is true. The other 
        properties shown below of the response are valid only if 
        PasswordProtected is false or this property is set to true
      PageCount: Number of pages contained in the document. Note that this 
        property may not be valid for certain types of documents (ex. 
        flow-based documents such as DOCX)
    */
    end;
    
    Note: If the password needs to be supplied by the user of your application then you can repeatedly attempt to fetch the document info by passing in the password the user has supplied, until such point that the correct password is supplied or the number of attempts have been exhausted. Once the correct password is supplied StarDocs stores it in its database so there is no need to supply the password for subsequent operations.
  14. You can request for download of a file by passing in the document URL. The SDK will ask the browser to download the file by launching a new tab pointing to the document URL. The server sets the Content-Disposition header to "attachment" so the browser will save the file rather than opening it.
    starDocs.storage.download(documentUrl)
      .done(function() {
        /* Success */
      })
      .fail(function(httpStatusCode, httpErrorMessage, response) {
        /* Handle error */ 
      });
    
  15. You can request for download of a file by passing in the document object and a file path, where the file should be saved, or a stream, where the file contents should be written out to.
    starDocs.Storage.Download(docObjectBalanceSheet, @"c:\documents");
    
  16. You can request for download of a file by passing in the document object and a file path, where the file should be saved, or an output stream, where the file contents should be written out to.
    starDocs.storage.download(docObjectBalanceSheet, "c:\\documents\\");
    
  17. You can request for download of a file by passing in the document object and a file path, where the file should be saved, or a stream, where the file contents should be written out to.
    StarDocs.Storage.Download(DocObjectAnnualReport, 'c:\documents');
    
  18. Videos

    Short videos demonstrating the integration of StarDocs Multi-format Document Viewer in your web applications.






---o0O0o---

Our .NET Developer Tools
XtremeDocumentStudio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
XtremeDocumentStudio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
XtremeDocumentStudio (for Java)

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2017 Gnostice Information Technologies Private Limited. All rights reserved.