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

Feature request: Adding hyperlinks

Open softwarerero opened this issue 6 years ago • 20 comments

Either page.drawText('<a href="https://pdf-lib.js.org//">pdf-lib</a>') or page.drawHtml('<a href="https://pdf-lib.js.org//">pdf-lib</a>') come to mind. It seems this is not supported, but why? Could this be added in the future?

Related issues: #412 (closed without comment) #515 (closed, referring to discord, but it seems to be a dead link)

softwarerero avatar Aug 06 '20 17:08 softwarerero

Hello @softwarerero!

You are correct that pdf-lib does not have a high level API for this. That is something I would very much like to provide. However, you can do it with a bit of low-level work. See https://github.com/Hopding/pdf-lib/issues/123#issuecomment-568804606.

If anybody is interested in creating a PR to add a high-level API for this, I'm happy to answer questions. Due to the nature of links and PDFs, it would probably end up looking closer to this:

page.drawLink('https://pdf-lib.js.org', { x: 50, y: 50, width: 100, height: 100 });
page.drawLink(pdfDoc.getPage(2), { x: 75, y: 75, width: 100, height: 100 });

Hopding avatar Aug 06 '20 17:08 Hopding

Thanks a lot, this library is wonderful. I found the PDF Specification) and see that I need a 'URI Action' but I'm not sure how to use it. Any help would be welcome, here is my intent:

const createPageLinkAnnotation = (pdf, uri, page) => {
  const { width, height } = page.getSize()
  pdf.context.register(
    pdf.context.obj({
      Type: 'Annot',
      Subtype: 'Link',
      /* Bounds of the link to the whole page */
      Rect: [
        0,
        0,
        width,
        height,
      ],
      /* Give the link a 2-unit-wide border, with sharp corners */
      Border: [0, 0, 2],
      /* Make the border color blue: rgb(0, 0, 1) */
      C: [0, 0, 1],
      /* Page to be visited when the link is clicked */
      // Dest: [pageRef, 'XYZ', null, null, null],
      // URI Action
      A: { Type: 'Action', S: 'URI', URI: uri },
      // A: { S: 'URI', URI: uri },
    }),
  )
}

softwarerero avatar Aug 06 '20 19:08 softwarerero

@softwarerero The way links are defined in the PDF spec, you define a rectangular section of the page that when clicked should activate the link (you'd probably want this rectangle to correspond to the bounds of piece of text). That's done with the Rect property of the annotation. To "use" the link, you simply register it in the document to obtain a reference. Then you add that reference to one or more pages (see https://github.com/Hopding/pdf-lib/issues/123#issuecomment-568804606):

const page = pdfDoc.getPage(0)
const link = createPageLinkAnnotation(pdfDoc, page.ref);
page.node.set(PDFName.of('Annots'), pdfDoc.context.obj([link]));

Note that you'll have to return the result of pdfDoc.register from createPageLinkAnnotation).

Hopding avatar Aug 06 '20 21:08 Hopding

@Hopding Thanks, but that example uses just a link to another page within the PDF, I want to link to a webpage.

softwarerero avatar Aug 06 '20 21:08 softwarerero

"Using" the link (connecting it to a page) works the same, regardless of what type of link the annotation represents (another PDF page or an external HTTP site).

Hopding avatar Aug 06 '20 21:08 Hopding

@Hopding Thanks again, I'm feeling close now, but the link is still not working:

const fs = require('fs')
const { PDFDocument, PDFName, StandardFonts, rgb, degrees, rotate } = require('pdf-lib')

const go = async () => {
  const pdf = await PDFDocument.create()
  const helveticaFont = await pdf.embedFont(StandardFonts.Helvetica)
  const page = pdf.addPage()
  page.drawText('https://pdf-lib.js.org/', {
    x: 23,
    y: 43,
    size: 20,
    font: helveticaFont,
    color: rgb(0.95, 0.1, 0.1),
    rotate: degrees(90),
  })

  const link = createPageLinkAnnotation(pdf, 'https://pdf-lib.js.org/', page)
  page.node.set(PDFName.of('Annots'), pdconst fs = require('fs')f.context.obj([link]));
  const pdfBytes = await pdf.save()  
  fs.writeFileSync(`~/test.pdf`, pdfBytes)
}

const createPageLinkAnnotation = (pdf, uri, page) =>
  pdf.context.register(
    pdf.context.obj({
      Type: 'Annot',
      Subtype: 'Link',
      Rect: [0, 30, 40, 230 ],
      Border: [0, 0, 2],
      C: [0, 0, 1],
      Dest: [uri, 'XYZ', null, null, null],
    }),
  )

go().catch(err => console.log(err))

softwarerero avatar Aug 06 '20 21:08 softwarerero

I wonder what the meaning of 'XYZ' is?

softwarerero avatar Aug 06 '20 21:08 softwarerero

Do you see an error? Can you share the document this produces?

Hopding avatar Aug 06 '20 21:08 Hopding

test.pdf

There is no error.

softwarerero avatar Aug 06 '20 21:08 softwarerero

Looks like you've wired it up to the page correctly. You'll just need to change some properties of the annotation for it to represent a URL. See the example I provided in https://github.com/Hopding/pdf-lib/issues/45#issuecomment-441043920. Note that it's for an older version of pdf-lib, but it should show you what properties and values you need in a link annotation in order to represent a URL.

Hopding avatar Aug 06 '20 22:08 Hopding

The difference I spotted is the A tag instead of Dest, but that seems to make no difference. I put my example with the changes in a repository: https://github.com/softwarerero/watermarkPdf

softwarerero avatar Aug 06 '20 23:08 softwarerero

Try this:

const createPageLinkAnnotation = (page: PDFPage, uri: string) =>
  page.doc.context.register(
    page.doc.context.obj({
      Type: 'Annot',
      Subtype: 'Link',
      Rect: [0, 30, 40, 230],
      Border: [0, 0, 2],
      C: [0, 0, 1],
      A: {
        Type: 'Action',
        S: 'URI',
        URI: PDFString.of(uri),
      },
    }),
  );

(async () => {
  const pdfDoc = await PDFDocument.create();
  const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
  const page = pdfDoc.addPage();
  page.drawText('https://pdf-lib.js.org/', {
    x: 23,
    y: 43,
    size: 20,
    font: helveticaFont,
    color: rgb(0.95, 0.1, 0.1),
    rotate: degrees(90),
  });

  const link = createPageLinkAnnotation(page, 'https://pdf-lib.js.org/');
  page.node.set(PDFName.of('Annots'), pdfDoc.context.obj([link]));

  const pdfBytes = await pdfDoc.save();
})();

Hopding avatar Aug 06 '20 23:08 Hopding

The PDFString made the difference, now it works. Thanks a lot!

softwarerero avatar Aug 06 '20 23:08 softwarerero

Hello,

Is there possibility to add several link annotations on one PDF page but not in one request just in few by one generic method? now if I add another link with new coordinates, on PDF with exist Annotation reference, new registration removes existing instance.

@EDIT I found it, instead of

pages[this.page - 1].node.set(PDFName.of('Annots'), pdfDoc.context.obj([linkAnnotationRef])); do pages[this.page - 1].node.addAnnot(linkAnnotationRef);

Bosper avatar Dec 15 '22 03:12 Bosper

Hello,

Is there possibility to add several link annotations on one PDF page but not in one request just in few by one generic method? now if I add another link with new coordinates, on PDF with exist Annotation reference, new registration removes existing instance.

@edit I found it, instead of

pages[this.page - 1].node.set(PDFName.of('Annots'), pdfDoc.context.obj([linkAnnotationRef])); do pages[this.page - 1].node.addAnnot(linkAnnotationRef);

Hey when i did this it is saying addAnnot is not defined

dipeshbansal avatar May 17 '23 10:05 dipeshbansal

@Bosper Regarding several link annotations on one PDF page: pdfDoc.context.obj([link1, link2, link3]) pdfDoc.context.obj() takes a list of link objects.

Sekin avatar Jun 13 '23 09:06 Sekin

Does anyone know of a way to make the link open a new window?

andrewjudd1 avatar Aug 30 '23 19:08 andrewjudd1

@sylvie-le Tried in MS word export to PDF, apparently it creates different rectangle for each line.

juneidy avatar Jul 01 '24 01:07 juneidy

Try this:

const createPageLinkAnnotation = (page: PDFPage, uri: string) =>
  page.doc.context.register(
    page.doc.context.obj({
      Type: 'Annot',
      Subtype: 'Link',
      Rect: [0, 30, 40, 230],
      Border: [0, 0, 2],
      C: [0, 0, 1],
      A: {
        Type: 'Action',
        S: 'URI',
        URI: PDFString.of(uri),
      },
    }),
  );

(async () => {
  const pdfDoc = await PDFDocument.create();
  const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
  const page = pdfDoc.addPage();
  page.drawText('https://pdf-lib.js.org/', {
    x: 23,
    y: 43,
    size: 20,
    font: helveticaFont,
    color: rgb(0.95, 0.1, 0.1),
    rotate: degrees(90),
  });

  const link = createPageLinkAnnotation(page, 'https://pdf-lib.js.org/');
  page.node.set(PDFName.of('Annots'), pdfDoc.context.obj([link]));

  const pdfBytes = await pdfDoc.save();
})();

@Hopding , I am using this code above, and I was able to add the link as well, but the link is added to somewhere else from what I am expecting. We have this Rect: [0, 30, 40, 230], what are each of the value in the array means. Also could you please tell where does the (0,0) of the whole pdf page is -> either bottom-left or top-left? Also I am using this code above to know where the link is added, but there is no border or color to the link:- Border: [0, 0, 2], C: [0, 0, 1],

It would be great if anyone could help me on the above points. Also do let me know if you need more info?

subhajit100 avatar Jul 10 '24 10:07 subhajit100

Try this:

const createPageLinkAnnotation = (page: PDFPage, uri: string) =>
  page.doc.context.register(
    page.doc.context.obj({
      Type: 'Annot',
      Subtype: 'Link',
      Rect: [0, 30, 40, 230],
      Border: [0, 0, 2],
      C: [0, 0, 1],
      A: {
        Type: 'Action',
        S: 'URI',
        URI: PDFString.of(uri),
      },
    }),
  );

(async () => {
  const pdfDoc = await PDFDocument.create();
  const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
  const page = pdfDoc.addPage();
  page.drawText('https://pdf-lib.js.org/', {
    x: 23,
    y: 43,
    size: 20,
    font: helveticaFont,
    color: rgb(0.95, 0.1, 0.1),
    rotate: degrees(90),
  });

  const link = createPageLinkAnnotation(page, 'https://pdf-lib.js.org/');
  page.node.set(PDFName.of('Annots'), pdfDoc.context.obj([link]));

  const pdfBytes = await pdfDoc.save();
})();

It works perfectly!

rimiti avatar Jan 06 '25 17:01 rimiti