PHP
<?php
use setasign\SetaPDF2\Core\Canvas\Canvas;
use setasign\SetaPDF2\Core\Document;
use setasign\SetaPDF2\Core\Document\Page\Annotation\LinkAnnotation;
use setasign\SetaPDF2\Core\Font\Standard\Helvetica;
use setasign\SetaPDF2\Core\PageFormats;
use setasign\SetaPDF2\Core\Writer\HttpWriter;
require_once('library/SetaPDF/Autoload.php');
$writer = new HttpWriter('link-annotation.pdf', true);
$document = new Document($writer);
// create a font instance
$font = Helvetica::create($document);
// let's create a page
$pages = $document->getCatalog()->getPages();
$page = $pages->create(PageFormats::A4);
// get access to the annotations helper
$annotations = $page->getAnnotations();
// lets' keep track of the text
$canvas = $page->getCanvas();
$canvas->setGraphicStateSync(
Canvas::GS_SYNC_CURRENT_TRANSFORMATION_MATRIX |
Canvas::GS_SYNC_TEXT
);
// write the link text and remember its start and end points
$text = $canvas->text()
->begin()
->setFont($font, 20)
->moveToNextLine(50, 700);
$start = $canvas->graphicState()->text()->getBottomUserSpace();
$text->showText('A link to https://www.setasign.com');
$end = $canvas->graphicState()->text()->getTopUserSpace();
$text->end();
// create the link annotation
$link = new LinkAnnotation(
array($start->getX(), $start->getY(), $end->getX(), $end->getY()),
new Document\Action\UriAction('https://www.setasign.com')
);
// define its color
$link->setColor(array(1, 0, 0));
// define a border and style
$borderStyle = $link->getBorderStyle();
$borderStyle->setWidth(1);
$borderStyle->setStyle(Document\Page\Annotation\BorderStyle::SOLID);
// add the new link annotation
$annotations->add($link);
// write another link text and remember its start and end points
$text = $canvas->text()
->begin()
->setFont($font, 20)
->moveToNextLine(50, 650);
$start = $canvas->graphicState()->text()->getBottomUserSpace();
$text->showText('This is a JavaScript action!');
$end = $canvas->graphicState()->text()->getTopUserSpace();
$text->end();
// create another link annotation
$link2 = new LinkAnnotation(
array($start->getX(), $start->getY(), $end->getX(), $end->getY()),
new Document\Action\JavaScriptAction('app.alert("SetaPDF rockz!");')
);
// define its color
$link2->setColor([0, 0, 1]);
// define a border and style
$borderStyle = $link2->getBorderStyle();
$borderStyle->setWidth(4);
$borderStyle->setStyle(Document\Page\Annotation\BorderStyle::DASHED);
$borderStyle->setDashPattern([2, 2]);
// add the new link annotation
$annotations->add($link2);
$document->save()->finish();