• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1351
  • Last Modified:

How to open a .pdf document in Visual Basic

How do you open a .PDF document within Visual Basic?

I am using Adobe Acrobat Reader 7.0.8 and Visual Basic 6 - needs to be able to run on .NET as well.

I cant find this PDF.OCX file not that would do much good as according to other knowledgebase items this has to be dragged onto the form, I need an alternative solution to be able to open a .PDF document.

Please help...

Cheers.

JC.
0
CirrusIT
Asked:
CirrusIT
  • 6
  • 6
  • 2
  • +2
1 Solution
 
Kinger247Commented:
Open it in a browser control.
0
 
Kinger247Commented:
Its a COM control down as 'Microsoft Internet Controls' or Interop.SHDocVw.dll
0
 
David LeeCommented:
Greetings, CirrusIT.

If by "open a .PDF document within Visual Basic" means to have the item open in a VB form, then Kinger247 has already given you the answer.  If instead you meant that you need a way to open a PDF document from within VB, but not in a VB form, then another option would be to use the Shell command and let Windows open the PDF in Acrobat Reader.  

Cheers!
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Kinger247Commented:
sorry CirrusIT, thought you where using .net,
the answer I gave is till the same just not the Interop.bit ;)
0
 
ch2Commented:
Sorry for my post above i writed in the wrong post.

0
 
Kinger247Commented:
Good advice anyway :)
0
 
jkaiosCommented:
Try this:

1. Name the Class module as clsShell32
2. Create a command button and test it as follows:

===========================[ FORM CODE ] ==================================
Private Sub Command1_Click()
   Dim oShell As New clsShell32
   Dim bOK As Boolean
   bOK = oShell.Execute("C:\Temp\myFile.PDF", me.hWnd)
   If Not bOK Then
     MsgBox oShell.ErrorMsg
   End If
End Sub
===========================[ FORM CODE ] ==================================


===========================[ CLASS MODULE CODE ] ============================

Option Explicit

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

'--- Constants for the nShowCmd parameter ---
Const SW_HIDE = 0                   'Hides the window and activates another window
Const SW_MAXIMIZE = 3               'Maximizes the specified window
Const SW_MINIMIZE = 6               'Minimizes the specified window and activates the next top-level window in the z-order
Const SW_RESTORE = 9                '-- same as SHOWNORMAL --
Const SW_SHOW = 5                   'Activates the window and displays it in its current size and position
Const SW_SHOWNORMAL = 1             'Activates and displays the window in its original size and position
Const SW_SHOWDEFAULT = 10           'Sets the "show state" based on the SW_flag specified in the STARTUPINFO structure
Const SW_SHOWMAXIMIZED = 3          'Activates the window and displays it as maximized
Const SW_SHOWMINIMIZED = 2          'Activates the window and displays it as minimized
Const SW_SHOWMINNOACTIVE = 7        'Displays the window as a minimized window. The active window remains active
Const SW_SHOWNA = 8                 'Displays the window in its current state. The active window remains active
Const SW_SHOWNOACTIVATE = 4         'Displays the window in its most recent size and position. The active window remains active

'--- This function's return value constants ---
Const ERROR_OS_OOM = 0              'The operating system is out of memory or resources
Const ERROR_BAD_FORMAT = 11&        'The .exe file is invalid (non-Win32® .exe or error in .exe image)
Const SE_ERR_ACCESSDENIED = 5       'The operating system denied access to the specified file
Const SE_ERR_ASSOCINCOMPLETE = 27   'The file name association is incomplete or invalid
Const SE_ERR_DDEBUSY = 30           'The DDE transaction could not be completed because other DDE transactions were being processed
Const SE_ERR_DDEFAIL = 29           'The DDE transaction failed
Const SE_ERR_DDETIMEOUT = 28        'The DDE transaction could not be completed because the request timed out
Const SE_ERR_DLLNOTFOUND = 32       'The specified dynamic-link library was not found
Const SE_ERR_FNF = 2                'The specified file was not found
Const SE_ERR_NOASSOC = 31           'There is no application associated with the given file name extension
Const SE_ERR_OOM = 8                'There was not enough memory to complete the operation
Const SE_ERR_PNF = 3                'The specified path was not found
Const SE_ERR_SHARE = 26             'A sharing violation occurred

'--- Exposed enums for the lpOperation param ---
Public Enum SE_Operation_Enum
   xEdit = 1
   xExplore = 2
   xFind = 3
   xOpen = 4
   xPrint = 5
End Enum

'--- Exposed enums for the nShowCmd param ---
Public Enum SE_ShowCmd_Enum
   xHide = SW_HIDE
   xMaximize = SW_MAXIMIZE
   xMinimize = SW_MINIMIZE
   xRestore = SW_RESTORE
   xShow = SW_SHOW
   xShowNormal = SW_SHOWNORMAL
   xShowDefault = SW_SHOWDEFAULT
   xShowMaximized = SW_SHOWMAXIMIZED
   xShowMinimized = SW_SHOWMINIMIZED
   xShowMinNoActive = SW_SHOWMINNOACTIVE
   xShowCurrentState = SW_SHOWNA
   xShowRecentState = SW_SHOWNOACTIVATE
End Enum

Dim m_lResult As Long

Public Function Execute(ByVal sFileName As String, _
                        Optional ByVal lWindowHandle As Long, _
                        Optional ByVal lOperation As SE_Operation_Enum = xOpen, _
                        Optional ByVal lCommand As SE_ShowCmd_Enum = xShowNormal, _
                        Optional ByVal sParameters As String, _
                        Optional ByVal sWorkDirectory As String) As Boolean
                       
   Dim sWork As String
   
   Select Case lOperation
      Case xEdit:    sWork = "edit"
      Case xExplore: sWork = "explore"
      Case xFind:    sWork = "find"
      Case xOpen:    sWork = "open"
      Case xPrint:   sWork = "print"
   End Select
   
   m_lResult = ShellExecute(lWindowHandle, sWork, sFileName, sParameters, sWorkDirectory, lCommand)
   
   Execute = (m_lResult > 32)
   
End Function

Public Property Get ErrorMsg() As String

   Dim sWork As String
   
   Select Case m_lResult
      Case ERROR_OS_OOM:            sWork = "The operating system is out of memory or resources"
      Case ERROR_BAD_FORMAT:        sWork = "The .exe file is invalid (non-Win32® .exe or error in .exe image)"
      Case SE_ERR_ACCESSDENIED:     sWork = "The operating system denied access to the specified file"
      Case SE_ERR_ASSOCINCOMPLETE:  sWork = "The file name association is incomplete or invalid"
      Case SE_ERR_DDEBUSY:          sWork = "The DDE transaction could not be completed because other DDE transactions were being processed"
      Case SE_ERR_DDEFAIL:          sWork = "The DDE transaction failed"
      Case SE_ERR_DDETIMEOUT:       sWork = "The DDE transaction could not be completed because the request timed out"
      Case SE_ERR_DLLNOTFOUND:      sWork = "The specified dynamic-link library was not found"
      Case SE_ERR_FNF:              sWork = "The specified file was not found"
      Case SE_ERR_NOASSOC:          sWork = "There is no application associated with the given file name extension"
      Case SE_ERR_OOM:              sWork = "There was not enough memory to complete the operation"
      Case SE_ERR_PNF:              sWork = "The specified path was not found"
      Case SE_ERR_SHARE:            sWork = "A sharing violation occurred"
      Case Else:                    sWork = "Undefined error (error#: " & m_lResult & ")"
   End Select
   
   ErrorMsg = sWork

End Property

===========================[ CLASS MODULE CODE ] ============================
0
 
CirrusITAuthor Commented:
Crikey, thanks for all the responses, even though some are a little off topic : )

I dont want to open the document in Visual Basic (i.e. in a form) i wish to open to the document in Adobe Acrobat reader but when i try the Shell ("Directory") command it errors saying invalid call or arguement.

Ill give jkaios code a try but the directory and file name is built up of Variables - 3 in total

DIRECTORY - contains the location
DATE - the date of the file
NUMBER - unique id

DATE and NUMBER make up the file name, so how do i write this command line so that is uses the variables?

oShell.Execute("C:\Temp\myFile.PDF", me.hWnd)

Come to think of it i will have to do some TRIMM 'ing functions on the variables to make sure there are no unneccesary spaces....

Many thanks

JC.
0
 
Kinger247Commented:
CirrusIT, I don't think anyone has been off topic ...

>>I dont want to open the document in Visual Basic (i.e. in a form) i wish to open to the document in Adobe Acrobat reader but when i try the Shell ("Directory") command it errors saying invalid call or arguement.

your original post was >How do you open a .PDF document within Visual Basic?
0
 
CirrusITAuthor Commented:
Um......i was referring to NERO burning CD comment....

perhaps should have been clearer in making that joke....
0
 
Kinger247Commented:
ah, I see .. , my apologises too :)

If your having problems with your file name, can you give an example it ?

Like : C:\Temp\20061122 12345.PDF
0
 
CirrusITAuthor Commented:
No worries matey, at the moment my Shell command looks like this:

Shell("C:\Temp\List Building.pdf")

This was just to prove to myself that you can open a PDF document in Visual Basc, just to basically load a .PDF document at the moment when the code hits a certain point.

-Background-
I have a form which the user can press SHIFT + F8 (keypressed function) to which will bring up a validation message and ask if they wish to load the scanned document selected.  

Once the IF statements check that no fields are missing / blank otherwise there's no point - if they are not blank it will then connect to a SQL database to retrieve the values to build the DIRECTORY, NUMBER & DATE values, then I wish to build the load .PDF line after the values have been retrieved - :

The naming convention of the file is : DDMMYYYYnnnnnnn

nnnnnnn being the unique id variable.

So DIRECTORY will = "C:\Temp\"
    DATE will = "12/12/2006"         - Although the alarm bells of doom are ringing in my head with this one cus of the \ \ charactors, not quite sure whether its possible to get rid of them.
    NUMBER will = "1234567"

Then have to add ".PDF" to the end of the statement i presume.

JKAIOS solution looks very thorough- problem being that I cant build another form with command button -  i need to load the document in the MODULE code once i have performed the validation mentioned above (checking for blanks and such) can this be done?

Many thanks for your help

JC.

0
 
CirrusITAuthor Commented:
After a bit of tinkering this is how I action without a command click:

Dim LoadDoc
LoadDoc = ("C:\Temp\MyFile.PDF")
oShell.Execute (LoadDoc)
MsgBox oShell.ErrorMsg

Just now need to figure out the syntax for using variables in the string, and how to remove the '/'s from a date field.......
0
 
CirrusITAuthor Commented:
For the people looking to remove the '/' from dates this how to do it:

Dim SDay, SMonth, SYear, FileDate 'Document properties

SDay = Day(YourDate)
SMonth = Month(YourDate)
SYear = Year(YourDate)
FileDate = (SDay & SMonth & SYear)

Will add the syntax for using variables in a string to this thread when ive figured it out for other peoples reference.

However the original query was solved by the marvellous post by JKAIOS - your a legend, much obliged.

Cheers,

JC
0
 
CirrusITAuthor Commented:
The missing piece of the puzzle, this is how you declare variables and use them in a string:

VarNumber = Trim(VarNumber)
           
LoadDoc = (Directory & FileDate & VarNumber & ".PDF")
   
oShell.Execute (LoadDoc)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 6
  • 6
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now