Solved

How to open a .pdf document in Visual Basic

Posted on 2006-11-21
16
1,300 Views
Last Modified: 2013-11-25
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
Comment
Question by:CirrusIT
  • 6
  • 6
  • 2
  • +2
16 Comments
 
LVL 10

Expert Comment

by:Kinger247
ID: 17988720
Open it in a browser control.
0
 
LVL 10

Expert Comment

by:Kinger247
ID: 17988739
Its a COM control down as 'Microsoft Internet Controls' or Interop.SHDocVw.dll
0
 
LVL 76

Expert Comment

by:David Lee
ID: 17988856
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
 
LVL 10

Expert Comment

by:Kinger247
ID: 17988865
sorry CirrusIT, thought you where using .net,
the answer I gave is till the same just not the Interop.bit ;)
0
 
LVL 11

Expert Comment

by:ch2
ID: 17988893
0
 
LVL 11

Expert Comment

by:ch2
ID: 17988899
Sorry for my post above i writed in the wrong post.

0
 
LVL 10

Expert Comment

by:Kinger247
ID: 17988930
Good advice anyway :)
0
 
LVL 12

Accepted Solution

by:
jkaios earned 500 total points
ID: 17990340
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:CirrusIT
ID: 17994264
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
 
LVL 10

Expert Comment

by:Kinger247
ID: 17994363
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
 

Author Comment

by:CirrusIT
ID: 17994375
Um......i was referring to NERO burning CD comment....

perhaps should have been clearer in making that joke....
0
 
LVL 10

Expert Comment

by:Kinger247
ID: 17994420
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
 

Author Comment

by:CirrusIT
ID: 17994608
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
 

Author Comment

by:CirrusIT
ID: 17996653
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
 

Author Comment

by:CirrusIT
ID: 18001735
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
 

Author Comment

by:CirrusIT
ID: 18006734
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now