Microsoft Developer Network > Forums Home > Visual Studio Express Editions Forums > Visual Basic Express Edition > loading a .pdf/word/etc. documents in webbrowser control?

Answered loading a .pdf/word/etc. documents in webbrowser control?

  • Wednesday, November 26, 2008 12:10 AM
     
     

     

    These documents are stored locally, or maybe in a database.  How do I load them into the webbrowser control.  Looking around I see that using the browser documentstream method might take care of it, any suggestions?

Answers

  • Wednesday, January 14, 2009 6:24 AM
     
     Answered
    hmm C# code :-(  What about targeting the x86 platform in the build/configuration manager instead of the x64 platform .
    • Marked As Answer by Stuck on Code Wednesday, January 14, 2009 7:31 AM
    •  

All Replies

  • Wednesday, November 26, 2008 2:06 AM
     
     
    WebBrowser1.Navigate("file:///C:/PDFs/Document1.pdf")
  • Wednesday, November 26, 2008 2:21 AM
     
     

     

    WebBrowser1.Navigate(file:///E:\Resources\Manuals\Document1.pdf)

     

    doesnt work

  • Wednesday, November 26, 2008 2:23 AM
     
     
    What do you mean by "doesn't work"? Are you getting an exception?

    Make sure to use / (forward slash) and not \.
  • Wednesday, November 26, 2008 2:27 AM
     
     

     

    tmpstr = "file" & ":///" & thisMasterItemObject.xFilePath.Replace("\", "/")

    WebBrowser1.Navigate(tmpstr)

     

    tmpstr = "file:///E:/Resources/Manuals/document.pdf"

    Navigation to the webpage was canceled

  • Wednesday, November 26, 2008 2:33 AM
     
     
    Try just WebBrowser1.Navigate("C:\Something\Doc.pdf")
  • Wednesday, November 26, 2008 2:34 AM
     
     
    I have.  Still get same problem.  I think i gotta use documentstream, i just dont know how to get a stream of a file.... No filestream will not work, it just display's jibberish in the webbrowser.

     

  • Wednesday, November 26, 2008 2:40 AM
     
     
    Right click on your toolbox and choose choose items . In the dialogbox that opens click the com tab and choose Adobe pdf reader . The reader control will show in your toolbox . Add it to a form and then use code to set the .src property of the control to load a pdf document . This assumes you have the Adobe pdf reader installed .

     

    Instead of the src property you can do this

     

    AxAcroPDF1.LoadFile("C:\myfile.pdf")

  • Wednesday, November 26, 2008 2:45 AM
     
     

    Yep, i saw you post in another thread about doing that.  Only reason I didnt try it, is I didnt understand how using AxAcroPDF1.LoadFile would get it into the webbrowser control.....  Does it actually do that?

     

    Furthermore, it doesnt account for word documents, text documents, etc....

     

  • Wednesday, November 26, 2008 2:50 AM
     
     
    No it is a PDF reader control that is all it does .

     

  • Wednesday, November 26, 2008 2:58 AM
     
     

    Its all good, I've decided not to use the browser control.  I'll just stick with using the process class.  Its better that I do it like that anyway.  I was just playing around to see how the browser integration might feel in my app.

     

    I'll definately store that nice little com object that adobe provided in my toolbox.  Although I'd still like to know how to use documentstream.

  • Wednesday, November 26, 2008 3:02 AM
     
     

    Well you could use a TabControl and put the reader on one tabpage the web browser on another maybe a richtextbox on a third tab etc

     

     

  • Wednesday, November 26, 2008 3:10 AM
     
     

    meh.... i dont like the way tabcontrol looks on vista.  Plus panels and controls on panels on the tab pages dont resize correctly.  Been a while since i used it, but something's a little off with that control.  Also, it would just add complexity to the interface.

     

    I'm pretty sure that what I was thinking in the initial post can be done with documentstream.

  • Wednesday, November 26, 2008 4:18 AM
     
     
    Hi stuck on Code

    You can give only the option is

    string FileN = Application.StartupPath.ToString() + @"\Files\" + FName.ToString() +  "." + _FileExtension.ToString();
    Uri uri = new Uri(FileN);
    WBFileBrowser.Url = uri;


    Thanks & regards
    Dhinesh paramasivam

  • Wednesday, November 26, 2008 8:55 PM
     
     

    sorry, doesnt work.  Says navigation canceled in the browser control.

     

    I've tried

     

    'Dim tempSTR As String = "file://" & thisMasterItemObject.xFilePath.Replace("\", "/")

    'Dim tempSTR As String = "file://" & thisMasterItemObject.xFilePath

    Dim tempSTR As String = thisMasterItemObject.xFilePath

    Dim thisURI As New Uri(tempSTR)

    WebBrowser1.Url = thisURI

  • Wednesday, November 26, 2008 9:02 PM
     
     

     

    I just use something like this with just a normal path string .

     

    Code Snippet

    Public Class Form1

     

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

     

    WebBrowser1.Url = New Uri("E:\Manuals\Samsung SyncMaster 275T Manual.pdf")

     

    End Sub

     

    End Class

     

     

  • Wednesday, November 26, 2008 9:24 PM
     
     

    'Dim tempSTR As String = "file://" & thisMasterItemObject.xFilePath.Replace("\", "/")

    'Dim tempSTR As String = "file://" & thisMasterItemObject.xFilePath

    'Dim tempSTR As String = thisMasterItemObject.xFilePath

    Dim thisURI As New Uri("E:\Resources\Manuals\document[1].pdf")

    WebBrowser1.Url = thisURI

     

    why isnt this working for me.... is it cuz i'm on vista?

     

    the same xFilePath works fine when used in my process class, so its not a filepath issue.

     

    'Dim thisProcessStartInfo = New ProcessStartInfo()

    'thisProcessStartInfo.FileName = thisMasterItemObject.xFilePath

    'Process.Start(thisProcessStartInfo)

     

     

    oh wait i think i might have it..... it doesnt like the space in my file path....

  • Wednesday, November 26, 2008 9:38 PM
     
     
    If it is saying that the operation was cancelled, maybe you are cancelling it from some other event. Post any other code that makes any kind of call to the web browser.
  • Wednesday, November 26, 2008 9:56 PM
     
     

    there is no other code.  If I open a new iexplorer browser, and manually paste the file path into the address bar, it converts it to its url equalivent, and gives me a quick warning about security or some such, and launches the .pdf in a new window.

     

    I've tried copying and pasting this converted url text directly into the uri object string, and i get the navigation canceled error.  I think its this security thing.

     

    btw, spaces in file path get converted to %20 in a url

     

  • Wednesday, November 26, 2008 10:22 PM
     
     
    Have you tried using an OpenFileDialog and are the results the same ?

     

  • Wednesday, November 26, 2008 11:02 PM
     
     

     

    the regular file path works fine in the process.start

     

    I think its this explorer security thing.  Here's the message I get when manually entering the file path, or the url equivalent into new iexplore.exe window

     

    Code Snippet

    Internet Explorer needs to open a new window to display this webpage.

     

    For your computer's security, websites that are in different security zones must open in different windows.

     

     

     

    and the .pdf opens in a new window.
  • Thursday, November 27, 2008 12:56 AM
     
     

    Ok so i'm trying to use browser.documentstream, and the webbrowser responds by showing vertical scrollbars, but no actual document or any other controls.

    Code Snippet

     

    Dim fs As FileStream = New FileStream(thisMasterItemObject.xFilePath, FileMode.Open, FileAccess.Read)

    Dim info As FileInfo = New FileInfo(thisMasterItemObject.xFilePath)

    Dim length As Int32 = info.Length

    Dim bytearray(length - 1) As Byte

    Dim i As Integer

    WebBrowser1.DocumentStream = fs

    i = fs.Read(bytearray, 0, length)

    'WebBrowser1.DocumentStream = fs

     

     

     

    Here is the definition for documentstream:

    "Use this property to load a Web page into the WebBrowser control from a Stream object. You can use this property, for example, to load Web pages from a database or resource file."

     

    Unfortunately I can not find any examples on the net (at least non that make sense to me) for what i'm trying to do.  Certainly this is nothing unique....

     

     

    The code below will launch the file, but in a seperate window.

    Code Snippet

    Dim ofd As New OpenFileDialog

    ofd.FileName = thisMasterItemObject.xFilePath

    WebBrowser1.Navigate(ofd.FileName)

     

     

  • Thursday, November 27, 2008 2:48 AM
     
     

     

    I cant get any of this to work, so how about a work around?  I see how sometimes a .pdf or .txt file is opened up within the same browser window, how could I write a html page that would launch a file.  Would I have to launch the file in a frame or iframe? 

     

    I figure my app could write the html code on the fly, and save the file as .html, then the webbrowser could navigate to the file.  Sound like a good idea?  I think its worth a shot, problem is I dont remember the simplest html.... its been years since I dabbled in it.  I'm sure the code to do this would only be a few lines... Can anyone help me out with a basic html page that will launch a file when the page loads.......

  • Thursday, November 27, 2008 3:41 AM
     
     

    bah, I tried using AxAcroPDF1 and get this error when clicking run for my application

     

    "An error occurred creating the form. See Exception.InnerException for details.  The error is: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

     

    I figured I'd just use the reader when its a .pdf i need to show, and normal webbrowser for everything else.......  I strike out again........  I'm on Vista64 bit.....

     

  • Thursday, November 27, 2008 4:11 AM
     
     
    Try targeting the x86 platform . If on your  build menu you don't have the configuration manager then use Tools-Options to open the options dialog . In the Projects and Solutions catagory check the checkbox for advanced build configuration then press ok . On the build menu choose the configuration manager . When it opens on the platform dropdown choose new . You should then be able to target the x86 platform .

     

  • Thursday, November 27, 2008 5:20 AM
     
     
    Hi

    After the files name is getting located the file string should be Like this

    F:\Application Folder\bin\Debug\Files\ef0709d3-48b6-469a-86ff-36dee21ffc7e1Checking.pdf

    Before assigning this string to "
    tempSTR" verify that you are assigning the right formatted value.

    then


    Dim thisURI As New Uri(tempSTR)

    WebBrowser1.Url = thisURI



    Thanks & Regards
    Dhinesh paramasivam
  • Thursday, November 27, 2008 6:01 AM
     
     
     iyngarangce wrote:
    Hi

    After the files name is getting located the file string should be Like this

    F:\Application Folder\bin\Debug\Files\ef0709d3-48b6-469a-86ff-36dee21ffc7e1Checking.pdf

    Before assigning this string to "
    tempSTR" verify that you are assigning the right formatted value.

    then


    Dim thisURI As New Uri(tempSTR)

    WebBrowser1.Url = thisURI



    Thanks & Regards
    Dhinesh paramasivam

     

    nice.... I'll definately do that. 

  • Thursday, November 27, 2008 9:36 AM
    Moderator
     
     
    Struck on Code,

    Take a look at this sample. Whether you can open the Word, Excel document in your application. If it can't, I think that you need to check the application permission in this scenario. Right click-> project->Properties-> security. Tell the result to me.

    Riquel
  • Thursday, November 27, 2008 8:23 PM
     
     

    I tried the microsoft webbrowser com object as shown in the sample code, and it exhibits the same results as the webbrowser class.

     

    I dont have Word or Excel installed on this computer, but I did try .txt and .rtf.  Back to using the webbrowser class, and the .txt file opens up in the browser.  the .rtf file opens up in a new window, just like the .pdf.

     

     

     

    As far as the project security settings:

     

    Enable click once security settings:  Unchecked

    This is a full trust application:  Selected

    Zone your application will be installed from:  Local Intranet

     

    File I/O and Registry permissions are not included.  All other permissions are included with settings as "(Zone Default)"

  • Friday, November 28, 2008 4:36 AM
     
     

    <Snip>

     

    Sorry that didnt work.  I got the following error:  "Object reference not set to an instance of an object." 

     

    <Snip>

     

     

     

  • Saturday, November 29, 2008 8:12 PM
    Moderator
     
     
    Stuck On Code: please send me an email.  You'll find my email address in my profile, |Monkeytail| = @
  • Tuesday, December 02, 2008 9:02 AM
    Moderator
     
     
    Hi Stuckoncode,

    If you check the Enable ClickOnce Security Settings, also select "This is a full trust application", then run this application in your local hard disk to see what happens. As far as I know, this is the computer-setting issues. When I use the
    DocumentStream property, the Webbrowser just shows the binary data. 

    Imports System.IO
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim s As Stream = New FileStream("E:\temp\test.pdf", FileMode.Open, FileAccess.Read)
            WebBrowser1.DocumentStream = s
        End Sub
    End Class

  • Wednesday, December 03, 2008 10:32 PM
     
     
    You know, there are controls out there that allow you to view PDF / XPS documents in you WinForms projects.
  • Wednesday, December 03, 2008 11:16 PM
     
     

     drummerboy0511 wrote:
    You know, there are controls out there that allow you to view PDF / XPS documents in you WinForms projects.

     

     

    I know, but I just wanted to stick with whatever standard explorer uses to view the documents.  One control.  I didnt want to have to show/hide controls to view particular document types.  I think this is a Vista thing, as I dont recall seeing any messageboxes about having to navigate to a new page due to a possible security threat in XP.

     

    I've let this issue drop for the moment, as its not all that vital to the project I was/am working on.  Having the documents open in a new window is acceptable, and maybe preferable.  But when and if I get back to it, I'll come back with a fresh mind, and have another look through this thread.

  • Thursday, December 04, 2008 2:16 AM
     
     
    That's a good idea. And, I understand your wanting to have just one control to do it all. I've been in the same boat several times. I want my end users to save as much disk space as possible and it's easier to manage.
  • Thursday, December 04, 2008 6:13 AM
     
     
    Hi Stuck on Code

    This may be helpful to you.

    I planned to give one html file and then load the file with javascript events to write the file name in the URL then write the contents to the HTML File and load it into Webbrowser with the file which you want to load

    Sure may be if it writes the file and loads successfully you will also use the same.

    If you can use this with the following steps

    1.Create a directory in the bin/debug folder called 'Files' which i used like that
    2.Place the document which you want then load the document in the specified string like FileName.txt in the code
    3.Run the application

    The code below will create a doc.html for you


    string path = @"document.location.href = 'FileName.txt';";
                string s = @"<html><body onLoad=""alert('this is working');" + path + "\"></body></html>";
                if (File.Exists(Application.StartupPath + @"\Files\doc.html"))
                {
                    File.Delete(Application.StartupPath + @"\Files\doc.html");
                }

                File.WriteAllText(Application.StartupPath + @"\Files\doc.html", s);

                webBrowser1.Navigate(Application.StartupPath + @"\Files\doc.html");

    Thanks & Regards
    Dhinesh paramasivam


  • Monday, December 08, 2008 8:03 AM
     
     

    We are changing the issue type to “Question” because you have followed up with the necessary information. If you don't have more time to look at the issue and provide more information, please feel free to change the issue type back to “Comment” by editing your initial post and changing the radio button at the top of the post editor window.

     

    Lol Big Smile

     

    Sorry Boss ( Riquel ) .

     

    Best Regards,

     

    BVS.

  • Wednesday, January 14, 2009 4:46 AM
     
      Has Code
    I hate to bring this topic back, but I would really like to get this to work now.  Simple code to try and load a .pdf into my webbrowser control.  It will NOT load the stupid .pdf in the browser, it launches in a new window. 

    namespace WindowsFormsApplication1  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
     
            private void Form1_Load(object sender, EventArgs e)  
            {  
                webBrowser1.Navigate(new Uri(@"file:///C:/Users/Me/Documents/TestDocument.pdf"));  
     
            }  
        }  

    In a WPF Browser application (on the same computer, Vista64bit) it works fine, it loads the .pdf in the WPF webbrowser.

                    Uri thisUri = new Uri(@"file:///C:/Users/Me/Documents/TestDocument.pdf");  
                    webBrowser1.Source = thisUri; 


    Both the forms application and WPF application are running in Full Trust mode.  I am running Vista64 bit.  I published the simple forms application indicated in the code above on an XP machine, and it DOES load the .pdf in the browser, so this is definately a Vista thing......  Any clues?

    Could it have something to do with the fact that the webbrowser class is based off the 64bit version of explorer instead of the 32 bit?  Any way to force the webbrowser to use the 32bit version instead?

    Let me say again, there is a feature in vista, that under certain conditions (I forget what the condition is) it will force you to open a new browser window, instead of using the current one.  I think this is why its launching in a new window.

    Compensating what I don't know yet, with what I do know now.
  • Wednesday, January 14, 2009 6:24 AM
     
     Answered
    hmm C# code :-(  What about targeting the x86 platform in the build/configuration manager instead of the x64 platform .
    • Marked As Answer by Stuck on Code Wednesday, January 14, 2009 7:31 AM
    •  
  • Wednesday, January 14, 2009 7:35 AM
     
     
    (C#/ vb...... its all the same )

     Thanks bdbodger, I should have thought of that, seeing as how I hinted to that in my previous post.

    I changed the target to x86, and it worked.  I switched it back to anycpu, and it still works.  I put it on x64, and it still works.   Hmmmm I WISH I HAD TESTED THE APP AGAIN BEFORE I SWITCHED IT TO X86.  I dunno, but its working now.

    Edit to add:  I created a new project, and added a webbrowser, and the navigate method to the form load event.  Ran it as its original target of anycpu, and it didnt work.  I am now switching it to target x86, and it worked.  I am now switching it back to target anycpu, and it didnt work ( lol ).  Now setting it to target x64, and it didnt work.  Switching it back to target x86, and it worked.  One more time back to anycpu, and it didnt work............. OK I DONT KNOW WHAT IN THE WORLD WAS GOING ON IN THE FIRST PROJECT I TESTED.   Seems to work in a logical mannor now, by tageting x86.


    Thanks again.

    Compensating what I don't know yet, with what I do know now.
  • Thursday, March 01, 2012 4:55 PM
     
     
    I am WPF 4.0 on Windows 7 64 bit with its web browser control and it always opens in a new browser window instead of the browser control asking first if I want to save it or open it. I am adobe reader 9 but before that I was using 7 or 8 and it always opened in the browser control without aksing me anything so something changed. I tried the various suggestions on this thread with no success including build the project as x86. Did you ever find a solution?

    Jim