We're sorry AsposeCloud doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.cloud

How to Find and Replace Text in PDF using PHP Laravel Throws Error

When trying to use the PHP API to replace a text in a PDF document, I get this error:

[400] Client error: 
`POST https://api.aspose.cloud/v3.0/pdf/kk-mappe.pdf/text/replace` 
resulted in a `400 Bad Request` 
response: {"TextReplaces":["The TextReplaces field is required."]} 

My code looks like this:

namespace App\Http\Controllers;
use Aspose\PDF\Api\PdfApi;
use Illuminate\Http\Request;
use Aspose\PDF\Configuration;
use Aspose\PDF\Model\TextReplace;
use Aspose\PDF\Model\TextReplaceListRequest;

class AsposePDFController extends Controller {
    private $baseURL = "https://api.aspose.cloud/v3.0/";

    private function getAPI() {
        $appSid = 'XXX';
        $appKey = 'XXX';
        $config = new Configuration();

        return new PdfApi(null, $config);

    public function replacePDFText(Request $request) {
        $api = $this->getAPI();
        $sourcePath = "C:/xampp7_4/htdocs/kkbackend/public/uploads/documents/";
        $sourceFile = $sourcePath . "kk-mappe.pdf";
        $remoteFileName = "kk-mappe.pdf";
        $outputFile = $sourcePath . "kk-mappe-replaced.pdf";
        // Upload File
        // Replace the Text
        $textReplace = new TextReplace();
        $textReplace->old_value = "Iserlohn";
        $textReplace->new_value = "Crailsheim";
        $textReplace->regex = false;

        $textReplaceRequest = new TextReplaceListRequest();
        $textReplaceRequest->text_replaces = [$textReplace];

        // Call the TextReplace API 
        $response = $api->postDocumentTextReplace(
            null,   // Storage
            null    // Folder
        // Download the resulting file
        $downloadResult = $api->downloadFile($remoteFileName);
        // Save it
        copy($downloadResult->getPathName(), $outputFile);
        return $downloadResult;

What am I missing?
Thanks a lot for help or a working example to replace text in a PDF document using the PHP API.


After looking into the source code, I’ve found the answer. Setting properties directly is wrong. I may pass them to the constructor instead or use the setter methods.

    $textReplace = new TextReplace([
        "old_value" => "Iserlohn",
        "new_value" => "Crailsheim",
        "regex" => false

    $textReplaceRequest = new TextReplaceListRequest([
        "text_replaces" => [$textReplace];

Now it works! Great!

1 Like


It is good to know that you have managed to resolve the issue. You can check the unit tests from Aspose.PDF Cloud SDK for PHP for your reference as well.