Accessing file attachments using the full API

57 views
Skip to first unread message

Matt Parizeau

unread,
May 8, 2020, 5:00:40 PM5/8/20
to PDFTron WebViewer
Q:

How can I access file attachment data using the full API?

A:

Here is some sample code which show how to do this:

const doc = await instance.docViewer.getDocument().getPDFDoc();
const files = await PDFNet.NameTree.find(doc, "EmbeddedFiles");
if (await files.isValid()) {
 
// Traverse the list of embedded files.
 
const i = await files.getIteratorBegin();
 
for (var counter = 0; await i.hasNext(); await i.next(), ++counter) {
   
const entry_name = await i.key().then(key => key.getAsPDFText());
    console
.log("Part: " + entry_name);
   
const file_spec = await PDFNet.FileSpec.createFromObj(await i.value());
   
const stm = await file_spec.getFileData();
    console
.log(stm);

   
const filterReader = await PDFNet.FilterReader.create(stm);
   
const dataArray = [];
   
const chunkLength = 1024;
    let retrievedLength
= chunkLength;
   
while (chunkLength === retrievedLength) {
     
const bufferSubArray = await filterReader.read(chunkLength);
      retrievedLength
= bufferSubArray.length;
      dataArray
.push(bufferSubArray);
   
}
   
const bufferFinal = new Uint8Array(dataArray.length * chunkLength + retrievedLength);
   
for (let i = 0; i < dataArray.length; i++) {
     
const offset = i * chunkLength;
     
const currentArr = dataArray[i];
      bufferFinal
.set(currentArr, offset);
   
}
   
// example function from our sample which downloads the attachment
   
// you could also turn bufferFinal into a blob and open in WebViewer
    window
.saveBufferAsPDFDoc(bufferFinal, 'attachment.pdf');
 
}
}

Reply all
Reply to author
Forward
0 new messages