REST API post pdf document to ECM corrupt file - Failed to load PDF document

Hello,
I have written a php function that takes information from Dolibarr’s Supplier_Invoice using the REST API and parses the data I need to create a particular PDF form my company requires to be submitted for payment.

I am using the tcpdf library and php to create the pdf form and display it on the local computer for printing. Additionally, I want to take a copy of the pdf and save it back to Dolibarr ECM.

Currently I am able to create the pdf form and save it locally to view it and print it. My problem is when I try to save the file back to Dolibarr I sometimes get a corrupt file saved in the ECM. But with some invoices it saves and reads just fine.

I am using tcpdf ($pdf->Output( $filename, “E”) to create a base64 encoded string, then pass that string to the REST API via POST Documents.

My function to achieve this is below:

<?php

// POST file to dolibarr api
function fcn_postPDFDocument($logger, $apiKey, $apiUrl, $pdfFileName, $modulepart, $ref, $attachment)
{

    $apiEndpoint = "documents/upload";
    $parameters = [
        "filename" => "$pdfFileName",
        "modulepart" => "$modulepart",
        "ref" => "$ref",
        "subdir" => "",
        "filecontent" => "chunk_split(file_get_contents($attachment))",
        "fileencoding" => "base64",
        "overwriteifexists" => "1",
        "createdirifnotexists" => "1"
    ];

$arrPostDocument = callAPI("POST", $apiKey, $apiUrl . "/" . $apiEndpoint, json_encode($parameters));
$arrPostDocument = json_decode($arrPostDocument, true);

if (isset($arrPostDocument["error"]) && $arrPostDocument["error"]["code"] >= "300") {
    echo "<br>Error in fcn_postPDFDocument - " . json_encode($arrPostDocument["error"]["message"]);
    $logger->critical(json_encode($arrPostDocument));
    exit;
}
return $arrPostDocument;

}

If I remove the chunk_split from

“filecontent” => “chunk_split(file_get_contents($attachment))”,

to this:

“filecontent” => “file_get_contents($attachment)”,

the files that were originally created successfully get corrupted, but the original files that were corrupt will create ok.

Sorry, I know this is long winded but any help would be appreciated.

Thank you