1

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.

  • Welcome to Stack Overflow! Since you are new user, I recommend you read ["How to Ask a Good Question"](https://stackoverflow.com/help/how-to-ask). Asking question properly will help you get better answers and help others be able to understand your question if they have a similar problem. – Marc LaFleur Oct 24 '17 at 22:59
  • Thanks @MarcLaFleur-Microsoft I rephrased the question, we are asking about changing document properties such as 'Authors' or creating new custom document properties – Sebastian Allen Oct 26 '17 at 07:37

1 Answers1

0

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.

Bemis
  • 3,092
  • 2
  • 17
  • 24
  • I should note, this will convert the raw file type if it isn't of type `.pptx, .docx, or .xlsx`. So not technically a true file size for a raw file format not in that set. For my application, I use the size to estimate the file upload progress bar, so it isn't a deal breaker for me (xlsx tend to be larger than the byte formats) – Bemis Sep 11 '20 at 20:52