/**
  * Updates the document instance.
  *
  * @param SetaPDF_Core_Document $document
  * @see ETSI TS 102 778-3 V1.2.1 - 4.7 Extensions Dictionary
  * @see ETSI EN 319 142-1 V1.1.0 - 5.6 Extension dictionary
  */
 public function updateDocument(SetaPDF_Core_Document $document)
 {
     $extensions = $document->getCatalog()->getExtensions();
     $extensions->setExtension('ESIC', '1.7', 2);
 }
    require 'credentials-ts.php';
} else {
    // path to your certificate and private key
    $cert = realpath('mycertandkey.crt');
    $passphrase = 'Passphrase for the private key in $cert';
    // your <customer name>
    $customerId = "";
}
// options for the SoapClient instance
$clientOptions = array('stream_context' => stream_context_create(array('ssl' => array('verify_peer' => true, 'cafile' => __DIR__ . '/ais-ca-ssl.crt', 'peer_name' => 'ais.swisscom.com'))), 'local_cert' => $cert, 'passphrase' => $passphrase);
// create a re-usable array of filenames (in/out)
$files = array(array('in' => 'files/tektown/Laboratory-Report.pdf', 'out' => 'output/tektown-timestamped.pdf'), array('in' => 'files/lenstown/Laboratory-Report.pdf', 'out' => 'output/lenstown-timestamped.pdf'), array('in' => 'files/etown/Laboratory-Report.pdf', 'out' => 'output/etown-timestamped.pdf'), array('in' => 'files/camtown/Laboratory-Report.pdf', 'out' => 'output/camtown-timestamped.pdf'));
// create document instances by the filenames
$documents = array();
foreach ($files as $file) {
    $documents[] = SetaPDF_Core_Document::loadByFilename($file['in'], new SetaPDF_Core_Writer_File($file['out']));
}
// initiate a batch instance
$batch = new SetaPDF_Signer_SwisscomAIS_Batch($customerId, $clientOptions);
// let's add PADES revoke information to the resulting signatures
$batch->setAddRevokeInformation('PADES');
try {
    // timestamp the documents and add the revoke information to the DSS of the documents
    $batch->timestamp($documents, true);
} catch (SetaPDF_Signer_SwisscomAIS_Exception $e) {
    echo 'Error in SwisscomAIS: ' . $e->getMessage() . ' with code ' . $e->getCode() . '<br />';
    /* Get the AIS Error details */
    echo "<pre>";
    var_dump($e->getResultMajor());
    var_dump($e->getResultMinor());
    echo "</pre>";
    // The account id (get in contact with info.ch@quovadisglobal.com to get demo credentials)
    $accountId = '';
    $clientId = '';
    // The password
    $password = '';
    $profile = 'Default';
    $pin = '';
}
// URL to the WSDL file
$wsdl = 'https://services.sealsignportal.com/sealsign/ws/BrokerClient?wsdl';
// Options for the SoapClient instance
$clientOptions = array('stream_context' => stream_context_create(array('ssl' => array('verify_peer' => true, 'cafile' => __DIR__ . '/cacert.pem', 'peer_name' => 'services.sealsignportal.com'))));
// create a HTTP writer
$writer = new SetaPDF_Core_Writer_Http('QuoVadis-Signed.pdf');
// let's get the document
$document = SetaPDF_Core_Document::loadByFilename('files/Laboratory-Report.pdf', $writer);
// now let's create a signer instance
$signer = new SetaPDF_Signer($document);
$signer->setAllowSignatureContentLengthChange(false);
$signer->setSignatureContentLength(32750);
// standard size by QuoVadis
// set some signature properies
$signer->setLocation($_SERVER['SERVER_NAME']);
$signer->setContactInfo('+01 2345 67890123');
$signer->setReason('testing...');
// create an QuoVadis module instance
$module = new SetaPDF_Signer_QuoVadis_Module($wsdl, $accountId, $password, $clientId, $pin, $profile, $clientOptions);
// login to QuoVadis system
$module->login();
// sign the document with the use of the module
$signer->sign($module);
 public function createScreeningPdf($hash)
 {
     $screening_entry_model = ScreeningEntry::findOne(['hash' => $hash]);
     $screening_form_model = ScreeningForm::findOne(['id' => $screening_entry_model->screening_form_id]);
     $subject_model = Subject::findOne(['id' => $screening_entry_model->subject_id]);
     $count = 1;
     //$permissions = \SetaPDF_Core_SecHandler::PERM_DIGITAL_PRINT ;
     $this->_font = 'Helvetica';
     //class_exists('TCPDF', true); // trigger Composers autoloader to load the TCPDF class
     $pdf = new \FPDI();
     $pdf->SetAutoPageBreak(true);
     // add a page
     $pdf->SetTopMargin(30);
     $pdf->AddPage();
     $pdf->setSourceFile(\yii::$app->basePath . "/../letterhead-mini-header.pdf");
     $tplIdx = $pdf->importPage(1);
     // use the imported page and place it at point 10,10 with a width of 100 mm
     $pdf->useTemplate($tplIdx, 0, 0);
     $pdf->SetFont($this->_font, '', 9);
     $pdf->SetXY(10, 6);
     $pdf->Cell(0, 3, 'Confidential - Participant screening form');
     $pdf->SetFont($this->_font, '', 12);
     $pdf->SetXY(10, 14);
     $pdf->MultiCell(150, 3, yii::$app->DateComponent->timestampToUkDate($screening_entry_model->created_at), 0, 'R');
     $pdf->MultiCell(100, 3, $screening_entry_model->screening_form_title, 0, '');
     $pdf->Ln();
     $pdf->SetFont($this->_font, '', 9);
     $pdf->Cell(100, 4, sprintf('Participant: %s %s (dob %s)', $screening_entry_model->subject->first_name, $screening_entry_model->subject->last_name, yii::$app->DateComponent->isoToUkDate($screening_entry_model->subject->dob)));
     $pdf->Cell(50, 4, sprintf('Identifier: %s', $screening_entry_model->subject->cubric_id), 0, '', 'R');
     $pdf->Ln();
     $pdf->Cell(100, 4, sprintf('Researcher: %s %s (project %s)', $screening_entry_model->researcher->first_name, $screening_entry_model->researcher->last_name, $screening_entry_model->project->code));
     $pdf->Cell(50, 4, sprintf('Resource: %s', $screening_entry_model->resource_title), 0, '', 'R');
     $pdf->SetXY(10, 38);
     $pdf->SetFont($this->_font, '', 12);
     $pdf->Cell(150, 4, sprintf('Responses'));
     $pdf->SetFont($this->_font, '', 9);
     $pdf->Ln();
     foreach (yii::$app->screeningresponse->getResponses($hash) as $response) {
         if (strlen($response['caption']) > 0) {
             $pdf->Ln();
             $pdf->MultiCell(180, 4, sprintf('%s ', $response['caption']), 0, 'U');
             $count = 1;
         }
         $pdf->MultiCell(180, 4, sprintf('%s. %s ', $count, $response['content']));
         $pdf->SetFont($this->_font, 'B', 9);
         if ($response['response'] === null) {
             $response['response'] = 'Not specified / Unknown.';
         }
         $pdf->MultiCell(180, 4, sprintf('%s ', $response['response']));
         $pdf->SetFont($this->_font, '', 9);
         $count++;
         $pdf->Ln();
     }
     $pdf->Ln();
     $pdf->SetFont($this->_font, '', 12);
     $pdf->Cell(180, 4, sprintf('Signatures'));
     $pdf->Ln();
     $pdf->Ln();
     $pdf->SetFont($this->_font, '', 9);
     $pdf->Cell(100, 4, 'Participant ');
     $pdf->Cell(100, 4, 'Researcher ');
     $pdf->Ln();
     $pdf->Ln();
     $currentX = $pdf->GetX();
     $currentY = $pdf->GetY();
     $pdf->Image(sprintf('/tmp/subject-%s.png', $hash), $currentX, $currentY);
     $currentX = $pdf->GetX();
     $pdf->Image(sprintf('/tmp/researcher-%s.png', $hash), $currentX + 100, $currentY);
     // now write some text above the imported page
     // NOW SET ScreeningEntry::progress_id = PUBLISHED so it cannot be edited again.
     // $pdfData = $pdf->Output('S');
     // create a writer
     // create a Http writer
     //$writer = new \SetaPDF_Core_Writer_Http("fpdf-sign-demo.pdf", true);
     // load document by filename
     //$document = new \SetaPDF_Core_Document::loadByString($pdfData, $writer);
     //$document = new \SetaPDF_Core_Reader_File($pdf->Output(), $writer);
     $writer = new \SetaPDF_Core_Writer_File("/Users/Spiro/tmp/myPDF.pdf");
     $document = \SetaPDF_Core_Document::loadByString($pdf->Output("S"), $writer);
     // let's prepare the temporary file writer:
     \SetaPDF_Core_Writer_TempFile::setTempDir("/tmp/");
     // create a signer instance for the document
     $signer = new \SetaPDF_Signer($document);
     // add a field with the name "Signature" to the top left of page 1
     $signer->addSignatureField(\SetaPDF_Signer_SignatureField::DEFAULT_FIELD_NAME, 1, \SetaPDF_Signer_SignatureField::POSITION_LEFT_BOTTOM, array('x' => 10, 'y' => 10), 180, 50);
     // set some signature properties
     $signer->setReason('Integrity');
     $signer->setLocation('CUBRIC');
     $signer->setContactInfo('+44 2920 703859');
     // ccreate an OpenSSL module instance
     $module = new \SetaPDF_Signer_Signature_Module_OpenSsl();
     // set the sign certificate
     $module->setCertificate(file_get_contents("/Users/spiro/Sites/projects/certs/certificate.pem"));
     // set the private key for the sign certificate
     $module->setPrivateKey(array(file_get_contents("/Users/spiro/Sites/projects/certs/key.pem"), ""));
     // create a Signature appearance
     $visibleAppearance = new \SetaPDF_Signer_Signature_Appearance_Dynamic($module);
     // choose a document to get the background from and convert the art box to an xObject
     $backgroundDocument = \SetaPDF_Core_Document::loadByFilename(Yii::getAlias('@frontend/web/img/cubric-logo.pdf'));
     $backgroundXObject = $backgroundDocument->getCatalog()->getPages()->getPage(1)->toXObject($document);
     // format the date
     $visibleAppearance->setShowFormat(\SetaPDF_Signer_Signature_Appearance_Dynamic::CONFIG_DATE, 'd-m-Y H:i:s');
     // disable the distinguished name
     $visibleAppearance->setShow(\SetaPDF_Signer_Signature_Appearance_Dynamic::CONFIG_DISTINGUISHED_NAME, false);
     // set the background with 50% opacity
     $visibleAppearance->setGraphic($backgroundXObject, 0.5);
     //$visibleAppearance->setBackgroundLogo($backgroundXObject, .5);
     // sign/certify the document
     // define the appearance
     $signer->setAppearance($visibleAppearance);
     $signer->sign($module);
     if (file_exists(sprintf('/tmp/subject-%s.png', $hash))) {
     }
     //   unlink(sprintf('/tmp/subject-%s.png' , $hash));
     if (file_exists(sprintf('/tmp/researcher-%s.png', $hash))) {
     }
     //     unlink(sprintf('/tmp/researcher-%s.png' , $hash));
     return true;
 }
$signer->setAllowSignatureContentLengthChange(false);
$signer->setSignatureContentLength(32000);
$signer->setSignatureFieldName($signatureFieldName);
// set some signature properties
$signer->setLocation($_SERVER['SERVER_NAME']);
$signer->setContactInfo('+01 2345 67890123');
$signer->setReason('testing...');
// create an Swisscom AIS module instance
$module = new SetaPDF_Signer_SwisscomAIS_Module($customerId, $clientOptions);
// let's add PADES revoke information to the resulting signatures
$module->setAddRevokeInformation('PADES');
// pass the timestamp module to the signer instance
$signer->setTimestampModule($module);
try {
    // create the document timestamp
    $signer->timestamp();
} catch (SetaPDF_Signer_SwisscomAIS_Exception $e) {
    echo 'Error in SwisscomAIS: ' . $e->getMessage() . ' with code ' . $e->getCode() . '<br />';
    /* Get the AIS Error details */
    echo "<pre>";
    var_dump($e->getResultMajor());
    var_dump($e->getResultMinor());
    echo "</pre>";
    die;
}
// get a document instance of the temporary result
$document = SetaPDF_Core_Document::loadByFilename($tempWriter->getPath(), $writer);
// update the DSS with the revoke information of the last response
$module->updateDss($document, $signatureFieldName);
// save and finish
$document->save()->finish();
 /**
  * Timestamps a collection of document instances.
  *
  * The document instances need to have writer instances setup properbly.
  *
  * @param SetaPDF_Core_Document[] $documents
  * @param bool $updateDss
  * @return bool
  * @throws SetaPDF_Core_Exception
  * @throws SetaPDF_Signer_Exception
  * @throws SetaPDF_Signer_Exception_ContentLength
  * @throws SetaPDF_Signer_SwisscomAIS_Exception
  */
 public function timestamp(array $documents, $updateDss = false)
 {
     $digestMethod = $this->_getDigestMethod();
     $data = array();
     $no = 0;
     foreach ($documents as $document) {
         $signer = new SetaPDF_Signer($document);
         $signer->setSignatureContentLength($this->getSignatureContentLength());
         $signer->setSignatureFieldName($this->getSignatureFieldName());
         $tmpDocument = $signer->preTimestamp(new SetaPDF_Core_Writer_TempFile());
         $data[$no] = array('document' => $document, 'signer' => $signer, 'tmpDocument' => $tmpDocument, 'digestValue' => $this->_getHash($tmpDocument->getHashFile()));
         $no++;
     }
     $req = array('SignRequest' => array('RequestID' => $this->_createRequestId(), 'Profile' => 'http://ais.swisscom.ch/1.0', 'OptionalInputs' => array('SignatureType' => 'urn:ietf:rfc:3161', 'ClaimedIdentity' => array('Name' => $this->_customerId), 'AdditionalProfile' => array('http://ais.swisscom.ch/1.0/profiles/batchprocessing', 'urn:oasis:names:tc:dss:1.0:profiles:timestamping')), 'InputDocuments' => array()));
     foreach ($data as $no => $documentData) {
         $req['SignRequest']['InputDocuments'][] = array('ID' => $no, 'DigestMethod' => array('Algorithm' => $digestMethod), 'DigestValue' => $documentData['digestValue']);
     }
     if ($this->_revokeInformation) {
         $req['SignRequest']['OptionalInputs']['AddRevocationInformation'] = array('Type' => $this->_revokeInformation);
     }
     $client = new SoapClient($this->_wsdl, array_merge($this->_clientOptions, array('trace' => true, 'encoding' => 'UTF-8', 'soap_version' => SOAP_1_1)));
     $this->_lastResult = $client->sign($req);
     $signResult = $this->_lastResult->SignResponse->Result;
     if ($signResult->ResultMajor !== 'urn:oasis:names:tc:dss:1.0:resultmajor:Success') {
         $exception = new SetaPDF_Signer_SwisscomAIS_Exception($signResult->ResultMessage->_);
         $exception->setRequest($req);
         $exception->setResult($this->_lastResult);
         throw $exception;
     }
     $timestamps = $this->_lastResult->SignResponse->SignatureObject->Other->SignatureObjects->ExtendedSignatureObject;
     if (!is_array($timestamps)) {
         $timestamps = array($timestamps);
     }
     foreach ($timestamps as $timestampData) {
         $timestamp = $timestampData->Timestamp->RFC3161TimeStampToken;
         $no = $timestampData->WhichDocument;
         $this->_signatures[$no] = $timestamp;
         $documentData = $data[$no];
         /**
          * @var $signer SetaPDF_Signer
          */
         $signer = $documentData['signer'];
         if (!$updateDss || !$this->_revokeInformation) {
             $signer->saveSignature($documentData['tmpDocument'], $timestamp);
         } else {
             $tempWriter = new SetaPDF_Core_Writer_TempFile();
             $writer = $documentData['document']->getWriter();
             $documentData['document']->setWriter($tempWriter);
             $signer->saveSignature($documentData['tmpDocument'], $timestamp);
             $document = SetaPDF_Core_Document::loadByFilename($tempWriter->getPath(), $writer);
             $this->updateDss($document, $this->getSignatureFieldName());
             $document->save()->finish();
         }
     }
     return true;
 }