Adding text to a PDF which is signed/certified using PHP

162 Views Asked by At

I tried adding text to this PDF https://www.canada.ca/content/dam/ircc/migration/ircc/english/pdf/kits/forms/imm5476e.pdf using FPDF & FPDI, but unfortunately i received an error:

CrossReferenceException: This PDF document is encrypted and cannot be processed with FPDI.

This is my complete code:

<?php
$servpath = getcwd();

require_once('app/ThirdParty/fpdf/fpdf.php');
require_once('app/ThirdParty/fpdi/src/autoload.php');

use setasign\Fpdi\Fpdi;

try {
    // Initialize the FPDF object
    $pdf = new Fpdi();

    // Add a page from an existing PDF file
    $existingPdfPath = $servpath.'/files/project_files/7/imm5409e.pdf';
    $pdf->setSourceFile($existingPdfPath);
    $existingPdfPage = $pdf->importPage(1); // Import the first page from the existing PDF

    $pdf->AddPage();
    $pdf->useTemplate($existingPdfPage);

    // Add text on the first page
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->SetTextColor(255, 0, 0); // Red text color
    $pdf->SetXY(50, 50); // Set the position for the text
    $pdf->Cell(100, 10, 'IRCC First Name', 0, 1, 'C'); // Add the text

    // Output or save the modified PDF
    $outputPdfPath = $servpath.'/files/project_files/7/imm5409e-output.pdf';
    $pdf->Output($outputPdfPath, 'F');

    echo 'Text added successfully to the PDF.';
} catch (setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException $e) {
    echo 'CrossReferenceException: ' . $e->getMessage();
} catch (setasign\Fpdi\PdfParser\PdfParserException $e) {
    echo 'PdfParserException: ' . $e->getMessage();
} catch (Exception $e) {
    echo 'An error occurred: ' . $e->getMessage();
}
?>

So i tought this would not be possible and then tried removing the protection in the PDF, so that the code can work. But i can't even remove the encryption in the PDF file. It says:

You cannot change security on this document because the document is signed or certified.

enter image description here

Is there any way that i can add text to this PDF file?

One hack i found was to open the PDF file in the browser and Print -> Save as PDF. The saved file works if i want to edit with PHP(FPDF & FPDI).

Is there a better way to do this, so that i can add text to this PDF dynamically?

0

There are 0 best solutions below