PDA

View Full Version : Run Acrobat to convert Word document to pdf



Rejje
06-10-2011, 04:51 PM
Hi!

I wonder if anyone can show me a macro that:

Opens Acrobat
Creates a .pdf file from .docx file
Saves the .pdf file to a folder
Exits AcrobatThanks for all help so far at this forum!

Frosty
06-11-2011, 08:09 AM
Two comments:
1. Always better to ask the question rather than provide what you think is the answer. The question (I think) you're really asking is: "how do I create a .PDF file from my existing .docx file?"

2. Depends on version. What version of word are you using? Word 2010 has a built in ability to "print" the document to a .PDF format.

Do you really need adobe acrobat to do what you really want to do? Because opening other applications and manipulating them from vba is a good bit more complicated, if not impossible.

Frosty
06-11-2011, 08:12 AM
The above sounds snarky. It's not meant to. Sometimes the right question is the key to answering it yourself. Your question is a hard answer. But you may already know the answer to my version of your question :)

Rejje
06-11-2011, 08:36 AM
Snarky? Not! I understand the reasons for the comments. I even expected these remarks.

Here's why (order of comments):

No; I'm not asking how to create .pdf file from an existing .docx file. The macro that I want to include this piece of code in already does print the .pdf as you suggest in comment 2. However I'm not at all satisfied with the result due to some very specific details (hard to explain if one hasn't seen the .pdf result).
I have version 2007 (which as comment 1 shows of course also has the built in ability to "print" the document to a .PDF format).Printing the document directly from Acrobat gives a perfect result and it is therefore essential I get this to work. I know others have got this working so I guess I as well at least have a chance.

Thanks for the remarks!

Frosty
06-11-2011, 08:42 AM
I don't have an immediate answer, but I have one more suggestion-- try switching default printers when you print to the file. I noticed that if I had, for example, a black and white printer as my default printer... Printing a color document would show up as a black and white PDF.

But using a color printer as my default printer allowed color .PDFs to be printed from Word.

Other than that, you'll probably be researching some Shell commands, and need to look up your version of acrobat to see if there is a command line option of printing a file. Something you could type in Start > Run.

Hope that helps. If not, then it gets complicated.

Rejje
06-11-2011, 12:10 PM
Thanks for all help so far Frosty!

Nope - switching printer or its settings doesn't help in this case.

I don't really think it's that complicated though. Check out the link below and the manuals it provides for controlling just about any function within Acrobat from an Office application.

http://www.khk.net/wordpress/2009/03/04/adobe-acrobat-and-vba-an-introduction/

I keep trying to get it to work with what I gather from these documents. However I'm not vba-skilled enough to manage this by myself really (yet that is!).

What do you think?

Frosty
06-11-2011, 01:00 PM
I think you've got the documentation you need. I don't have adobe professional installed (or any of the full versions), so I can't test the code and provide you a solution, but it actually doesn't look that hard.

Do you know about CreateObject/GetObject? Maybe someone with the full version will be able to give you something specific.

Something along the lines of:

Sub Test
Dim oApp as Object
Dim oDoc as Object

Set oApp = CreateObject("AcroExch.App")

End Sub

Shouldn't throw up an error (which it's doing on my machine, since I only have reader).

Do you have any code at this point? Did you set a reference (which I'm not sure you actually need) specified in that link?

Frosty
06-11-2011, 01:14 PM
I guess the better approach is to actually perform exactly what he is doing on his website, and make sure you can do that (Excel 2007, etc).

If you can do exactly what he's doing, then I think you're in business... otherwise, you're going to need to have someone with the same version of Adobe installed help you, or start posting code and giving lines which are causing problems.

The problem is, just like Microsoft changes things between version... so does Adobe. So that example is Adobe 9.0... not sure what version you have, but things could be different.

And those technical documentation manuals are great, but there also voluminous. You're just looking for the .Open and the .Print and probably the .Exit commands.

Also-- doesn't installing adobe full give you a virtual "printer" that you can print to? If you selected that as your default printer, you can't do a print (not a file print) from Word and accomplish what you want? Or did you want to automate the whole thing (suggesting file/path name etc)?

Will be offline for a while, but hopefully this is pushing the ball further a little bit.

I'd try to recreate exactly what Karl has done, rather than try to extrapolate something from his code and find out, at the end of the day, that your setup is too different for even his original code to work

bstephens
06-11-2011, 01:48 PM
Rejje,

I am using the following code, and calling it from the ribbon, not the most elegant, but it works (also uses word's built in .pdf rendering as opposed to calling acrobat which is fine for my purposes). Might be helpful to you.

Sub Convert2PDF()
On Error GoTo ErrHandler

ErrHandler:
If Err <> 0 Then
' Display an error message.
MsgBox error(Err) & " Please close the .pdf document with the same file name as the open document and try again."
'MsgBox "No document open to create an Instant PDF"
'Clear the error.
Err.Clear
Exit Sub
End If

If IsDocEmpty = True Then Exit Sub
If ActiveDocument.Saved = False Then
Call MessageBoxAnswer
Else
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
ActiveDocument.Path & "\" & Left(ActiveDocument.Name, _
Len(ActiveDocument.Name) - 4) & ".pdf", ExportFormat:= _
wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentWithMarkup, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=False, UseISO19005_1:=False
'MsgBox ("Current changes to word document saved and Instant PDF created at:" & vbCrLf & ActiveDocument.Path & "\" & Left(ActiveDocument.Name, Len(ActiveDocument.Name) - 4) & ".pdf")

End If

End Sub

Sub MessageBoxAnswer()
Dim intAnswer As Integer
intAnswer = MsgBox("Current changes to the word document are not saved, save current changes and create instant PDF?", vbYesNo + vbQuestion, _
"Document Not Saved")
Select Case intAnswer
Case vbYes
Call FileSave
Call Convert2PDF
Case vbNo
Exit Sub
End Select
End Sub

'Callback for rxbtnConvert2PDF onAction
Sub rxbtnConvert2PDF_click(control As IRibbonControl)
Call Convert2PDF
End Sub

Function IsDocEmpty() As Boolean

' Initialize function to True.
IsDocEmpty = True
For Each astory In ActiveDocument.StoryRanges

' Check for text. If the length of the
' current story is greater than one, then
' there is either text or more than one
' empty line.
If Len(astory.Text) <> 1 Then
IsDocEmpty = False
End If

' Check for Objects.
' Note: If there are no objects within
' the current story range, an error occurs.
On Error Resume Next
If astory.ShapeRange.Count > 0 Then
If Err = 0 Then
IsDocEmpty = False
Else
On Error GoTo 0
End If
End If

' If something was found, then
' return to the calling routine with
' a value of False.
If IsDocEmpty = False Then Exit Function

Next

End Function

Rejje
06-11-2011, 05:38 PM
Regarding Frosty´s reply:

Unfortunately shifting default printer can't be considered as this will be used in an environment where shifting isn't an option due to policies.

Library: Adode Acrobat 8.0

Do I know about CreateObject/GetObject? Not in detail; my vba experience is about be a total of some 10 week of spare time learning and is also my total experience of script code. I guess you mean the dimming/setting of applications, files and such though.

Recreate exactly what Karl has done? Agree!

Well I'll start working on the code and post the it soon. Hopefully someone will follow up my issues as I keep trying.

I have not had time to check the sub yet - I'll get back on that soon.




Regarding bstephens´s reply:

The suggested code

ActiveDocument.ExportAsFixedFormat OutputFileName:= _
ActiveDocument.Path & "\" & Left(ActiveDocument.Name, _
Len(ActiveDocument.Name) - 4) & ".pdf" etc. etc.

is exactly what I've tried. This is what gives the lesser result in my particular project. Lesser in this case are small pieces of lines in tables where these are not supposed to be shown due to original formatting. These printed tables originate from excel by the way (if this could be a lead for anyone).


Thanks to both of you for helping!

Frosty
06-12-2011, 10:29 AM
So the .pdf from word is showing artifacts (lines) from an embedded excel spreadsheet?

Although it's an interesting exercise to get Acrobat working (and may very well be useful for other items), since you're spending the time trouble-shooting anyway, maybe it would be worth trying to solve the original problem, rather than trying to solve the "solution"?

There are options in excel (whether using white borders, or turing off the "grid lines" view options) which may affect an embedded object.

Of course, if you mean "copied and pasted" when you say "originate from excel" then that's something else.

But print drivers are notoriously finicky about borders and table cells (embedded object or not), so maybe you can try "jiggling" those things as well.

georgeeasten
06-13-2011, 06:38 AM
Another thought might be to open a blank pdf and paste the word document contents into the pdf using send keys.

Something like this might get you started:

Option Explicit

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

Function OpenAnyFile(FileToOpen As String)

Call ShellExecute(0, "Open", FileToOpen & vbNullString, _
vbNullString, vbNullString, 1)

End Function


Then you would run this when you want to create a pdf:

Sub ExApplication()
Selection.WholeStory
Selection.Copy
Call Open_Any.OpenAnyFile("C:\Program Files\Adobe\Acrobat.exe") 'this will need to be the correct path

'*****
'YOU NEED CODE HERE TO USE THE SetForeGroundWindow FUNCTION AND THE USE SendKeys BUT UNFORTUNATLEY I DO NOT HAVE EXPERIENCE WITH THESE
'*****

Application.Quit
End Sub

I cannot take credit for all of this as I had help from this forum previously.

Maybe someone else might be able to look at whether this is a possibility?!

georgeeasten
06-13-2011, 09:56 AM
I have been thinking about this because it intrigued me; I was working on something similar.

I have the following which I have been testing with notepad and also firefox to do an auto search. All you would need to do is change the application path to the Acrobat path and away you go (hopefully)!

I would be very interested to see if this works.

Sub get_it2()

Selection.WholeStory
Selection.Copy
Selection.HomeKey Unit:=wdStory

MyAppID = Shell("C:\WINDOWS\system32\notepad.exe", 1)
AppActivate MyAppID

SendKeys "^v"
SendKeys "^s"

End Sub

The only downside is that it uses sendkeys (although I'm not sure there is anything else you can do (I stand to be corrected!)).

You can also send ALT F4 and rely on the autosave function of Acrobat which will then close Acrobat after saving. If you want to use this then simply replace SendKeys "^s" with SendKeys "%{F4}" - I have not tested this.

Please also note I have been unable to test this with Acrobat because I do not have the full version.

Rejje
06-14-2011, 03:12 AM
I keep trying with the send keys but it doesn't seem to work. Adobe opens up but really there is no where to paste Word's wholestory. Acrobat needs to work with files, or scan.

I also tried what would happen in case I copied the Word file, opened Acrobat and tried to ctrl+v: Nothing!

Intrigued as well I have continued thinking in your way and this is what I've come up with:

One can right click the Word file and choose "Convert to Adobe PDF". This runs Acrobat with exactly the same result as creating .pdf from open Acrobat app.

What do you think about this idea? Could it work with send keys?

georgeeasten
06-14-2011, 03:47 AM
You could try sending all of the key combinations to create a new document rather than attempting to select a file though the openfile dialog.

Something like this should work:Sub Acrobat()

Selection.WholeStory
Selection.Copy

MyAppID = Shell("C:\WINDOWS\system32\notepad.exe", 1)
AppActivate MyAppID
SendKeys "^n", True
Sleep (2000)
'*****
'enter additional send keys (ensuring to include the wait = true) to create 'the appropriate document for pasting into
'*****
Sleep (5000) 'experiment with the time to sleep -this is currently 5 seconds
SendKeys "^v", True
SendKeys "^s", True

End Sub


I have called the Sleep API which you will need to add to the declarations:Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Just select declarations in the top right dropdown and paste the above.

This is a link which sets out the SendKeys you will need:
http://msdn.microsoft.com/en-us/library/aa202943%28v=office.10%29.aspx

Send Key for down four times would appear like this:SendKeys "{DOWN}{DOWN}{DOWN}{DOWN}", True

As stated before SendKeys can be very unreliable so this is why I have called the Sleep declaration so we can wait for Acrobat to do its thing.

You might want to consider moving to VB to solve this because that is much more versatile and reliable. I am currently rewriting everything so I can control everything through VB - it is a slow process!!!

georgeeasten
06-14-2011, 05:34 AM
I think the SendKeys should be something like this:

SendKeys "%", True
SendKeys "{DOWN 4}{RIGHT}{DOWN 5}{ENTER}", True

This sends Alt to select the File menu and waits for it to be executed then moves down to create pdf and then blank pdf. You should then be able to paste into this ending up with:Sub Acrobat()

Selection.WholeStory
Selection.Copy

MyAppID = Shell("C:\WINDOWS\system32\notepad.exe", 1)
AppActivate MyAppID

SendKeys "%", True
SendKeys "{DOWN 4}{RIGHT}{DOWN 5}{ENTER}", True

Sleep (5000) 'experiment with the time to sleep - this is 5 currently seconds

SendKeys "^v", True

Sleep (2000) 'experiment with the time to sleep - this is 2 currently seconds

SendKeys "^s", True

End Sub

I have got this from a website displaying a screen shot of the menu, however, your version may be different. Also, if multiple users are to utilise this and they have different versions it may not work.

Frosty
06-14-2011, 04:04 PM
Don't you run into problems in Windows 7 with SendKeys and UAC (User Account Control)?

I still think the best way to proceed is to solve the original problem: get rid of the gridlines the Word PDF printer is *thinking* it sees. However, I can only watch on the sidelines and wish you luck!