Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Add internal links to PDF attachments #858

Closed
RichardBray opened this issue Apr 14, 2021 · 1 comment
Closed

[Question] Add internal links to PDF attachments #858

RichardBray opened this issue Apr 14, 2021 · 1 comment

Comments

@RichardBray
Copy link

I really enjoy using this library, one of the best for PDFs in Javascript out there.

I have a bit of an obscure request. I have created a PDF with attachments but I don't know how to create a link to an attachment in that PDF.

I know it's possible with Acrobat Reader DC and I've actually done it before.

And I know there is a way in pdf-lib to create an internal link to pages, but I don't know how to do it for attachments.

Here is the code I've come up with so far:

// imports omitted

async function main() {
  const pdfDoc = await PDFDocument.create();

  // - Setup PDF buffers
  const page1 = fs.readFileSync("...");
  const page2 = fs.readFileSync("...");
  const page3 = fs.readFileSync("...");

  const page1Doc = await PDFDocument.load(page1);

  // - Attach documents
  await pdfDoc.attach(page2, "page2.pdf", {
    mimeType: "application/pdf",
    description: "Page2",
    creationDate: new Date(),
    modificationDate: new Date(),
  });

  await pdfDoc.attach(page3, "page3.pdf", {
    mimeType: "application/pdf",
    description: "Page3",
    creationDate: new Date(),
    modificationDate: new Date(),
  });

  const [existingPage] = await pdfDoc.copyPages(page1Doc, [0]);
  pdfDoc.addPage(existingPage);

  // - Link to attachment
  const pdfUrlDict = pdfDoc.context.obj({
    Type: "Annot",
    Subtype: "Link",
    Rect: [50, 650, 50 + 100, 650 + 50],
    Border: [0, 0, 2],
    C: [0, 0, 1],
    Dest: [pdfDoc.embeddedFiles[0].ref, "XYZ", null, null, null],
  });
  const pdfUrl = pdfDoc.context.register(pdfUrlDict);
  existingPage.node.set(PDFName.of("Annots"), pdfDoc.context.obj([pdfUrl]));

  // - Save PDF
  const pdfBytes = await pdfDoc.save();
}
main();

The link is visible, it just doesn't open an attachment.

@Hopding
Copy link
Owner

Hopding commented Sep 24, 2021

Hello @RichardBray! Thanks for the well written and concise question 🙂. I'm not sure how to do this offhand, but I would like to support this type of thing with a higher level API. I've added it to the roadmap for tracking: #998.

If you're still interested in this and would like to dig in yourself, you can check section 12.6.4.2 Go-To Actions of the PDF spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants