Add Paragraphs to Microsoft Word Documents in PHP
Learn how to programmatically add custom paragraphs into DOCX files using PHP code.
We might think of basic file conversions - like converting our documents to PDF, for example - as the extent to which we can automate DOCX-related processes in our web applications. In reality, we can go a lot further than that.
OpenXML file structure makes it easy to navigate the path of DOCX documents and programmatically incorporate brand new content. Well - I should say it makes that relatively easy. In order to successfully navigate OpenXML file structure, we still need a working knowledge of how OpenXML file paths are meant to be navigated, and that isn’t knowledge we’re likely to have on hand.
Thankfully, using a couple of low-code web APIs, we can structure our programmatic content changes in a simple, easily readable request object and pass that object to a specialized service. The result? We’ll end up with an automated workflow that makes direct changes to DOCX files as if we were working manually within a text editor application ourselves.
In this tutorial, we’ll learn how to call a series of Cloudmersive APIs that cumulatively create a quick, memory-efficient workflow for programmatically adding paragraphs into our DOCX files. Specifically, we’ll call APIs that perform the following sequence of operations:
Convert our DOCX file into a temporary editing URL
Add a custom paragraph into the document
Download the modified URL and convert it back to DOCX file bytes
Step 1: Install the SDK
To get started, we’ll run the following composer command to install the Cloudmersive Document Convert API client:
composer require cloudmersive/cloudmersive_document_convert_api_client
Step 2: Configure an API Key
We’ll configure authorization for all three API calls the same way: by adding a free Cloudmersive API key into the below PHP snippet.
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
To get our free API key, we just need to visit the Cloudmersive website and create a free account. Free API keys allow a limit of 800 API calls per month with zero additional commitments.
Step 3: Create our Temporary Editing URL
To convert our file bytes into a temporary editing URL, we’ll create an instance of the Edit Document API and pass our file path to the endpoint. This returns the URL to our console.
$apiInstance = new Swagger\Client\Api\EditDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.
try {
$result = $apiInstance->editDocumentBeginEditing($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditDocumentApi->editDocumentBeginEditing: ', $e->getMessage(), PHP_EOL;
}
?>
Step 4: Customize the “Insert Paragraph” API Request
With our temporary editing URL ready, we’ll now create an additional instance of the Edit Document API to send our new paragraph configuration request to the endpoint.
$apiInstance = new Swagger\Client\Api\EditDocumentApi(
new GuzzleHttp\Client(),
$config
);
$req_config = new \Swagger\Client\Model\InsertDocxInsertParagraphRequest(); // \Swagger\Client\Model\InsertDocxInsertParagraphRequest | Document input request
try {
$result = $apiInstance->editDocumentDocxInsertParagraph($req_config);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditDocumentApi->editDocumentDocxInsertParagraph: ', $e->getMessage(), PHP_EOL;
}
?>
We’ll structure our request object following the below model to add one (or more) new paragraphs to our document.
{
"InputFileBytes": "string",
"InputFileUrl": "string",
"ParagraphToInsert": {
"ParagraphIndex": 0,
"Path": "string",
"ContentRuns": [
{
"RunIndex": 0,
"Path": "string",
"TextItems": [
{
"TextIndex": 0,
"Path": "string",
"TextContent": "string"
}
],
"Bold": true,
"Italic": true,
"Underline": "string",
"FontFamily": "string",
"FontSize": "string"
}
],
"StyleID": "string"
},
"InsertPlacement": "string",
"InsertPath": "string"
}
This API returns the temporary editing URL modified with our new paragraph contents.
Step 5: Convert the Finalized URL into DOCX File Bytes
We’ll now create one final instance of the Edit Document API to download DOCX file bytes from the temporary URL we’ve been working with. This returns our DOCX file bytes as a string, and we can write the resulting content to a new file with a .docx extension.
$apiInstance = new Swagger\Client\Api\EditDocumentApi(
new GuzzleHttp\Client(),
$config
);
$req_config = new \Swagger\Client\Model\FinishEditingRequest(); // \Swagger\Client\Model\FinishEditingRequest | Cloudmersive Document URL to complete editing on
try {
$result = $apiInstance->editDocumentFinishEditing($req_config);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditDocumentApi->editDocumentFinishEditing: ', $e->getMessage(), PHP_EOL;
}
?>
Just like that, we’re all done - we now have a three-step process in place to programmatically add new content into DOCX files. Thanks to the combination of external server processing and temporary URLs, we’ll be able to make document edits at high speed with minimal impact on local memory consumption.