Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.97k stars 671 forks source link

Adding Outline to an existing pdf document with outlines. #1151

Open NidhiMohan opened 2 years ago

NidhiMohan commented 2 years ago

What were you trying to do?

Hi,

I have a pdf document and I am trying to add bookmarks/outlines to it. It already has a few existing outlines. I followed this blog to create the outline .

This issue here is when I save the pdf after adding new outlines, the outlines get disappeared.

How did you attempt to do it?

`const doc = await PDFDocument.load(documentBuffer); const pageRefs = getPageRefs(doc);

const outlinesDictRef = doc.context.nextRef(); const outlineItem1Ref = doc.context.nextRef(); const outlineItem2Ref = doc.context.nextRef(); const outlineItem3Ref = doc.context.nextRef();

const outlineItem1 = createOutlineItem( doc, "Page 1 new", outlinesDictRef, outlineItem2Ref, pageRefs[0], );

const outlineItem2 = createOutlineItem( doc, "Page 2 new", outlinesDictRef, outlineItem3Ref, pageRefs[1] );

const outlineItem3 = createOutlineItem( doc, "Page 3 new", outlinesDictRef, outlineItem2Ref, pageRefs[2], true ); const outlinesDictMap = new Map(); outlinesDictMap.set(PDFName.Type, PDFName.of("Outlines")); outlinesDictMap.set(PDFName.of("First"), outlineItem1Ref); outlinesDictMap.set(PDFName.of("Last"), outlineItem3Ref); outlinesDictMap.set(PDFName.of("Count"), PDFNumber.of(3));

doc.catalog.set(PDFName.of("Outlines"), outlinesDictRef);

const outlinesDict = PDFDict.fromMapWithContext(outlinesDictMap, doc.context);

//First 'Outline' object. Refer to table H.3 in Annex H.6 of PDF Specification doc. doc.context.assign(outlinesDictRef, outlinesDict);

//Actual outline items that will be displayed doc.context.assign(outlineItem1Ref, outlineItem1); doc.context.assign(outlineItem2Ref, outlineItem2); doc.context.assign(outlineItem3Ref, outlineItem3);

const file = await doc.save(); `

What actually happened?

The old outlines are getting overridden by the newly added outline.

What did you expect to happen?

I expect it to add new outlines but also show me the existing outlines when I save the pdf.

How can we reproduce the issue?

Add outlines to an existing PDF that already have outlines.

Version

"pdf-lib": "^1.17.1",

What environment are you running pdf-lib in?

Browser

Checklist

Additional Notes

No response

ZhouChuanlin001 commented 1 year ago

Can I ask how to add an outline to an existing pdf document

saran-surya commented 2 months ago

@ZhouChuanlin001 , You still stuck with the issue ?