PDA

View Full Version : Converting Word to PDF using VBA



knly5292
09-14-2012, 09:07 AM
Hello,

I've used the ExportAsFixedFormat function to convert a saved Word document to PDF. It works great on my computer, but when I ran it on another computer it crashed.

Here's the code


Private Sub ConvertToPDF(ByVal Doc As Word.Document, ByVal App As Word.Application, ByRef Template As clsTemplate)

Dim DocName As String 'The name of the document

DocName = Doc.Name
'Remove word document extention from pdf file name
If InStr(1, DocName, ".docx") > 0 Then
DocName = Replace(DocName, ".docx", "")
ElseIf InStr(1, DocName, ".doc") > 0 Then
DocName = Replace(DocName, ".doc", "")
End If
Template.PDFPath = Doc.Path & "\" & DocName & ".pdf"


Doc.ExportAsFixedFormat OutputFileName:=Template.PDFPath, ExportFormat:= _
wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent, IncludeDocProps:=True
End Sub


It'd be great if someone can tell me why it doesn't work on another computer.

Thanks

Kenneth Hobs
09-14-2012, 09:22 AM
Welcome to the forum!

Do it manually and then you will have you answer most likely. If not, you did not add the references or class as needed maybe.

Crash does not help us help you.

knly5292
09-14-2012, 10:03 AM
I have the same references on both computers. When I ran it on the second computer it had an error simply saying cannot open PDF file and closes.

Kenneth Hobs
09-14-2012, 11:33 AM
Try posting a sample doc and a simple test routine.

Of course you could step through the code with F8 to see where it runs amiss.

snb
09-14-2012, 02:22 PM
I think I would use:



Private Sub ConvertToPDF(ByVal Doc As Word.Document)
Doc.ExportAsFixedFormat doc.path & "\" & createobject("scripting.filesystemobject").getbasename(doc) & ".pdf" ,wdExportFormatPDF
End Sub

arronlee
09-16-2015, 01:44 AM
Hi, knly.
I wonder How to deal with these code? Do I need another 3rd party manual toolkit? When it comes to PDF converting process, I have another question, I wonder have you ever tried to convert pdf to other image files before? As for myself, I am testing the related PDF to PNG converting (http://www.pqscan.com/convert-pdf/to-png-csharp.html), PDF to BMP converting (http://www.pqscan.com/convert-pdf/to-bmp-csharp.html) , and PDF to JPG converting programs these days. Do you have experience about it? Any suggestion will be appreciated. Thanks in advance.



Best regards,
Pan