How to paste figures in an opened ms word document? (programmatically using COM Automation server))

32 views (last 30 days)
Is it possible to connect to an opened or active MSword document (the one I'm editing at that moment) and paste any matlab figures? There are a lot of answers were MSword documents are opened or created, but now I want to paste some matlab results into an opened document. I think it must be something like this:
  1. let script connect to the active document using activex server
  2. copy figure programmatically
  3. paste matlab results in word doc programmatically
  4. release connection and leave doc open (so that I can proceed documentation in MSword)
Regards, Patrick

Accepted Answer

Raptrick
Raptrick on 13 Apr 2016
Thanks for all the answers. The following code is what I was looking for. Before running this script you have to open a MS word document. Position the cursor at the position where you want to paste the figure.
% Generate test plot
x = linspace(0,2*pi,1000);
plot(x,sin(x));
% Copy current figure
print(gcf, '-dmeta')
% Get a handle to the running Microsoft Word program:
h = actxGetRunningServer('word.Application');
% Command line notification
disp(['Pasting a figure in ' h.ActiveDocument.Name ])
% Pastespecial as Shape
h.selection.PasteSpecial(0,0,1,0,3)
% Modify shape size (72 points in one inch) and convert to
% InlineShape. Move cursor one position to the right for the next action.
h.selection.ShapeRange.Width = 1*72; % width = 1inch
h.selection.Shaperange.ConvertToInlineShape
h.selection.Start = h.selection.Start+1;
h.selection.End = h.selection.End+1;
% End notification (optional)
h.selection.TypeText('end')
Patrick

More Answers (3)

MBD4FUN
MBD4FUN on 10 Apr 2016

Image Analyst
Image Analyst on 10 Apr 2016

Image Analyst
Image Analyst on 29 Apr 2020
Here is a full demo that shows you three different ways/options for saving axes into an existing Word Document using Word as an ActiveX server. This demo reads all PNG format images from the drive into the axes, and pastes them into a Word document that you specify:
% Script to save MATLAB axes (containing Tif images, or whatever you want) at the top of a Word Document.
% By Image Analyst. April 2020.
% Initialization steps. Brute force cleanup of everything currently existing to start with a clean slate.
% Just for the demo. If you put this into your own function you'll want to get rid of the close and clear commands.
clc; % Clear the command window.
fprintf('Beginning to run %s.m ...\n', mfilename);
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
%---------------------------------------------------------------------------------------------------------
% Specify the existing Word document that we want to paste images into.
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
if ~isfolder(startingFolder)
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.doc*');
[baseFileName, wordDocumentFolder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% Exit if the user clicked the Cancel button.
return;
end
wordFullFileName = fullfile(wordDocumentFolder, baseFileName)
if ~isfile(wordFullFileName)
% They probably typed in a new name for a non-existent document.
msgbox('Error: %s must exist already, and it does not.', wordFullFileName);
return;
end
%---------------------------------------------------------------------------------------------------------
% Get a list of TIF images.
imagesFolder = pwd; % The current folder, or wherever you want.
fprintf('Now getting a list of image files in folder "%s".\n', imagesFolder);
filePattern = fullfile(imagesFolder, '*.png'); % Change to whatever extension (image file format) you want.
fileList = dir(filePattern);
if isempty(fileList)
[~, ~, ext] = fileparts(filePattern);
warningMessage = sprintf('No %s format images found in folder\n%s\n\nExiting.', ext, imagesFolder);
uiwait(warndlg(warningMessage));
return; % Exit since there's nothing to do. No images to paste!
end
numberOfFiles = length(fileList);
%---------------------------------------------------------------------------------------------------------
% Open the document in Word using ActiveX.
fprintf('MATLAB is launching Word as an ActiveX server...\n');
Word = actxserver('Word.Application'); % A MATLAB function.
fprintf('Word is now opening "%s" ...\n', wordFullFileName);
Word.Documents.Open(wordFullFileName); % An ActiveX method.
fprintf('Document "%s" has been opened in Word. Now making it visible.\n', wordFullFileName);
Word.Visible = true; % Make it visible. An ActiveX property.
% Set horizontal alignment
% Word.Selection.ParagraphFormat.Alignment options formats:
% 0: Left-aligned
% 1: Center-aligned
% 2: Right-aligned
% 3: Fully justified
% 4: Paragraph characters are distributed to fill the entire
% width of the paragraph
% 5: Justified with a medium character compression ratio
% 6: Does not exist.
% 7: Justified with a high character compression ratio
% 8: Justified with a low character compression ratio
% 9: Justified according to Thai formatting Layout
Word.Selection.ParagraphFormat.Alignment = 0; % Left align the images. An ActiveX property.
hFig = figure; % Bring up new figure.
%---------------------------------------------------------------------------------------------------------
% For each image drop onto the Word document.
for k = 1 : numberOfFiles
pictureFullFileName = fullfile(fileList(k).folder, fileList(k).name);
fprintf('Reading in %s, and pasting onto document.\n', fileList(k).name);
theImage = imread(pictureFullFileName);
imshow(theImage);
hFig.WindowState = 'maximized'; % Need to re-maximize each figure since imshow() unmaximizes them.
caption = sprintf('#%d of %d : %s', k, numberOfFiles, fileList(k).name);
title(caption, 'FontSize', 15, 'Interpreter', 'none'); % Using 'Interpreter', 'none' so underlines in the file name don't cause the title to be subscripted after the underline
drawnow;
pause(0.6); % Optional : Delay a bit so we can see the image before it vanishes.
% Pick only ONE of the 3 options below to paste the axes into Word at the beginning of the document.
%---------------------------------------------------------------------------------------------------------
% OPTION 1: Transfer to Word by copying the current axes object to the clipboard and pasting into Word using ActiveX method Selection.Paste().
% If you're using r2020a or later, use copygraphics() instead of the print() to copy the figure to the clipboard.
copygraphics(gca); % A MATLAB function. This will also copy the title above the image, and the axis tick marks (if showing) in addition to the image.
Word.Selection.Paste; % An ActiveX method.
%---------------------------------------------------------------------------------------------------------
% OPTION 2: Transfer to Word by giving the file name string to the InlineShapes.AddPicture method of ActiveX.
% Tell Word to read the file from the drive using it's filename, and then insert into the document.
% Word.Selection.InlineShapes.AddPicture(pictureFullFileName,0,1); % An ActiveX method.
%---------------------------------------------------------------------------------------------------------
% OPTION 3: Transfer to Word by giving the file name string to the InlineShapes.AddPicture method of ActiveX.
% Pre-2020a, use print to copy the figure to the clipboard.
% print(gca, '-dmeta'); % Export figure to clipboard
% invoke(Word.Selection,'Paste'); % An ActiveX method.
end
%---------------------------------------------------------------------------------------------------------
% Clean up and shutdown.
% Close the image figure window.
close(hFig);
% Save the active Word document without prompting the user.
fprintf('Now saving Word document "%s".\n', wordFullFileName);
Word.ActiveDocument.Save(); % An ActiveX method.
% Shut down Word. Close it.
fprintf('Now shutting down the Word ActiveX server.\n');
Word.Quit; % An ActiveX method.
% Clear the variable from MATLAB's memory (workspace).
clear('Word');
% Let user know that we're all done, and offer to open the file.
promptMessage = sprintf('Done pasting %d images into Word.\nDo you want to open the document in Word?', numberOfFiles);
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Yes - Continue', 'No - Quit', 'Yes - Continue');
if contains(buttonText, 'Yes', 'IgnoreCase', true)
% Cause the operating system to launch Word and open the document.
winopen(wordFullFileName);
end
fprintf('Done running %s.m ...\n', mfilename);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!