Save image to a new word document

14 views (last 30 days)
Miguel Herrera
Miguel Herrera on 19 Apr 2018
Answered: Madheswaran on 28 Dec 2024 at 5:53
Good afternoon, relatively simple question. Lets say a have a graph plot(x,y) and want to save that image to a new word document. I'd like to give that graph a label (ex. Figure 1) and also add more graphs to it. Also, is there an automated way of naming said word document?
  1 Comment
Guillaume
Guillaume on 19 Apr 2018
In my opinion, you'll spend less time saving the graph as an image (or better as SVG) and importing that manually into word than writing the code to do that automatically from matlab.

Sign in to comment.

Answers (1)

Madheswaran
Madheswaran on 28 Dec 2024 at 5:53
Hi Miguel,
You can use MATLAB's 'actxserver' to interact with Microsoft Word to achieve your desired task. Below is a minimal example to create a Word document, insert a plot as an image, label it, and save the document with an automated name.
% Sample data for plotting
x = 1:10;
y = rand(1, 10);
% Create a new figure and plot
fig = figure('Visible','off');
plot(x, y);
title('Sample Plot');
% Save the plot as an image
imgFile = 'tempPlot.png';
saveas(fig, imgFile);
% Initialize Word application
wordApp = actxserver('Word.Application');
wordApp.Visible = false; % Set to true if you want to see the Word application
doc = wordApp.Documents.Add;
% Insert plot image into the Word document
selection = wordApp.Selection;
selection.InlineShapes.AddPicture(fullfile(pwd, imgFile));
selection.TypeParagraph; % Move to a new line
selection.TypeText('Figure 1: Sample Plot');
% Add more graphs if needed
docFileName = [pwd '\GraphDocument.docx'];
invoke(doc, 'saveas', docFileName);
% Clean up
doc.Close;
wordApp.Quit;
delete(wordApp);
delete(imgFile);
disp(['Word document saved as: ' docFileName]);
The above code generates a sample graph and inserts it into a Word document, which is then saved in the current working directory. To change the document's name or save location, you can modify the 'docFileName' variable accordingly.
For more information, refer to the following MathWorks documentation:
  1. actxserver - https://mathworks.com/help/releases/R2024b/matlab/ref/actxserver.html
  2. invoke - https://mathworks.com/help/releases/R2024b/matlab/ref/com.invoke.html
Hope this helps!

Categories

Find more on Printing and Saving in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!