No one has responded to this discussion for at least a year, so this information may be out of date. If you're looking for information about this topic, please search for a more recent discussion or post a new question.

Open PDF files in the browser

  • First of all I would like to thank  'jbooker' for resolving this issue - http://community.office365.com/en-us/f/154/t/2617.aspx

    I came up with a bit more elegant way of programming the similar issue by using jQuery.

     

    1) Step 1:Download pdf icon and name it as ICPDF.gif

    http://www.iconarchive.com/show/soft-scraps-icons-by-deleket/Adobe-PDF-Document-icon.html

     

    2) Step 2: Copy & Paste the below script in notepad (or
    any editor of your choice) and save it as javascript file. For example
    'jPDFViewer.js'

     


    <html>
       <head>
        <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>

     </head>
        <body>
        <script type="text/javascript">
        
        //The script will run after the page is loaded
        ExecuteOrDelayUntilScriptLoaded(Page_Load,"SP.js");


        // Load the page.
        function Page_Load() {
            try
                {
                    //setting icons
                    var $pdficons = $("td[class='ms-vb-icon'] img[title$='.pdf']");

                    $pdficons.each(function(index)
                                    {
                                       
    var siteCollectionUrl = document.location.protocol + "//" +
    document.location.host + _spPageContextInfo.siteServerRelativeUrl;
                                        var pdfImgLoc = siteCollectionUrl + "/SiteAssets/scripts/ICPDF.gif";
                                        $(this).attr({src: pdfImgLoc});

                                    }
                                   );

                    //assign javascript for the pdf files
                    var $items = $('.ms-vb a[href$=".pdf"]');
                    $items.each(function(index)

                                    {
                                       
    var $itemURL =  document.location.protocol + "//" +
    document.location.host + $(this).attr('href');
                                        $(this).removeAttr("onclick");
                                        $(this).unbind("click");

                                        $(this).attr({
                                                onclick: "javascript:OpenPDF('" + $itemURL + "')",
                                                onmousedown: "return VerifyHref(this,event,'0','AdobeAcrobat.OpenDocuments','')"

                                            });                               
                                     }
                                );
                }
                catch (e) {
                    alert(e.message);

                    }
            }

            function OpenPDF(itemPath) {
               document.write("<embed id='PDF' width='100%' height='100%' src='" + itemPath +"' type='application/pdf' />");

            }
        </script>       
        </body>
    </html> 


     

    3) Step 3:  Save and upload the jQuery file & the PDF icon file. In this example I've uploaded the files under the 'scripts' folder of 'Site Assets' library in the site collection. - "SiteCollection/Site Assets/scripts".  (Check the green shaded color in the script)

     

    Check the screen shots on how to enable the pdf via Content Editor Webpart.

    Click on 'OK' and you should see that pdf icons are populated for the PDF files and when clicked it should open in the browser.

     

    P.S: Make sure that you have installed the latest Adobe Acrobat Reader.

     

  • Vamsi,

    I like it!  Thanks for posting!

    Especially the part of altering the OnClick and OnMouseDown attribs which appear to be causing an extra Read\Edit message in sharepoint of late.  I noticed recently that the HTML output is different for PDF files and suspect MS may be preparing a path to open PDFs in the browser soon.

    They appear to be providing the "'Sharepoint.OpenDocuments'" argument in Mousedown and onclick now for PDF files which is new, I think.

    I'd like to try to see how it works when referenced in the masterpage and get it to open in a new window.

    Does it work well with Grouped doc lib view?

    Josh

  • Vamsi,

     

    I had a chance to try your code.  I like it because it removes the need for a separate viewer page and the jquery is a little easier to read.  I found a few things and altered them based on feedback from other users.

     

    1) failed in grouped view so I added some overrides to call Page_Load() upon expanding a group.

    2) failed when PDF name has apostrophe so I swaped quotes around.

    3) many folks prefer opening docs in new window so I altered OpenPDF() accordingly.

    4) dropped sitecollection stuff from URLs to stick with relative links. <EDIT: Okay not a good idea, I added them back>

    5) made it so it can be used in masterpage by removing <html><script> tags which required a workaround to include jquery library reference.

    6) image still failed when the file is checked out because the title includes the 'checked out to...' after file name.  I'm not experienced enough with jquery selectors to fix that quickly and I've run out of time for today.

     <EDIT:  #6 is fixed.  I also edited selector a little to handle pdf links on public site pages since it isn't easy to create a javascript link in public site editor.>

     

    Also, there is not SiteAssets library on P1 subscriptions so that's why I decided to have folks create a new library called Utilities.  That's not as important with this solution because the pdf.aspx viewer page is not required.

     

    Save the code below to a text file and reference it in your master page like so:

    <Script type="text/javascript" src="/utilities/pdf.js"></script>

     

    or add <Script type="text/javascript"></Script> tags in the file to use in Content Editor.

     

    Let me know your thoughts,

    Thanks again,

    Josh

     

    function IncludeJS(jsFile)
    {//includes external js file when this one loads
    //usage
    //IncludeJS('jsFile.js');
      document.write('<script type="text/javascript" src="'
        + jsFile + '"></scr' + 'ipt>');
    }
    //required jquery library
    IncludeJS('https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js');

        //The script will run after the page is loaded
        ExecuteOrDelayUntilScriptLoaded(Page_Load,"SP.js");

        // Load the page.
        function Page_Load() {
            try
                {
    var siteCollectionUrl = document.location.protocol + "//" +
     document.location.host + _spPageContextInfo.siteServerRelativeUrl;  //sitecollection url not needed for relative image location
    var pdfImgLoc =  "/utilities/ICPDF.gif"; 
                    //setting icons
                    var $pdficons = $("td[class='ms-vb-icon'] img[title*='.pdf' class!='ms-vb-icon-overlay']");//added * to catch checked out docs - excluded overlay imgs
        $pdficons = $pdficons.add("img[src='/_layouts/images/pdficon.gif']");
                    $pdficons.each(function(index)
                                    {
                                        //var pdfImgLoc = siteCollectionUrl + "/utilities/ICPDF.gif"; //moved to top of function for one-time variable set
                                        $(this).attr({src: pdfImgLoc});
                                    }
                                   );

                    //assign javascript for the pdf files
                    //var $items = $('.ms-vb a[href$=".pdf"]');
        var $items = $('a[href$=".pdf"]');  //removed .ms-vb class selector to catch public site links and app page links
                    $items.each(function(index)

                                    {
                                      
    //var $itemURL =  document.location.protocol + "//" +
    //document.location.host + $(this).attr('href');
    var $itemURL =  $(this).attr('href');  //use the href fixes for search pages
             $(this).removeAttr("onclick");
                                        $(this).unbind("click");

                                        $(this).attr({
                                                onclick: 'javascript:OpenPDF("' + $itemURL + '"); return false',
                                                onmousedown: "return VerifyHref(this,event,'0','','')"

                                            });   //return false added so href is not followed when open new window - quote marks swapped to handle file names with apostrophe                      
                                     }
                                );
                }
                catch (e) {
                    alert(e.message);

                    }
            }

            function OpenPDF(itemPath) {
       myTitle = itemPath.split('/').pop().toString()
       myWindow = window.open("", "",'toolbar=no')
       myWindow.document.write('<embed id="PDF" width="100%" height="100%" src="' + itemPath +'" type="application/pdf" />');//quote marks swapped to handle file names with apostrophe
       myWindow.document.title = myTitle
       myWindow.document.close()
            }
    //end required code
     

    //Optional Grouped View Fix
    // Override ExpGroupRenderData in init.js to call Page_Load() upon expand group
    ExpGroupRenderData = (function (old) {
        return function (htmlToRender, groupName, isLoaded) {
        var result = old(htmlToRender, groupName, isLoaded);
    Page_Load();
    };
    })(ExpGroupRenderData);

    ExpCollGroup = (function (old) {
        return function (c,h,m,l) {
        var result = old(c,h,m,l);
    Page_Load();
    };
    })(ExpCollGroup);

    //End Override

    //optional Open PDF in Browser Menu Item
    //Add Doc Item Menu 'Open PDF in Browser'
    function Custom_AddDocLibMenuItems(m, ctx)
    {
    var strDisplayText="Open PDF in Browser";
    var d= m.parentElement
    var a;
    while(a!=null&&a.tagName!="CTXName")a=FindSTSMenuTable(d,"CTXName");
    var b = itemTable.getElementsByTagName('a')[0];
    var c = b.href;
    var strAction='OpenPDF("' + c + '"); return false'
    var strImagePath="/utilities/icpdf.gif";
    //alert(strAction);
    //check if pdf extention
    var fileExt = c.split('.').pop().toLowerCase();
    if (fileExt == "pdf")
    {
    //add menu item
    CAMOpt(m, strDisplayText, strAction, strImagePath);
    }
     // add a separator to the menu
    CAMSep(m);
    //return false to render default menu options or True to prevent default menu
    return false;
    }
    //End Add Doc Item Menu

    1 out of 1 people found this post helpful.

  • PS...i ust got this email...wonder if the update includes PDF support???

    Dear Office 365 / SharePoint Online Administrator,

    Over the next few weeks, we will be updating your Office 365/SharePoint Online environment to bring a new set of features to your service. This is a planned service update. This e–mail explains the expected experience so you can convey the information to your users. You will receive a second notification 24 to 48 hours before we begin your update.

    During update your overall experience will not be affected. All aspects of SharePoint Online will continue to work — except during two known periods lasting less than 30 minutes. During this 30 minute period, users will not be able to add new content, edit or add items to lists, search indexing will pause, and you will not be able to make changes from within your SharePoint Online Administration Center.

    We appreciate your patience.

    Thank you,

    The Office 365 Team

  • I am using this newly modified code and the path /utilities/pdf.js does not work for me. When I create a new site collection, the path to the utilities library is myurl.sharepoint.com/sites/sitename/utilities. To reference it in the master page, I had to reference /sites/sitename/utilities for it to work.

  • Implemented as prescribed.  Icons and context menu works fine.  When link is invoked, the new window opens but the content of the window is empty.  Here is the source for the pop-up window "<embed id="PDF" width="100%" height="100%" src="fccs.sharepoint.com/.../FLEX_BROCHURE.pdf" type="application/pdf" />"

    Is there something else that I need to do to actually display the PDF?

  • Matt,

    The src attrib is incomplete due to a problem with the script.  In some cases relative URLs don't work as expected and the Vamsi's script was better that way!

    I edited my post above to correct this.  Please copy and overwrite your pdf.js.

    Let me know.

    Have a Great Day!

    Josh

  • Thanks Josh!  The url is no longer root-relative.  However, the PDF is still not displaying in the pop-up window.  It is as if the browser is not processing the embed tag??

    Page Source = <embed id="PDF" width="100%" height="100%" src="https://fccs.sharepoint.com/FC Systems Library/FLEX_BROCHURE.pdf" type="application/pdf" />

  • Thanks jbooker for enhancing the code to meet further requirements. I have to still test your updated code and will let you know my results.

    @Matt Manley: Did u install the latest Adobe Acrobat reader? Let me know your results.

  • OPEN PDF FILES IN SHAREPOINT 2010 ONLINE (OFFICE 365) INTERNET EXPLORER BROWSER - SOLVED!

    My compliments to the collaborative effort started by Josh Booker and extended by Vamsi to provide a legitimate solution to one of Microsoft's most significant draw-backs in the SharePoint 2010 Online (O365) service!

    The solution prescribed in this post resolves the inability to view PDF files in a browser window for both IE and FireFox.  The solution is simple to implement and provides the end-user a very professional and transparent solution.

    We have tested the solution with a number of IE versions (8x through 9) using a variety of configurations of the Adobe Add-in versions (6x-10) and found the solution to be highly reliable.

    Thanks to Josh and Vamsi for enhancing this system!

  • Great News!!. PDFs are now supported in SharePoint Online.

    community.office365.com/.../sharepoint-online-service-update.aspx

  • Josh, I was hoping you could help with the a couple of questions.  I saved this <Script type="text/javascript" src="/utilities/pdf.js"></script> to a text file and uploaded it to my master pages.  I also copied the script and saved it to my utilities library as pdf.js.  I am not sure about the next step.  I want to add this to all of my existing sites and libraries.  Mark

  • Hi Mark,

    Rather than save the script reference to a new file in your master pages gallery, you need to edit the existing master page file called 'v4.master'

     

    1) Open your site in Sharepoint Designer 2010

    2) Edit v4.master and paste the script reference at the end of the file between close body & html tags like so:

    </body>
    <script type="text/javascript" src="/utilities/pdf.js"></script>
    </html>

     

    3) save the file and try your site for PDF enhancements.

     

    FYI, public site editor pages don't use this master page they use root.master which I'm told 'breaks if you breath on it' so you have to add the script to each of you public pages.

     

    All pages in teamsite work fine.

    Have a great day!

    Josh

  • Josh, I followed the instructions but the PDF would not open in browser.

    I copied the code above into notebook and saved as pdf.js.  

    I started at:  function IncludeJS(jsFile) and ended at: //End Add Doc Item Menu.  The is a blue circle with a letter i next to the v4master file in SD.

    I am testing with a P1 site but will apply to a some E1 sites when I know it works.  Any problem with using P1?

  • Hi Mark,

    This should work on P1, except for on public site pages.  The above code needs to be saved as pdf.js in a library called Utilities.  You can test this by typing the abosulte url yoursite.sharepoint.com/.../pdf.js If the file is there, this will result in a save cancel dialog. Which is good.

    Them you edit the v4.master page as descirbed above and your pages should allow opening PDFs in the browser.  If you've done this an still doesn't work then check to see if the 'Open PDF in Browser' menu item appears in the document drop down.  Dos that work?

    Thanks,

    Josh

1|2|3