Skip to content

Instantly share code, notes, and snippets.

@gioiliop7
Created December 7, 2024 21:18
Show Gist options
  • Save gioiliop7/bd8201b26b664abd5720d1fbc34c9f9e to your computer and use it in GitHub Desktop.
Save gioiliop7/bd8201b26b664abd5720d1fbc34c9f9e to your computer and use it in GitHub Desktop.
[WORDPRESS,PHP] Sign a pdf with hashed username
function signPdf($attachmentId)
{
// Get the current user
$currentUser = wp_get_current_user();
$username = $currentUser->user_login;
$hashedUsername = hash('sha256', $username);
// Get the absolute server path of the attachment
$pdfPath = get_attached_file($attachmentId);
if (!$pdfPath) {
// Handle the case where the attachment ID doesn't exist or is not a valid attachment
return;
}
$fontPath = 'calibri-regular.php';
// Create a new PDF instance
$pdf = new Fpdi();
// Get the number of pages in the existing PDF
$pageCount = $pdf->setSourceFile($pdfPath);
// Loop through all pages
for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
// Add a new page for each existing page
$pdf->SetAutoPageBreak(false);
$pdf->AddPage();
$pdf->AddFont('Calibri', '', $fontPath);
$pdf->SetFont('Calibri', '', 9);
// Add text only on the first page
if ($pageNumber === 1) {
// Set X-coordinate for right-aligned text
$xRightAlign = $pdf->GetPageWidth() - 10;
$pdf->SetXY($xRightAlign, 10);
$pdf->Cell(0, 0, encodeForPdf('Digitally Signed'), 0, 1, 'R');
// Adjust Y-coordinate
$pdf->SetXY($xRightAlign, $pdf->GetY() + 5);
$pdf->Cell(0, 0, encodeForPdf("Υπογράφοντας"), 0, 1, 'R');
// Adjust Y-coordinate
$pdf->SetXY($xRightAlign, $pdf->GetY() + 5);
$pdf->Cell(0, 0, encodeForPdf($hashedUsername), 0, 1, 'R');
// Adjust Y-coordinate
$pdf->SetXY($xRightAlign, $pdf->GetY() + 5);
// Get date format and time format from WordPress settings
$dateFormat = get_option('date_format');
$timeFormat = get_option('time_format');
$formattedDate = date_i18n($dateFormat . ', ' . $timeFormat);
$pdf->Cell(0, 0, encodeForPdf($formattedDate), 0, 1, 'R');
}
// Import existing PDF page
$templateId = $pdf->importPage($pageNumber);
// Use the imported page as a template
$pdf->useTemplate($templateId, 0, 0);
}
// Output the modified PDF to the temporary file
$pdf->Output($pdfPath, 'F');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment