Insert PDF into Word Document using Java

This guide describes how to insert PDF into Word document using Java. It covers the IDE setup, a list of programming steps, and a working code sample demonstrating how to add a PDF into Word using Java. Tips are also shared at the end to change the position and icon of the attachment and to embed files of other formats.

Steps to Attach a PDF to Word using Java

  1. Configure the IDE to use Aspose.Words for Java for attaching a PDF file to a Word document
  2. Open the destination Word file in the Document object
  3. Initialize a DocumentBuilder for the loaded document and add a line of text to introduce the attachment
  4. Read the PDF file into a FileInputStream
  5. Call the insertOleObjectAsIcon() method to place the PDF in the document as an icon with a caption
  6. Assign a file name and display name to the package of the embedded PDF
  7. Save the Word document containing the PDF attachment

These steps explain how to embed a PDF in Word using Java. Open the destination Word file, add an introductory line with the DocumentBuilder, and read the PDF into a FileInputStream. The insertOleObjectAsIcon() method then places this stream in the document as an icon, after which the file name and display name of the package are assigned and the output Word file is saved.

Code to Insert a PDF into Word using Java

This sample code shows how to attach a document in Word using Java. To place the attachment inside a table or at a bookmarked location, call moveToCell() or moveToBookmark() before inserting the PDF. A custom icon can be displayed by passing the path of an ICO file as the third parameter of insertOleObjectAsIcon() instead of null. The same approach also works for other file types, such as Excel sheets, PowerPoint presentations, or ZIP archives.

This guide has shown how to attach a PDF file to a Word document as an embedded object. To delete bookmarks from a Word file, see the article Remove Bookmark in Word using Java.