Add a PDF into a word document using docxtemplater

366 views Asked by At

Is there any possible way to add an existing PDF-File into a word document using docxtemplater (e.g. in connection with survey.JS) Manually you can do this within Word by selecting > Insert > Object > Create From File > Browse the PDF you want to insert. Many thanks!

Could't find any tag (as a placeholder) in docxtemplater for PDFs yet. Not sure, if the image module could help here?

1

There are 1 answers

0
Eugene Astafiev On

You can add an OLE object in the following way in VBA:

Sub InsertAttachment()
    Dim oRng As Range
    On Error GoTo err_Handler
    Set oRng = ActiveDocument.Bookmarks("BM").Range
    If oRng.InlineShapes.Count > 0 Then oRng.InlineShapes(1).Delete
    ActiveDocument.InlineShapes.AddOLEObject _
            ClassType:="AcroExch.Document.DC", _
            FileName:=Environ("UserProfile") & "\Desktop\test.pdf", _
            LinkToFile:=False, _
            DisplayAsIcon:=True, _
            IconFileName:="C:\path_to_icon\PDFFile.ico", _
            IconIndex:=0, _
            IconLabel:="This is a test", _
            Range:=oRng
    oRng.End = oRng.End + 2
    oRng.Select
    ActiveDocument.Bookmarks.Add Name:="BM", Range:=oRng
lbl_Exit:
    Set oRng = Nothing
    Exit Sub
err_Handler:
    If Err.Number = 5941 Then
        MsgBox "The bookmarked location cannot be found"
    Else
        MsgBox "There has been an unhandled error number " & Err.Number & vbCr & Err.Description
    End If
    Err.Clear
    GoTo lbl_Exit
End Sub

The InlineShapes.AddOLEObject method creates an OLE object and returns the InlineShape object that represents the new OLE object.