Laravel: add image on pdf with specific location

159 Views Asked by At

builing Laravel API, I have contract PDF file stored in remote server and saved in database with uid, and also online signature file, which is png. now when user clicks sign button, i want to take this png image and place it, lets say bottom right corner(this might change) in contract PDF. I tried it with laravel domPDF and laravel-snappy packages but no desired result. Example with domPDF:

    public function addSignatureToPdf(ContractFile $contractFile)
{
    // Path to the existing PDF file
    $pdfPath = storage_path($this::PDF_DIRECTORY_PATH . "combined_document{$contractFile->getHash()}.pdf");

    $existingPdfContent = file_get_contents($pdfPath);

    // Set the path to your signature image
    $signatureImagePath = storage_path('app/contract-files/დავით-ხაჩიძე.png');

    // Load the HTML content with the image (signature) added
    $html = view('pdf.signature', compact('signatureImagePath'))->render();
    $htmlWithEncoding = mb_convert_encoding($existingPdfContent . $html, 'HTML-ENTITIES', 'UTF-8');

    // Convert HTML to PDF
    $pdf = PDF::loadHTML($htmlWithEncoding);

    // Save the modified PDF
    $outputPdfPath = storage_path($this::PDF_DIRECTORY_PATH . 'modified_contract.pdf');
    file_put_contents($outputPdfPath, $pdf->output());

    return "PDF with signature added saved at: $outputPdfPath";
}

this created pdf file but with binary data in it and im not sure where and how do i append image to pdf. Any suggestions how to do it with laravel?

1

There are 1 best solutions below

2
moin On

convert image into base64

function convertImageToBase64($path) : string{
   try {
       return base64_encode(file_get_contents(public_path($path)));
   } catch (\Throwable $th) {
       return '';
   }
}