Need to Print Embedded PDFs

kmackie1

New Member
Joined
Jul 30, 2013
Messages
14
Here is my code so far:

Public Sub PrintPDFFiles()​
Const ADOBEPATH As String = "C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe"​
Const FILE_PATH As String = "C:\Users\kmackie\Desktop\Sample\Test"​
Const FILE_EXT As String = "PDF"​

Dim fso, fld, file​

Set fso = CreateObject("Scripting.FileSystemObject")​
Set fld = fso.GetFolder(FILE_PATH)​

For Each file In fld.Files​
If UCase(Right(file.Name, 3)) = FILE_EXT Then​
Shell """" & ADOBEPATH & """/n /t """ & file.Path & """"​
End If​
Next​
End Sub

This code works perfectly for what I am trying to do... except for one thing:

I want to open and print PDFs that are already embedded into my worksheet. I can use the code to open the embedded PDF files:


ActiveSheet.Shapes("Object 1").OLEFormat.Activate​

How on earth can I just open these files and print them. I've spent so long trying to figure this out. If you can't tell... I'm a bit of a newbie.

End result:
I want to be able to click a button, have it open the embedded pdf file in Adobe Reader, Print it, Close Adobe Reader.
I will name my first born son to the man that can solve this problem for me!
 
Re: Need to Print Embedded PDFs - PLEASE HELP :(

ZVI

Tested, works perfectly. I even tried adding in highlights, underline, several fonts to test, all did work with no problems. Many thanks.

Would future updates of Adobe Reader be likely to break this VBA code?

Best regards
 
Last edited by a moderator:
Upvote 0

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Re: Need to Print Embedded PDFs - PLEASE HELP :(

ZVI

Tested, works perfectly. I even tried adding in highlights, underline, several fonts to test, all did work with no problems. Many thanks.

Would future updates of Adobe Reader be likely to break this VBA code?

Best regards
Hi Saliman,

Glad it has helped, thanks for the feedback!
The fixed version of the code should work in future updates of Adobe Reader.

Best Regards
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

Hi Saliman,

Glad it has helped, thanks for the feedback!
The fixed version of the code should work in future updates of Adobe Reader.

Best Regards

Hi ZVI

Following on from your bug fix, I also came across additional bug fixes:-
1) The code does crash when there is a hidden sheet
2) When there is a hidden sheet with a PDF, it prints it anyway.
3) The code seems to "hang" when the process is finished. Macro is then terminated by closing the open Adobe reader manually.

My fixes are:-
1)
Code:
Private Sub PrintSheetsAndPdfs()  Dim Sh As Worksheet, obj As OLEObject
  For Each Sh In Worksheets
    With Sh.UsedRange
      If .Cells.Count > 1 Or Len(.Cells(1)) Then
[U][I][B]      If Sh.Visible = True Then[/B][/I][/U]
        Sh.PrintOut
[U][I][B]        End If[/B][/I][/U]
      End If
2)
Code:
    End With    For Each obj In Sh.OLEObjects
      If obj.progID Like "Acro*.Document*" And obj.OLEType = 1 Then
        Sh.Activate
[U][I][B]        If Sh.Visible = True Then[/B][/I][/U]
        Call PrintEmbeddedPDFs_03
[U][I][B]        End If[/B][/I][/U]
        Exit For
      End If
3) Adding this line before the macro starts
Code:
        CreateObject("wscript.shell").Run "AcroRd32.exe"
seems to fix this issue, despite having two instances of Adobe Reader.
Please note that when the original macro runs, the Adobe Reader is not "killed", it merely shuts the current file within. I suspect the macro was waiting for Adobe reader to be "killed"?
Having another instance of Adobe Reader seems to "kill" the program, and leave one running, and the macro is able to continue and not hang.

Do let me know your thoughts.

Best regards

Saliman
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

... Do let me know your thoughts...
Hi Saliman,

Points 1 and 2 have sense.
But alternatively hidden sheets can be temporarily set to visible before printing.

Points 3 – the printing by command line is not good and came from the original post, read my comments in post#25.
My interest was mainly in extracting of embedded PDF for the printing, not in printing itself.
For printing of PDFs I’d rather use automation of Adobe Acrobat like this:
Rich (BB code):
#If VBA7 Then
  Private Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hWnd As LongPtr) As Long
  Private Declare PtrSafe Function CloseClipboard Lib "user32" () As Long
  Private Declare PtrSafe Function GetClipboardData Lib "user32" (ByVal wFormat As Long) As LongPtr
  Private Declare PtrSafe Function GlobalSize Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
  Private Declare PtrSafe Function GlobalLock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
  Private Declare PtrSafe Function GlobalUnlock Lib "kernel32" (ByVal hMem As LongPtr) As Long
  Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
  Dim hWnd As LongPtr, Size As LongPtr, Ptr As LongPtr
#Else
  Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
  Private Declare Function CloseClipboard Lib "user32" () As Long
  Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Long) As Long
  Private Declare Function GlobalSize Lib "kernel32" (ByVal hMem As Long) As Long
  Private Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
  Private Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
  Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
  Dim hWnd As Long, Size As Long, Ptr As Long
#End If
 
Sub PrintEmbeddedPDFs_04(Optional Sh As Worksheet)
' ZVI:2013-08-01 http://www.mrexcel.com/forum/excel-questions/717204-need-print-embedded-pdfs-please-help.html
' ZVI:2014-05-14 Added subrotines for printing sheets and embedded PDFs
' ZVI:2014-06-28 Fixed the incorrect finding of last "%%EOF" in PDF with comments
' ZVI:2014-07-11 Running of command line is replaced by automation of Acrobat application
 
  Dim a() As Byte, b() As Byte, i As Long, j As Long, k As Long, n As Long
  Dim FN As Integer, f As String, p As Variant, obj As OLEObject
 
  If Sh Is Nothing Then Set Sh = ActiveSheet
  p = Sh.Parent.Path
 
  ' Check OleObjects presence
  With Sh.OLEObjects
    If .Count = 0 Then
      MsgBox "Embedded PDF not found", vbExclamation, "Nothing to print"
      Exit Sub
    End If
  End With
 
  On Error GoTo exit_
 
  With CreateObject("AcroExch.App") ' <-- ZVI:2014-07-11
   
    ' Print all PDFs embedded into the active sheet
    For Each obj In Sh.OLEObjects
      i = 0:  hWnd = 0: Size = 0: Ptr = 0
      If obj.progID Like "Acro*.Document*" And obj.OLEType = 1 Then
        obj.Copy
        If OpenClipboard(0) Then
          hWnd = GetClipboardData(49156)
          If hWnd Then Size = GlobalSize(hWnd)
          If Size Then Ptr = GlobalLock(hWnd)
          If Ptr Then
            ReDim a(1 To CLng(Size))
            CopyMemory a(1), ByVal Ptr, Size
            Call GlobalUnlock(hWnd)
            i = InStrB(a, StrConv("%PDF", vbFromUnicode))
            If i Then
              ' --> ZVI:2014-06-28
              k = InStrB(i, a, StrConv("%%EOF", vbFromUnicode)) ' - i + 7
              While k
                j = k - i + 7
                k = InStrB(k + 5, a, StrConv("%%EOF", vbFromUnicode))
              Wend
              ' <--
              ReDim b(1 To j)
              For k = 1 To j
                b(k) = a(i + k - 1)
              Next
              Ptr = 0
            End If
          End If
          Application.CutCopyMode = False
          CloseClipboard
          If i Then
            n = n + 1
            f = p & "\" & n & "_embedded_.pdf"
            If Len(Dir(f)) Then Kill f
            FN = FreeFile
            Open f For Binary As #FN
            Put #FN, , b
            Close #FN
            ' --> ZVI:2014-07-11 Silent printing
            With CreateObject("AcroExch.AVDoc")
              .Open f, vbNullString
              .PrintPagesSilent 0, .GetPDDoc.GetNumPages - 1, 0, False, True
            End With
            .CloseAllDocs
            ' <--
            Kill f
          End If
        Else
          Application.CutCopyMode = False
        End If
      End If
    Next
    
    .Exit   ' <-- ZVI:2014-07-11
  End With  ' <-- ZVI:2014-07-11
 
  ' Show the amount of embedded PDFs being printed
  MsgBox "Amount of the printed PDFs: " & n, vbInformation, "PrintEmbeddedPDFs"
 
exit_:
 
  If Err Then MsgBox Err.Description, vbCritical, "Error #" & Err.Number
 
End Sub
 
 
Sub PrintSheetsAndThenEmbeddedPdfs()
  PrintSheets
  PrintEmbeddedPdfs
End Sub
 
Sub PrintSheetsAndPdfs()
  Dim Sh As Worksheet
  For Each Sh In Worksheets
    If Sh.Visible Then
      With Sh.UsedRange
        If .Cells.Count > 1 Or Len(.Cells(1)) Then
          Sh.PrintOut
        End If
      End With
      For Each obj In Sh.OLEObjects
        If obj.progID Like "Acro*.Document*" And obj.OLEType = 1 Then
          PrintEmbeddedPDFs_04 Sh
          Exit For
        End If
      Next
    End If
  Next
End Sub
 
Sub PrintSheets()
  Dim Sh As Worksheet
  For Each Sh In Worksheets
    If Sh.Visible Then
      With Sh.UsedRange
        If .Cells.Count > 1 Or Len(.Cells(1)) Then
          Sh.PrintOut
        End If
      End With
    End If
  Next
End Sub
 
Sub PrintEmbeddedPdfs()
  Dim Sh As Worksheet, obj As OLEObject
  For Each Sh In Worksheets
    If Sh.Visible Then
      For Each obj In Sh.OLEObjects
        If obj.progID Like "Acro*.Document*" And obj.OLEType = 1 Then
          PrintEmbeddedPDFs_04 Sh
          Exit For
        End If
      Next
    End If
  Next
End Sub

Best Regards
 
Last edited:
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

ZVI this thread really useful, thanks

Pls can you share your email ID, by sending personal email in this forum to me or here you can reply. I try to send you email, but your quota of email is full.

I have some work around so pls help me!
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

ZVI this thread really useful, thanks

Pls can you share your email ID, by sending personal email in this forum to me or here you can reply. I try to send you email, but your quota of email is full.

I have some work around so pls help me!

Hi RL,

Since this is a public forum, your question should be just posted in the appropriate forum.
You may post the question in the thread with thematic similar to yours or better create new thread for that.
Helpers (volunteers at their spare time) try to look at as many threads as they can, and if come across yours and think they can help, they usually will.

PMs are not for asking for help with questions - read the point #18 of the Posting Guidelines.
And yeah, sometimes Inbox becomes saturated such messages which are not allowed/encouraged.
I'll clean some of them today to allow good PMs :)

Regards,
Vlad
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

Dear ZVI

Your code no longer works in Excel 2010 (Works in Excel 2013!). The change seems to have come about as a result of recent windows update.

Within Sub PrintSheetsAndPdfs:-

Code:
      If obj.progID Like ""Acro*.Document*" And obj.OLEType = 1 Then

is flagged up as an issue by Excel VBA.

Upon further investigation, it seems to throw an error when there is no PDFs on the worksheet available to print, but there is a "Form" tick button macro button on the workpage. Deleting the tick buttons from the worksheet, makes the macro run perfectly.

Could you advise on how the macro could try ignore the buttons?

Best regards

Saliman
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

Please ignore my message, it seems Microsoft has buggered up their update efforts.

Deleting %temp%\excel8.0\*.exd file fixed the problem.

Until Microsoft releases another update..... :mad:

Dear ZVI

Your code no longer works in Excel 2010 (Works in Excel 2013!). The change seems to have come about as a result of recent windows update.

Within Sub PrintSheetsAndPdfs:-

Code:
      If obj.progID Like ""Acro*.Document*" And obj.OLEType = 1 Then

is flagged up as an issue by Excel VBA.

Upon further investigation, it seems to throw an error when there is no PDFs on the worksheet available to print, but there is a "Form" tick button macro button on the workpage. Deleting the tick buttons from the worksheet, makes the macro run perfectly.

Could you advise on how the macro could try ignore the buttons?

Best regards

Saliman
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

Nice to see you have solved the issue! :)
 
Upvote 0
Re: Need to Print Embedded PDFs - PLEASE HELP :(

thanks for the solution.

But it is working for only PDFs with single page, and not multiple page PDFs. I tried with a PDF with 2 pages, and 3 pages, and its throwing error, stating that the PDF didn't form completely, and needs to be repaired, and then adobe reader doesn't open anything.

please help!
 
Upvote 0

Forum statistics

Threads
1,216,108
Messages
6,128,872
Members
449,475
Latest member
Parik11

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top