How to get the document information such as the author, created date and size using office word add-in 2013?
The Document.getFilePropertiesAsync method seems to only return the URL which is the file path.
How to get the document information such as the author, created date and size using office word add-in 2013?
The Document.getFilePropertiesAsync method seems to only return the URL which is the file path.
Bizarre that the developers didn't add file size to getFilePropertiesAsync
!
Fortunately, getFileAsync
(link) provides the file size. You should be able to call this to simply get the size, save that attribute and close the file.
This works for me, I have it in my App component:
const [fileName, setFileName] = useState("");
const [fileSize, setFileSize] = useState(0);
useEffect(() => {
Office.context.document.getFilePropertiesAsync(function(asyncResult) {
if (asyncResult && asyncResult.value && asyncResult.value.url) {
const name = asyncResult.value.url.replace(/^.*[\\\/]/, "");
setFileName(name);
}
});
}, []);
useEffect(() => {
if (fileName) {
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 4194304 }, function(result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
// Get the File object from the result.
const file = result.value;
setFileSize(file.size);
file.closeAsync(() => {});
}
});
}
}, [fileName]); // Note: if both async file calls fire, one of them will fail.
The comment at the end refers to this error https://stackoverflow.com/a/28743717/1467365. The if (fileName)
check in the 2nd useEffect hook ensures the file properties call completes before opening the file to get its size.
After fetching both you should be able to store them in a Context provider and access both attributes throughout your application.