Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print mail item as pdf

Tags:

vba

outlook

I am attempting to save all of the mail items within a folder in Outlook as PDF.

Sub pdfConversion()
    Dim outApp As Object, objOutlook As Object, objFolder As Object, myItems As Object, myItem As Object
    Dim psName As String, pdfName As String

    Set outApp = CreateObject("Outlook.Application")
    Set objOutlook = outApp.GetNamespace("MAPI")
    Set objFolder = objOutlook.GetDefaultFolder(olFolderInbox).Folders("PDF Conversion")
    Set myItems = objFolder.Items

    For Each myItem In myItems
        myItem.PrintOut copies:=1, preview:=False, ActivePrinter:="Adobe PDF", printtofile:=True, _
        collate:=True, prtofilename:="C:\Users\lturner\Documents\" & myItem.Subject & ".pdf"
    Next myItem
End Sub

I am using Outlook 2007, which doesn't have the option to save mails as PDF, hence I'm attempting to use the .PrintOut method.

Using the above I am currently receiving a "Named argument not found" error. I've looked elsewhere on the internet, but cannot seem to find a solution.

like image 871
luke_t Avatar asked Jul 14 '15 09:07

luke_t


2 Answers

I used a combination of the answers posted by Krishna and Eugene Astafiev to produce the below code, which will now produce a PDF document out of the myItem.

Dim objDoc As Object, objInspector As Object
For Each myItem In myItems
    fileName = Replace(myItem.Subject, ":", "")
    Set objInspector = myItem.GetInspector
    Set objDoc = objInspector.WordEditor
    objDoc.ExportAsFixedFormat folderPath & fileName & ".pdf", 17
    Set objInspector = Nothing
    Set objDoc = Nothing
Next myItem

Posting this so anyone in the future who stumbles across the question can see the working code, which uses the WordEditor property.

like image 170
luke_t Avatar answered Nov 13 '22 21:11

luke_t


There is no need to use the SaveAs method of the MailItem class. The WordEditor property of the Inspector class returns an instance of the Word Document class which represents the message body. You can call the ExportAsFixedFormat method of the Document class directly from Outlook avoiding any disk operations. See Chapter 17: Working with Item Bodies for more information.

like image 35
Eugene Astafiev Avatar answered Nov 13 '22 19:11

Eugene Astafiev