How to merge text

Conceptual diagram of a merge

One very useful application of the Google Docs API is to merge information from one or more data sources into a document.

This page outlines how you can take data from an external source and insert it into an existing template document.

A template is a special kind of document that contains fixed text, which is the same for all documents created from the template, as well as designated places where other text can be placed. For example, a contract template might have a lot of fixed content, together with places for the receiver's name, address, and other details. Your app can then merge customer-specific data into the template to create finished documents.

There are a number of reasons why this approach is useful, including:

  • It's easy for designers to fine-tune a document's design using the Google Docs editor. This is much easier than adjusting parameters in your app to adjust the rendered layout.

  • Separating content from presentation is a well-known design principle with many benefits.

A basic recipe

Here's an example of how you can use the Docs API to merge data into a document.

  1. Create your document exactly as you want it to appear using dummy content to help you with the design and format. Any formatting on the text that you want to replace is preserved.

  2. For each element that you'll be inserting, replace the dummy content with a tag. Be sure to use strings that are unlikely to occur normally. For example, {{account-holder-name}} might be a good tag.

  3. In your code, use the Google Drive API to make a fresh copy of the document.

  4. In your code, use the batchUpdate() method with the document name and include a ReplaceAllTextRequest.

Documents are referenced by their IDs. The ID of a document is part of the URL:

https://docs.google.com/document/d/documentId/edit

Example

Consider the following example, which replaces two fields in a template with actual values to generate a finished document.

To perform this merge, you can use the code shown below.

Java

        String customerName = "Alice";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String date = formatter.format(LocalDate.now());

        List<Request> requests = new ArrayList<>();
        requests.add(new Request()
                .setReplaceAllText(new ReplaceAllTextRequest()
                        .setContainsText(new SubstringMatchCriteria()
                                .setText("{{customer-name}}")
                                .setMatchCase(true))
                        .setReplaceText(customerName)));
        requests.add(new Request()
                .setReplaceAllText(new ReplaceAllTextRequest()
                        .setContainsText(new SubstringMatchCriteria()
                                .setText("{{date}}")
                                .setMatchCase(true))
                        .setReplaceText(date)));

        BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();
        service.documents().batchUpdate(documentId, body.setRequests(requests)).execute();

Node.js

  let customerName = 'Alice';
  let date = yyyymmdd()
  let requests = [
    {
      replaceAllText: {
        containsText: {
          text: '{{customer-name}}',
          matchCase: true,
        },
        replaceText: customerName,
      },
    },
    {
      replaceAllText: {
        containsText: {
          text: '{{date}}',
          matchCase: true,
        },
        replaceText: date,
      },
    },
  ];

  google.options({auth: auth});
  google
      .discoverAPI(
          'https://docs.googleapis.com/$discovery/rest?version=v1&key={YOUR_API_KEY}')
      .then(function(docs) {
        docs.documents.batchUpdate(
            {
              documentId: '1yBx6HSnu_gbV2sk1nChJOFo_g3AizBhr-PpkyKAwcTg',
              resource: {
                requests,
              },
            },
            (err, {data}) => {
              if (err) return console.log('The API returned an error: ' + err);
              console.log(data);
            });
      });

Python

    customer_name = 'Alice'
    date = datetime.datetime.now().strftime("%y/%m/%d")

    requests = [
         {
            'replaceAllText': {
                'containsText': {
                    'text': '{{customer-name}}',
                    'matchCase':  'true'
                },
                'replaceText': customer_name,
            }}, {
            'replaceAllText': {
                'containsText': {
                    'text': '{{date}}',
                    'matchCase':  'true'
                },
                'replaceText': str(date),
            }
        }
    ]

    result = service.documents().batchUpdate(
        documentId=document_id, body={'requests': requests}).execute()

Managing templates

For template documents that the application defines and owns, create the template using a dedicated account representing the application. Service accounts are a good choice and avoid complications with G Suite policies that restrict sharing.

When you create instances of documents from templates, always use end-user credentials. This gives users full control over the resulting presentation and prevents scaling issues related to per-user limits in Google Drive.

To create a template using a service account, perform the following steps using the application credentials:

  1. Create a new document using documents.create in the Docs API.
  2. Update the permissions to allow the document recipients to read using permissions.create in the Drive API.
  3. Update the permissions to allow template authors to write using permissions.create in the Drive API.
  4. Edit the template as required.

To create a new instance of the document, perform the following steps using the user credentials:

  1. Create a copy of the template using files.copy in the Drive API.
  2. Replace values using documents.batchUpdate in the Docs API.

Send feedback about...

Google Docs API
Google Docs API
Need help? Visit our support page.