pdf-lib functionality: launch hyperlinks in a new browser tab

I am currently working on incorporating hyperlinks into a PDF file using the pdf-lib JavaScript library. However, I've encountered an issue where when I click on a link in the PDF while viewing it in a browser, it opens the corresponding webpage in the same tab instead of a new tab. Is there a way to modify this behavior so that the link opens in a new tab?

export const drawLink = (
  x: number,
  y: number,
  item: TransformedEvent,
  haufefontSans: PDFFont,
  currentPage: PDFPage,
  pdfDoc: PDFDocument,
  linkImg: PDFImage
) => {
  if (getTexts.link(item).trim() === "nothing_to_link") {
    return y;
  } else {
    const linkAnnotation: PDFDict = pdfDoc.context.obj({
      Type: "Annot",
      Subtype: "Link",
      Rect: [x, y - 10, x + 150, y + 10],
      Border: [0, 0, 0],
      C: [0, 0, 1],
      A: {
        Type: "Action",
        S: "URI",
        URI: PDFString.of(getTexts.link(item).trim()),
        // NewWindow: true,  <-- this does not work.
      },
    });
    const linkAnnotationRef = pdfDoc.context.register(linkAnnotation);

    currentPage.drawText("mehr erfahren", {
      x: x + 18,
      y: y,
      size: 13,
      color: red,
      font: haufefontSans,
    });
    currentPage.drawImage(linkImg, {
      x: x + 2,
      y: y - 2,
      width: 11,
      height: 11,
    });
    y -= 13;

    let existingAnnots: PDFObject[] = [];
    const existingAnnotsObj = currentPage.node.get(PDFName.of("Annots"));
    if (existingAnnotsObj instanceof PDFArray) {
      existingAnnots = existingAnnotsObj.asArray().slice();
    } else if (existingAnnotsObj) {
      existingAnnots.push(existingAnnotsObj);
    }
    existingAnnots.push(linkAnnotationRef);
    currentPage.node.set(
      PDFName.of("Annots"),
      pdfDoc.context.obj(existingAnnots)
    );
    return y;
  }
};

Answer №1

There are typically two methods for creating a clickable link in any PDF document that will function properly with PDF readers.

As outlined in the PDF Standard:

PDF contains elements like annotations and hyperlinks that are separate from the main page content but are essential for interactive viewing and sharing of documents.

A uniform resource identifier (URI) is a string used to identify and locate a resource on the Internet, usually a file linked within the document. This can also refer to a query or other entity. URI actions trigger the resolution of a URI link. "Table 210 — Additional entries specific to a URI action" illustrates the dictionary entries unique to this type of action.

The first method involves displaying the URL text visibly (there is intentionally a gap here), such as
https: //stackoverflow.com/questions/78260497 It's important to note how the browser automatically generates a hyperlink based on web viewer standards.

In a PDF, there should not be any gaps pdf-lib: open links in new tab, but users have the freedom to decide what action they want to take with a link since no predefined action enforces "open in new tab," "open in new window," or even "open in browser" if the PDF viewer is an editor for reading PDFs.

https://i.sstatic.net/1ErOX.png

The second type of hyperlink is a PDF action that does not require scripts because it is integrated into the reader, attempting to direct the user to a URL starting with https:// from the specified area of the page. Ultimately, it is left to the user to determine the preferred method for this action through the viewer's settings. https://i.sstatic.net/lEGHW.png https://i.sstatic.net/fk19t.png https://i.sstatic.net/z6ADw.png

Answer

Therefore, by default, relocating a URI will replace the current viewport content. This may result in navigating to a different "Page" within the same PDF, another Page in a separate PDF, or a website. However, according to PDF design, the default PDF "/Action" occurs in the same tab.

Some more complex attempts involve scripted actions to display secondary modals featuring multimedia content (to a limited extent) or previously SWF-driven interactions. But these practices are strongly discouraged and often do not function correctly in most secure PDF viewers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with dynamically loading jQuery arise specifically on certain websites

Code: initializeJQuery(); function initializeJQuery() { if (typeof jQuery === "undefined") { var scriptElement = document.createElement('script'); scriptElement.setAttribute("type", "text/javascript"); scriptElement.setAttribute("sr ...

The style of react-router links remains unvisited

Currently working on a small website using React Router, I've encountered an issue where only the homepage link receives the visited styles. The other links do not display the visited style, even after being visited. Check out the code here Here is ...

Storing an image as an encoded string in MongoDB: Step-by-step guide

Currently, my goal is to transform an image into a string and store it in MongoDB. Additionally, I would like the ability to decode it at a later time. My approach involves solely using Express, MongoDB, and ReactJS. I specifically do not want to upload t ...

The modal appears on the screen prior to the content being shown

While attempting to render a bootstrap modal with content from a REST call, I am encountering an issue where the modal appears before the content has finished populating. The modal is triggered by a button click event. If I click the button again after wa ...

Issue: Connection Problem in React, Express, Axios

I've encountered an issue while attempting to host a website on an AWS EC2 instance using React, Express, and Axios. The specific problem I'm facing is the inability to make axios calls to the Express back-end that is running on the same instanc ...

Issue with displaying Youtube search API results on EJS template file

I'm currently trying to integrate the YouTube Search API into my website. However, when I make the API call from my route, the results are returned but the page is rendered before the results finish processing - likely due to the asynchronous behavior ...

Unable to extract query parameters from URL using Express JS as req.query returns an empty object

I came across discussions about this issue here and here, but unfortunately, the solutions provided didn't work for me. I'm attempting to extract parameters from the URL using req.query. In my server.js file, I've implemented the following: ...

Angular's $http.get method allows you to make HTTP

My goal is to display all lists and the tasks associated with each list. In my controller, I have the following code: $http.get('api/list/').success(function (data) { $scope.lists = data; $scope.tasks = data[0].Task; ...

Error found: Unexpected character in JSON data at line 1, position 4

Here is a json encoded string: { "user": [{ "id": "45", "name": "Raj", "loc": "kizhakood", "dist": "wayanad", "phone": "9815678421", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Issue with Foundation 6 not triggering the change.zf.slider event

Hey there, this is my first time posting and I could really use some help... I'm struggling to make the $("[data-slider]").on('change.zf.slider', function(){}); event trigger. I've attempted using the id of the element like so $(" ...

What is the reason for $(this) being appropriately recognized for click events but not for hover actions?

Why does this work on an element-by-element basis? <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> &l ...

How can you identify if JavaScript is turned off without relying on the noscript tag?

While working on designing a pop-up notification for cases when JavaScript is disabled, I incorporated html, css, and bootstrap elements into my project. An issue arose as I pondered if there exists a method to identify whether the html class within my p ...

The function range.insertNode() is failing to insert the text node as it should

I'm currently working on developing a Chrome extension. Essentially, I want the user to be able to insert HTML format tags before and after selected text when they click on a content menu option. These tags are added in an event page that sends the f ...

What are the steps for creating a dropdown menu that allows for easy selection of the correct item

I am dealing with a dropdown menu as shown below. <select name="slt"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="3">Three +</option&g ...

Is it possible to simultaneously press two keys in WebdriverIO?

Currently, I'm working on writing code with WebdriverIO that involves pressing the shift and tab keys simultaneously. So far, I've successfully managed to press each key individually using browser.keys("\uE004"); and browser.keys("\uE0 ...

Selecting items using raycasting

Currently attempting to select objects when clicked, using the common code found in various examples: function onMouseDown(evt) { evt.preventDefault(); canvasAbsoluteHeight = $('canvas').height(); canvasAbsoluteWidth = $('canv ...

Selecting elements with special characters in their IDs using JQuery can be done

I am facing an issue with this HTML code where the Id includes special characters: <input type="text" id="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

.then() failing to wait for completion of all promises

Currently, I am loading multiple gltf models using an async function. After that, I go through the results using .then() and add the models to my scene. However, everything works perfectly fine until I decide to remove one of the models from the source. Sp ...

What could be causing the jQuery blur function to malfunction in the tag-it library?

My attempts to implement JQuery's blur with the tag-it library have been unsuccessful. I cannot figure out why the blur function is not functioning properly. When clicking off the input field, nothing happens and there are no error messages. The al ...