pdf-lib icon indicating copy to clipboard operation
pdf-lib copied to clipboard

Is it possible to add links to objects?

Open masterRokshi opened this issue 8 years ago • 5 comments

For example add a link on the text, on the rectangle etc.

masterRokshi avatar Nov 14 '18 09:11 masterRokshi

Hello @masterRokshi. My apologies for the late response.

You certainly can add links to documents with pdf-lib. There isn't currently a nice high-level API for doing it though, so the code is a big ugly. Here's an example:

import {
  drawText,
  PDFArray,
  PDFContentStream,
  PDFDictionary,
  PDFDocument,
  PDFDocumentFactory,
  PDFDocumentWriter,
  PDFName,
  PDFNumber,
  PDFString,
} from 'pdf-lib';

/* (1) Create a new PDF document */
const pdfDoc = PDFDocumentFactory.create();

/* (2) Embed a standard font within the document */
const [FontHelvetica] = pdfDoc.embedStandardFont('Helvetica');

/* (3) Define constants for the page's width and height */
const PAGE_WIDTH = 500;
const PAGE_HEIGHT = 500;

/* (4) Create the link annotation/object */
const linkAnnotation = pdfDoc.register(
  PDFDictionary.from(
    {
      Type: PDFName.from('Annot'),
      Subtype: PDFName.from('Link'),
      /* Bounds of the link on the page */
      Rect: PDFArray.fromArray(
        [
          PDFNumber.fromNumber(145), // lower left x coord
          PDFNumber.fromNumber(PAGE_HEIGHT / 2 - 5), // lower left y coord
          PDFNumber.fromNumber(358), // upper right x coord
          PDFNumber.fromNumber(PAGE_HEIGHT / 2 + 15) // upper right y coord
        ],
        pdfDoc.index
      ),
      /* Give the link a 2-unit-wide border, with sharp corners */
      Border: PDFArray.fromArray(
        [
          PDFNumber.fromNumber(0),
          PDFNumber.fromNumber(0),
          PDFNumber.fromNumber(2)
        ],
        pdfDoc.index
      ),
      /* Make the border color blue: rgb(0, 0, 1) */
      C: PDFArray.fromArray(
        [
          PDFNumber.fromNumber(0),
          PDFNumber.fromNumber(0),
          PDFNumber.fromNumber(1)
        ],
        pdfDoc.index
      ),
      /* URI to be visited when the link is clicked */
      A: PDFDictionary.from(
        {
          Type: PDFName.from('Action'),
          S: PDFName.from('URI'),
          URI: PDFString.fromString('https://github.com/Hopding/pdf-lib')
        },
        pdfDoc.index
      )
    },
    pdfDoc.index
  )
);

/* (5) Draw some text for the link to be placed over */
const contentStream = pdfDoc.register(
  pdfDoc.createContentStream(
    drawText('Link to the pdf-lib GitHub Repo', {
      x: 150,
      y: PAGE_HEIGHT / 2,
      font: 'Helvetica',
      size: 15,
      colorRgb: [0, 0, 1]
    })
  )
);

/* (6) Create a page and add everything to it */
const page = pdfDoc
  .createPage([PAGE_WIDTH, PAGE_HEIGHT])
  .set('Annots', PDFArray.fromArray([linkAnnotation], pdfDoc.index))
  .addContentStreams(contentStream)
  .addFontDictionary('Helvetica', FontHelvetica);

/* (7) Add the page to the PDF document */
pdfDoc.addPage(page);

/* (8) Serialize the PDF document */
const pdfBytes = PDFDocumentWriter.saveToBytes(pdfDoc);

And here is the resulting document: pdf_with_link.pdf

Let me know if you're looking for something different and I can provide an example more fitting for your use case.

Hopding avatar Nov 22 '18 14:11 Hopding

Thanks a bunch ! Amazing work you have done with this lib!

masterRokshi avatar Nov 27 '18 14:11 masterRokshi

Thanks, I’m glad you find it useful!

Hopding avatar Nov 27 '18 23:11 Hopding

Hey @Hopding . I was able to add one link per page through this method, is there a way we can add multiple links on same page, as it is getting overriden once i add other link

dipeshbansal avatar May 17 '23 10:05 dipeshbansal

@Hopding I was working on adding multiple links to the pdf. Here is how my pdf turned out to be. sample.pdf Everything works fine but I have a question. While setting the node, the existingAnnotation has empty array and unless I push the first link twice, the link is not working. If I don't update the array twice, the first link doesnt work. Everything except that does however. Can you help?

const createPageLinkAnnotation = (page, uri, placeHolder, width) => {
  if (!uri) return null;
  const position = [
    placeHolder.formField.coordinates.x,
    placeHolder.formField.coordinates.y,
    placeHolder.formField.coordinates.x + width,
    placeHolder.formField.coordinates.y - placeHolder.height,
  ];
  return page.doc.context.register(
    page.doc.context.obj({
      Type: "Annot",
      Subtype: "Link",
      Rect: position,
      Border: [0, 0, 0],
      C: [0, 0, 2],
      A: {
        Type: "Action",
        S: "URI",
        URI: PDFString.of(uri),
      },
    })
  );
};

for (const placeHolder of fileDetails?.fields) {
  const currentPageIndex = placeHolder?.formField?.pageIndex;
  const currentPage = pages[currentPageIndex];
  if (!currentPage) return;

//I am drawing the multi line url text here and creating page annotation on same coordinate below
  const fontFamily =
    placeHolder?.fontStyle?.bold && placeHolder?.fontStyle?.italics
      ? customBoldItalicFont
      : placeHolder?.fontStyle?.bold
      ? customBoldFont
      : placeHolder?.fontStyle?.italics
      ? customItalicFont
      : customFont;
  placeHolder.content = placeHolder?.urlData?.text || "";
  let pdfWriter = new PdfWriter(currentPage, placeHolder, fontFamily);
  const contentWidth = pdfWriter.writeTextBox();

  const redirectToLink = placeHolder?.urlData?.url || "";
  const link = createPageLinkAnnotation(
    currentPage,
    redirectToLink,
    placeHolder,
    contentWidth
  );
  if (link) {
    const existingAnnotations = currentPage.node.get(PDFName.of("Annots"));
    
    //Part of confusion. Why only adding link of array once doesn't work in initial case?
    if (existingAnnotations.array.length == 0) {
      existingAnnotations.array.push(link);
    }
    existingAnnotations.array.push(link);
    currentPage.node.set(PDFName.of("Annots"), existingAnnotations);
  }
}
const pdfBytes = await pdfDoc.save();

shrestharohit avatar Mar 01 '24 10:03 shrestharohit