none
Add PDF attachment to OneNote page using Microsoft Graph API request RRS feed

  • Question

  • Hi,

    I want to add a PDF file to a OneNote page (attachment + printout). Has anyone achieved this? The page gets created and I see a PDF file shortcut. But when I click the PDF file icon on the OneNote page I get a message that the document is probably corrupt. Maybe the binary stream is not correct? Does anyone know how to correctly generate a binary or MIME stream from a pdf file?

    An example is showed on this page: https://graph.microsoft.io/GraphDocuments/api-reference/beta/api/notes_post_pages.htm. But is does not show how to generate the binary stream for a file.

    See the blocks below for my code. The binary stream is generated using this function: 

    function convertFileToBase64viaFileReader(url, callback){
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';    
        xhr.onload = function() {
          var reader  = new FileReader();
          reader.onloadend = function () {
             callback(reader.result);
          }
          reader.readAsDataURL(xhr.response);      
        };
        xhr.open('GET', url);
        xhr.send();
    }

    --MyAppPartBoundaryContent-Dis-data; name="Presentation"
    Content-type: text/html
    
    <!DOCTYPE html>
    <html>
    <head>
    	<title>OneNote test page</title>
    </head>
    <body>
    	<div style=";width:280px;top:120px;left:68px">
    		<p>Divs, images, and objects that are direct children of the body can be absolutely positioned elements on the page.</p><p>The body must specify data-absolute-enabled=&quot;true&quot; and the absolutely positioned elements must specify style=&quot;&quot;.</p><p>An absolutely positioned div can contain non-absolutely positioned elements, such as images and objects.</p>
    	</div>
    	<object data-attachment="Document.pdf" data="name:EmbeddedFileBlocksName1"  type="application/pdf" />
    </body>
    </html>
    
    --MyAppPartBoundary
    
    Content-Dis-data; name="EmbeddedFileBlocksName1"
    Content-type:application/pdf
    
    JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhubC1OTCkgL1N0cnVjdFRyZWVSb290IDEwIDAgUi9NYXJrSW5mbzw8L01hcmtlZCB0cnVlPj4+Pg0KZW5kb2JqDQoyIDAgb2JqDQo8PC9UeXBlL1BhZ2VzL0NvdW50IDEvS2lkc1sgMyAwIFJdID4+DQplbmRvYm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CjAwMDAwMDAwMTIgNjU1MzUgZg0KMDAwMDAwMDAxMyA2NTUzNSBmDQowMDAwMDAwMDE0IDY1NTM1IGYNCjAwMDAwMDAwMTUgNjU1MzUgZg0KMDAwMDAwMDAxNiA2NTUzNSBmDQowMDAwMDAwMDE3IDY1NTM1IGYNCjAwMDAwMDAwMTggNjU1MzUgZg0KMDAwMDAwMDAxOSA2NTUzNSBmDQowMDAwMDAwMDIwIDY1NTM1IGYNCjAwMDAwMDAwMjEgNjU1MzUgZg0KMDAwMDAwMDAwMCA2NTUzNSBmDQowMDAwMDAxODcyIDAwMDAwIG4NCjAwMDAwMDIxMDUgMDAwMDAgbg0KMDAwMDA4OTE4OCAwMDAwMCBuDQp0cmFpbGVyDQo8PC9TaXplIDI1L1Jvb3QgMSAwIFIvSW5mbyA5IDAgUi9JRFs8OTI2RDNFMTM5NzcyMzc0MzgzQkY2NkJCQjRBNkUzMTU+PDkyNkQzRTEzOTc3MjM3NDM4M0JGNjZCQkI0QTZFMzE1Pl0gPj4NCnN0YXJ0eHJlZg0KODk0NzgNCiUlRU9GDQp4cmVmDQowIDANCnRyYWlsZXINCjw8L1NpemUgMjUvUm9vdCAxIDAgUi9JbmZvIDkgMCBSL0lEWzw5MjZEM0UxMzk3NzIzNzQzODNCRjY2QkJCNEE2RTMxNT48OTI2RDNFMTM5NzcyMzc0MzgzQkY2NkJCQjRBNkUzMTU+XSAvUHJldiA4OTQ3OC9YUmVmU3RtIDg5MTg4Pj4NCnN0YXJ0eHJlZg0KOTAxMzQNCiUlRU9G
    
    --MyAppPartBoundary--

    $.ajax({
    	      type: "POST",
    	      url: "https://graph.microsoft.com/beta/me/notes/sections/" + SectionID + "/pages",	     	      
    	      headers: {
    	        'Authorization': 'Bearer ' + token,
    	        'Content-Type': 'multipart/form-data; boundary=MyAppPartBoundary'        
    	      },      
    	      data: htmlContent
    	    }).done(function (response) {
    	      console.log('Successfully fetched notebooks from OneNote.');
    	      console.log(response);      
    	    }).fail(function (error) {
    	      console.log(error);
    	      console.log('Fetching files from OneNote failed.');
    	    });


    Wednesday, January 6, 2016 9:14 AM

Answers

  • Hi j.van.bremen.

    Sorry for the confusion.

    To make the code above to runnable to create a new OneNote page with an attached PDF or image, we need to modify the code below to corresponding the file we upload:

       fd.append('file', input.files[0]);

    Here is runnable sample for your reference. Run the HTML below:

    <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
        <script>
    
            $(document).ready(function () {
                $("#Button1").click(createPage);
            })
    
            function createPage() {
                var fd = new FormData();
                var input = document.getElementById('File2');
                var images = document.getElementById('File3');
                var oneNotePage = $("#OneNotePage").val();
    
                var blob = new Blob([oneNotePage], { type: "text/html" });
    
                fd.append("Presentation", blob);
                fd.append('fileBlock1', input.files[0]);
                fd.append('imageBlock1', images.files[0]);
                $.ajax({
                    url: 'https://www.onenote.com/api/v1.0/me/notes/pages',
                    data: fd,
                    processData: false,
                    contentType: false,
                    headers: {
                        "Authorization": "Bearer EwB4Aq1DBAAUGCCXc8wU%2FzFu9QnLdZXy%2BYnElFkAAYvzKOymuCdQuurK934KbOWzjcpqEPAyGOh9tTW1fkmg70925E4NPmS8qE6wNSzeAj4KM8fMpFSD6XxKlf1fJtNMu8C8Del1fjZ9XyV%2FU5LZnK9C7ERCgQl5Z9LuZDtdT4Zd5avfZ5Wi43wqMlexey%2FokYsF8SZVA7doGbTm0pFdyxqtP6RASsLZeP2Vc3NR%2Bsj6GnC4YKpi%2Bu1C07l8W5Q9KfHwhzhyzsDMXiPQOiMR%2BoXOKsmw008HHPTwM22n0wVlzLRM5mSwhRxFKa03C0PuK5lrJHLnddkwxXc9ybvHE4qJT2tZT9CqAtWxjcQnbW459G5YSrqK%2FPd5bjzjrA0DZgAACMn0XStJvjuVSAFbHDKb0K8T%2F%2FBEL1zDZXYRgAY0SwZKVCJ8IsxIeubew4aup6%2BZJDy9fZcncqYipi2a1fBH3K6oIUpLEu%2BqB0fAQZpu3ANDvJyyrZJrhfoMXsj0Dd%2BK%2Be%2FFNb83XRsOaFhYVbJlVTZa6PsZwjQBYSEP2%2FsXoGh3rgmJ1ewgLC4XtQzOCn5lB6GxeunasPB%2BspfYKVJ%2BWzYrgqnlt4QPVlWFWjSXVzTN2YifrfTz5PUzsbBdHxMWkEuYatcH2o2CliHpGqytbEbhutzf30mqL0agmPr6KsEko7GNwb%2FF4R%2Bb0X7JapriTbiUQERwXNrUFkYP%2Bp7CjS7TFMuvErB5ynsqDFnJEuY%2BF%2F8NLaWHSVSF5boP79YtIICbuADEX4Wr5tG94bBcOPbivGyMOn7Ab8%2Bye%2BHwiR3ngL9RpDyl4KLyNYDUprIVO6nyXwE%3D",
                        "My-Second-Header": "second value"
                    },
                    type: 'POST',
                    success: function (data) {
                        alert(data);
                    }
                });
            }
        </script>
    </head>
    <body>
        <textarea id="OneNotePage" rows="20" cols="20"></textarea>
        <div>PDF:<input id="File2" type="file" /></div>
        <div>IMAGE:<input id="File3" type="file" /></div>
        <input id="Button1" type="button" value="Create" />
    </body>
    </html>

    Copy the HTML below into the textarea control:

    <!DOCTYPE html>
    <html>
      <head>
        <title>A page with rendered images and an attached file</title>
        <meta name="created" content="2015-07-22T09:00:00-08:00" />
      </head>
      <body>
        <p>Here's an image from an <i>online source</i>:</p>
        <img src="https://i-msdn.sec.s-msft.com/dynimg/IC726037.png" alt="an image on the page" width="500" />
        <p>Here's an image uploaded as <b>binary data</b>:</p>
        <img src="name:imageBlock1" alt="an image on the page" width="300" />
        <p>Here's a file attachment:</p>
        <object data-attachment="FileName.pdf" data="name:fileBlock1" type="application/pdf" />
      </body>
    </html>

    Upload the PDF and image then click the "Create" button.

    Note: Please replace the access token before you make a request to create the OnenNote page.

    Regards & Fei


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Wednesday, January 13, 2016 6:37 AM
    Moderator

All replies

  • Hi,

    To make a multipart/form-data post, we can use "FormData" object easily to construct the request. Here is an sample for your reference:
    HTML:

    <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
        <script>
           
            $(document).ready(function () {
                $("#Button1").click(createPage);
            })
           
            function createPage() {
                var fd = new FormData();
                var input = document.getElementById('File2');
    
                var oneNotePage = $("#OneNotePage").val();
    
                var blob = new Blob([oneNotePage], { type: "text/html" });
    
                fd.append("Presentation", blob);
                fd.append('file', input.files[0]);
                $.ajax({
                    url: 'https://www.onenote.com/api/v1.0/me/notes/pages',
                    data: fd,
                    processData: false,
                    contentType: false,
                    headers: {
                        "Authorization": "Bearer EwB4Aq1DBAAUGCCXc8wU%2FzFu9QnLdZXy%2BYnElFkAATmghqCJc5MVkFGS8fzO%2BZ9JG8jUs2aStDKhUcVJaYniXilGNOq8Hwsrg4rBbvHsXWPMxnhdeekxDyO%2Bv%2FPq5qnme7pwuDV26EPJTePrC0T8Ivkf53Sq%2Bba5sMts2f31IH2zak6Oot5Vqn8KnfrxneT%2Bw69eDM3Un%2FeWHmWUOjHute1tEvqr2L9xnT0nsr2RzCPz8F6DAj6WElYtZFZYeDzUIPvzmSc2vw6lQT0IP0NWiVciJjGy2zAsSkrAOQDSJqkHJYNUzLK9KNwcegzmARo7FVqzNfI84fKwVuMLV%2Fh6F1jQrcGQRyWDa8sRQimhun0OyuZkA9XeGghA%2F9lcXnoDZgAACENlJHFR3NzZSAHGlQzhJ3GXg%2BXqUBRkDzXssmksNX29vwsjTb7k1WHix8QUGLqcNVHOTucHky3cm6p7yRlW09Al1ISgEqXR1hQlJPPSpfG3kI7skVwFI7UD%2FP0wG2OUTJewIFFC22DTuUEI1%2FdNSjrBmQNxutZMOby%2BwzFFulKp2GTzaJ9kBaHT3IM%2BQR7Z69US9S7cbBZ6X1IqTzFzdKqGrGXTW6lfgAn4lmmt6jfJ%2F6vqjcIUqKZF0c3uFS9TJHzg2hTymfnO%2BmMBt%2B7ozE%2F%2FayoBkpYpamXJZRcZfjsByTh6pBsEPFQ%2Bhn9DiSdXUlAYRalgF4OiZLDqwLboQVM9aFKn3sXxmRC2Spc7j46wFA00nSi5z4kFs5daolKcrYG0VGeyHTLsvXJVICOg4AD4XaZYA5NGmvSGpDgV8uRru2yXvuQbAefpVWFz1uqg2KsbXwE%3D",
                        "My-Second-Header":"second value"
                    },
                    type: 'POST',
                    success: function (data) {
                        alert(data);
                    }
                });
            }
        </script>
    </head>
    <body>
            <textarea id="OneNotePage" rows="20" cols="20"></textarea>
            <div><input id="File2" type="file"  /></div>
            <input id="Button1" type="button" value="button" />
            <input id="Button2" type="submit" value="Button2" />
    </body>
    </html>
    To run this sample successfully, we need to past the HTML below to the HTML area control in the HTML page above and upload the PDF file using the HTML file control:

    <!DOCTYPE html>
    <html>
      <head>
        <title>A page with rendered images and an attached file</title>
        <meta name="created" content="2015-07-22T09:00:00-08:00" />
      </head>
      <body>
        <p>Here's an image from an <i>online source</i>:</p>
        <img src="http://..." alt="an image on the page" width="500" />
        <p>Here's an image uploaded as <b>binary data</b>:</p>
        <img src="name:imageBlock1" alt="an image on the page" width="300" />
        <p>Here's a file attachment:</p>
        <object data-attachment="FileName.pdf" data="name:fileBlock1" type="application/pdf" />
      </body>
    </html>
    Regards & Fei


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Saturday, January 9, 2016 6:27 AM
    Moderator
  • Hi Fei Xue,

    Thanks so much for your respone.

    I am getting the following error: XMLHttpRequest cannot load https://www.onenote.com/api/v1.0/me/notes/pages. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://deboefjes.sharepoint.com' is therefore not allowed access. The response had HTTP status code 401

    I have added crossDomain = true but the error still occurs.

    Do you also have an example for the Graph API? When I send the request to Graph I do not get this error but the PDF file in the OneNote page remains empty. 

    Monday, January 11, 2016 3:05 PM
  • Hi J.van.bremen,

    The issue of HTTP 401 is caused by the unauthorized, you need to replace the token with your available one.

    >>Do you also have an example for the Graph API? When I send the request to Graph I do not get this error but the PDF file in the OneNote page remains empty. <<

    You can get lots of samples about Office 365 from link below:
    Office 365 API code samples and videos

    In addition, you can play the Graph API with link below:
    https://graphexplorer2.azurewebsites.net/

    Regards & Fei


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Tuesday, January 12, 2016 7:31 AM
    Moderator
  • Hi,

    I have used the sample code and I am able to post a page to my OneNote notebook. However, when I try to attach a PDF file the file remains empty. Is there a working javascript sample that posts a new OneNote page with an attached PDF or image?

    Tuesday, January 12, 2016 8:01 AM
  • Hi j.van.bremen.

    Sorry for the confusion.

    To make the code above to runnable to create a new OneNote page with an attached PDF or image, we need to modify the code below to corresponding the file we upload:

       fd.append('file', input.files[0]);

    Here is runnable sample for your reference. Run the HTML below:

    <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
        <script>
    
            $(document).ready(function () {
                $("#Button1").click(createPage);
            })
    
            function createPage() {
                var fd = new FormData();
                var input = document.getElementById('File2');
                var images = document.getElementById('File3');
                var oneNotePage = $("#OneNotePage").val();
    
                var blob = new Blob([oneNotePage], { type: "text/html" });
    
                fd.append("Presentation", blob);
                fd.append('fileBlock1', input.files[0]);
                fd.append('imageBlock1', images.files[0]);
                $.ajax({
                    url: 'https://www.onenote.com/api/v1.0/me/notes/pages',
                    data: fd,
                    processData: false,
                    contentType: false,
                    headers: {
                        "Authorization": "Bearer EwB4Aq1DBAAUGCCXc8wU%2FzFu9QnLdZXy%2BYnElFkAAYvzKOymuCdQuurK934KbOWzjcpqEPAyGOh9tTW1fkmg70925E4NPmS8qE6wNSzeAj4KM8fMpFSD6XxKlf1fJtNMu8C8Del1fjZ9XyV%2FU5LZnK9C7ERCgQl5Z9LuZDtdT4Zd5avfZ5Wi43wqMlexey%2FokYsF8SZVA7doGbTm0pFdyxqtP6RASsLZeP2Vc3NR%2Bsj6GnC4YKpi%2Bu1C07l8W5Q9KfHwhzhyzsDMXiPQOiMR%2BoXOKsmw008HHPTwM22n0wVlzLRM5mSwhRxFKa03C0PuK5lrJHLnddkwxXc9ybvHE4qJT2tZT9CqAtWxjcQnbW459G5YSrqK%2FPd5bjzjrA0DZgAACMn0XStJvjuVSAFbHDKb0K8T%2F%2FBEL1zDZXYRgAY0SwZKVCJ8IsxIeubew4aup6%2BZJDy9fZcncqYipi2a1fBH3K6oIUpLEu%2BqB0fAQZpu3ANDvJyyrZJrhfoMXsj0Dd%2BK%2Be%2FFNb83XRsOaFhYVbJlVTZa6PsZwjQBYSEP2%2FsXoGh3rgmJ1ewgLC4XtQzOCn5lB6GxeunasPB%2BspfYKVJ%2BWzYrgqnlt4QPVlWFWjSXVzTN2YifrfTz5PUzsbBdHxMWkEuYatcH2o2CliHpGqytbEbhutzf30mqL0agmPr6KsEko7GNwb%2FF4R%2Bb0X7JapriTbiUQERwXNrUFkYP%2Bp7CjS7TFMuvErB5ynsqDFnJEuY%2BF%2F8NLaWHSVSF5boP79YtIICbuADEX4Wr5tG94bBcOPbivGyMOn7Ab8%2Bye%2BHwiR3ngL9RpDyl4KLyNYDUprIVO6nyXwE%3D",
                        "My-Second-Header": "second value"
                    },
                    type: 'POST',
                    success: function (data) {
                        alert(data);
                    }
                });
            }
        </script>
    </head>
    <body>
        <textarea id="OneNotePage" rows="20" cols="20"></textarea>
        <div>PDF:<input id="File2" type="file" /></div>
        <div>IMAGE:<input id="File3" type="file" /></div>
        <input id="Button1" type="button" value="Create" />
    </body>
    </html>

    Copy the HTML below into the textarea control:

    <!DOCTYPE html>
    <html>
      <head>
        <title>A page with rendered images and an attached file</title>
        <meta name="created" content="2015-07-22T09:00:00-08:00" />
      </head>
      <body>
        <p>Here's an image from an <i>online source</i>:</p>
        <img src="https://i-msdn.sec.s-msft.com/dynimg/IC726037.png" alt="an image on the page" width="500" />
        <p>Here's an image uploaded as <b>binary data</b>:</p>
        <img src="name:imageBlock1" alt="an image on the page" width="300" />
        <p>Here's a file attachment:</p>
        <object data-attachment="FileName.pdf" data="name:fileBlock1" type="application/pdf" />
      </body>
    </html>

    Upload the PDF and image then click the "Create" button.

    Note: Please replace the access token before you make a request to create the OnenNote page.

    Regards & Fei


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Wednesday, January 13, 2016 6:37 AM
    Moderator