forked from stefslon/exportToPPTX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exportToPPTX.m
executable file
·3075 lines (2680 loc) · 166 KB
/
exportToPPTX.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef exportToPPTX < handle
% exportToPPTX Creates PowerPoint 2007+ (PPTX) slides
%
% exportToPPTX allows user to create PowerPoint 2007+ (PPTX) files
% without using COM-objects automation. Proper XML files are created and
% packed into PPTX file that can be read and displayed by PowerPoint.
%
% exportToPPTX methods:
% exportToPPTX - Starts new presentation or opens an existing presentation
% save - Saves current presentation
% addSlide - Adds a slide to the presentation
% switchSlide - Switches current slide to a given slide ID
% addPicture - Adds picture to the current slide
% addShape - Adds lines or closed shapes to the current slide
% addNote - Adds notes information to the current slide
% addTextbox - Adds textbox to the current slide
% addTable - Adds PowerPoint table to the current slide
%
% exportToPPTX properties:
% author - Presentation's author, default is 'exportToPPTX'
% title - Presentation's title, default is 'Blank'
% subject - Presentation's subject, default is blank
% description - Presentation's description, default is blank
%
% Basic usage example:
%
% % Start new presentation
% pptx = exportToPPTX();
%
% % Set presentation title
% pptx.title = 'Basic example'
%
% % Just an example image
% load mandrill; figure('color','w'); image(X); colormap(map); axis off; axis image;
%
% % Add slide, then add image to it, then add box
% pptx.addSlide();
% pptx.addPicture(gcf,'Scale','maxfixed');
% pptx.addTextbox('Mandrill','Position',[0 5 6 1],'FontWeight','bold','HorizontalAlignment','center','VerticalAlignment','bottom');
%
% % Save
% pptx.save('example.pptx');
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% PROPERTIES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Define constants
properties (Constant,Access=private)
CONST_IN_TO_EMU = 914400;
CONST_PT_TO_EMU = 12700;
CONST_DEG_TO_EMU = 60000;
CONST_FONT_PX_TO_PPTX = 100;
end
%% Define run-time public (settable) properties
properties (Access=public)
% author Presentation's author, default is 'exportToPPTX'
%
% Example:
% pptx.author = 'exportToPPTX Example';
author = 'exportToPPTX';
% title Presentation's title, default is 'Blank'
%
% Example:
% pptx.title = 'Demonstration Presentation';
title = 'Blank';
% subject Presentation's subject, default is blank
%
% Example:
% pptx.subject = 'Demonstration of various exportToPPTX commands';
subject = '';
% description Presentation's description, default is blank
%
% Example:
% pptx.description = 'Description goes in here';
description = '';
end
%% Define run-time gettable properties (not settable)
properties (GetAccess=public,SetAccess=private)
dimensions = [10 7.5]; % Presentation's dimensions in inches (read only)
fullName = ''; % Full filename of the openned presentation (empty if new)
numSlides = 0; % Total number of slides
currentSlide % Current slide
end
%% Define run-time private properties (for internal use)
properties (Access=private)
revNumber = 0;
numMasters
tempName
createdDate
updatedDate
imageTypes
videoTypes
bgColor
lastSlideId
lastRId
themeNum = 0;
Slide
SlideMaster
NotesMaster
end
%% Define internal XML structures that are kept in memory for modifications
properties (Access=private)
XML
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% METHODS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Public methods
methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PPTX = exportToPPTX(fileName,varargin)
% exportToPPTX([fileName],...)
%
% Start new presentation or open an existing presentation
% Actual PowerPoint files are not written until 'save' command is called.
% No required inputs. This command does not return any values.
%
% Additional parameters:
% Dimensions two element vector specifying presentation's width and
% height in inches. Default size is 10 x 7.5 in.
% Author specify presentation's author. Default is "exportToPPTX".
% Title specify presentation's title. Default is "Blank".
% Subject specify presentation's subject line. Default is empty (blank).
% Comments specify presentation's comments. Default is empty (blank).
% BackgroundColor Three element vector specifying RGB value in the
% range from 0 to 1. By default background is white.
%
% Examples:
% % Start new presentation
% pptx = exportToPPTX();
%
% % Open existing presentation
% pptx = exportToPPTX('\\path\to\some\existing\presentation.pptx');
%% Obtain temp folder name
tempName = tempname;
while exist(tempName,'dir'),
tempName = tempname;
end
%% Create temp folder to hold all PPTX files
mkdir(tempName);
PPTX.tempName = tempName;
if nargin>0 && ~isempty(fileName)
% Open file
%% Check input validity
[filePath,fileName,fileExt] = fileparts(fileName);
if isempty(filePath),
filePath = pwd;
end
if ~strncmpi(fileExt,'.pptx',5),
fileExt = cat(2,fileExt,'.pptx');
end
fullName = fullfile(filePath,cat(2,fileName,fileExt));
PPTX.fullName = fullName;
if exist(PPTX.fullName,'file'),
PPTX.openExistingPPTX();
%% Load important XML files into memory
PPTX.loadAndParseXMLFiles();
else
error('exportToPPTX:fileNotFound','PPTX to open (%s) not found.',PPTX.fullName);
end
else
% New file
mi = false(size(varargin));
[PPTX.dimensions,mi] = exportToPPTX.getPVPair(varargin,'Dimensions',PPTX.dimensions,mi);
[PPTX.author,mi] = exportToPPTX.getPVPair(varargin,'Author',PPTX.author,mi);
[PPTX.title,mi] = exportToPPTX.getPVPair(varargin,'Title',PPTX.title,mi);
[PPTX.subject,mi] = exportToPPTX.getPVPair(varargin,'Subject',PPTX.subject,mi);
[PPTX.description,mi] = exportToPPTX.getPVPair(varargin,'Comments',PPTX.description,mi);
[PPTX.bgColor,mi] = exportToPPTX.getPVPair(varargin,'BackgroundColor',[],mi);
if any(~mi)
error('exportToPPTX:badProperty','Unrecognized property %s',varargin{find(~mi,1)});
end
if numel(PPTX.dimensions)~=2,
error('exportToPPTX:badDimensions','Slide dimensions vector must have two values only: width x height');
end
if ~isempty(PPTX.bgColor),
if ~isnumeric(PPTX.bgColor) || numel(PPTX.bgColor)~=3,
error('exportToPPTX:badProperty','Bad property value found in BackgroundColor');
end
end
%% Create new (empty) PPTX files structure
PPTX.fullName = [];
PPTX.createdDate = datestr(now,'yyyy-mm-ddTHH:MM:SS');
PPTX.initBlankPPTX();
PPTX.loadAndParseXMLFiles();
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function delete(PPTX)
% Destructor: clears out temporary storage
% TODO: check if recently saved before destroying changes
% Remove temporary directory and all its contents
rmdir(PPTX.tempName,'s');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function disp(PPTX)
% Command window display
showFileName = PPTX.fullName;
if isempty(showFileName),
showFileName = '<new>';
end
fprintf('\tFile: %s\n',showFileName);
fprintf('\tTotal slides: %d\n',PPTX.numSlides);
fprintf('\tCurrent slide: %d\n',PPTX.currentSlide);
fprintf('\tAuthor: %s\n',PPTX.author);
fprintf('\tTitle: %s\n',PPTX.title);
fprintf('\tSubject: %s\n',PPTX.subject);
fprintf('\tDescription: %s\n',PPTX.description);
fprintf('\tDimensions: %.2f x %.2f in\n',PPTX.dimensions);
fprintf('\n');
if ~isempty(PPTX.SlideMaster),
for imast=1:numel(PPTX.SlideMaster),
fprintf('\tMaster #%d: %s\n',imast,PPTX.SlideMaster(imast).name);
if ~isempty(PPTX.SlideMaster(imast).Layout),
for ilay=1:numel(PPTX.SlideMaster(imast).Layout),
placeHolders = sprintf('%s, ',PPTX.SlideMaster(imast).Layout(ilay).place{:});
if ~isempty(placeHolders),
placeHolders = sprintf('(%s)',placeHolders(1:end-2));
end
fprintf('\t\tLayout #%d: %s %s\n',ilay,PPTX.SlideMaster(imast).Layout(ilay).name,placeHolders);
end
else
fprintf('\t\tNo layouts defined.\n');
end
end
else
fprintf('\tNo master layouts defined.\n');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function currentSlideId = addSlide(PPTX,varargin)
% addSlide(...)
%
% Adds a slide to the presentation. No additional inputs required. Returns
% newly created slide ID (sequential slide number signifying total slides in
% the deck, not neccessarily slide order).
%
% Additional parameters:
% Position Specify position at which to insert new slide. The value
% must be between 1 and the total number of slides.
% BackgroundColor Three element vector specifying RGB value in the
% range from 0 to 1. By default background is white.
% Master Master layout ID or name. By default first master layout is used.
% Layout Slide template layout ID or name. By default first slide
% template layout is used.
%
% Examples:
% % Add new slide
% pptx.addSlide();
%
% % Add new slide with green background at position 1
% pptx.addSlide('BackgroundColor','g','Position',1);
% Adding a new slide to PPTX
% 1. Create slide#.xml file
% 2. Create slide#.xml.rels file
% 3. Update presentation.xml to include new slide
% 4. Update presentation.xml.rels to link new slide to presentation.xml
% 5. Update [Content_Types].xml
% Parse optional inputs
mi = false(size(varargin));
[bgCol,mi] = exportToPPTX.getPVPair(varargin,'BackgroundColor',[],mi);
[insPos,mi] = exportToPPTX.getPVPair(varargin,'Position',[],mi);
[masterID,mi] = exportToPPTX.getPVPair(varargin,'Master',1,mi);
[layoutID,mi] = exportToPPTX.getPVPair(varargin,'Layout',1,mi);
if any(~mi)
error('exportToPPTX:badProperty','Unrecognized property %s',varargin{find(~mi,1)});
end
bgCol = exportToPPTX.validateColor(bgCol);
if ~isempty(bgCol),
bgContent = { ...
'<p:bg>'
'<p:bgPr>'
'<a:solidFill>'
['<a:srgbClr val="' bgCol '"/>']
'</a:solidFill>'
'<a:effectLst/>'
'</p:bgPr>'
'</p:bg>'
};
else
bgContent = {};
end
if ~isempty(insPos) && (insPos<1 || insPos>PPTX.numSlides+1 || numel(insPos)>1),
% Error condition
error('exportToPPTX:badProperty','addSlide position must be between 1 and the total number of slides');
end
% Parse master number and layout number
% Use first master slide by default
if isnumeric(masterID),
masterNum = masterID;
elseif ischar(masterID),
masterNum = find(strncmpi({PPTX.SlideMaster.name},masterID,length(masterID)));
if isempty(masterNum),
warning('exportToPPTX:badName','Master layout "%s" does not exist in the current presentation',masterID);
masterNum = 1;
end
if numel(masterNum)>1,
warning('exportToPPTX:badName','There are multiple matches for master layout "%s"',masterID);
masterNum = masterNum(1);
end
end
if ~isempty(masterNum) && (masterNum<1 || masterNum>PPTX.numMasters),
error('exportToPPTX:badProperty','addSlide cannot proceed because requested slide master number does not exist');
end
% Use first layout slide by default
if isnumeric(layoutID),
layoutNum = layoutID;
elseif ischar(layoutID)
layoutNum = find(strcmp({PPTX.SlideMaster(masterNum).Layout.name},layoutID));
if isempty(layoutNum)
layoutNum = find(strncmpi({PPTX.SlideMaster(masterNum).Layout.name},layoutID,length(layoutID)));
end
if isempty(layoutNum)
warning('exportToPPTX:badName','Layout "%s" does not exist in the current master',layoutID);
layoutNum = 1;
end
if numel(layoutNum)>1
warning('exportToPPTX:badName','There are multiple matches for layout "%s"',layoutID);
layoutNum = layoutNum(1);
end
end
if ~isempty(layoutNum) && (layoutNum<1 || layoutNum>PPTX.SlideMaster(masterNum).numLayout),
error('exportToPPTX:badProperty','addSlide cannot proceed because requested slide layout number does not exist');
end
% Check if slides folder exists
if ~exist(fullfile(PPTX.tempName,'ppt','slides'),'dir'),
mkdir(fullfile(PPTX.tempName,'ppt','slides'));
mkdir(fullfile(PPTX.tempName,'ppt','slides','_rels'));
end
% Before creating new slide, is there a current slide that needs to be
% saved to XML file?
if isfield(PPTX.XML,'Slide') && ~isempty(PPTX.XML.Slide),
fileName = PPTX.Slide(PPTX.currentSlide).file;
xmlwrite(fullfile(PPTX.tempName,'ppt','slides',fileName),PPTX.XML.Slide);
xmlwrite(fullfile(PPTX.tempName,'ppt','slides','_rels',cat(2,fileName,'.rels')),PPTX.XML.SlideRel);
end
% Update useful variables
PPTX.numSlides = PPTX.numSlides+1;
PPTX.lastSlideId = PPTX.lastSlideId+1;
PPTX.lastRId = PPTX.lastRId+1;
% Create new XML file
% file name and path are relative to presentation.xml file
fileName = sprintf('slide%d.xml',PPTX.numSlides);
fileContent = { ...
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">'
'<p:cSld>'
[bgContent{:}]
'<p:spTree>'
'<p:nvGrpSpPr>'
'<p:cNvPr id="1" name=""/>'
'<p:cNvGrpSpPr/>'
'<p:nvPr/>'
'</p:nvGrpSpPr>'
'<p:grpSpPr>'
'<a:xfrm>'
'<a:off x="0" y="0"/>'
'<a:ext cx="0" cy="0"/>'
'<a:chOff x="0" y="0"/>'
'<a:chExt cx="0" cy="0"/>'
'</a:xfrm>'
'</p:grpSpPr>'
'</p:spTree>'
'</p:cSld>'
'<p:clrMapOvr>'
'<a:masterClrMapping/>'
'</p:clrMapOvr>'
'</p:sld>'};
retCode = exportToPPTX.writeTextFile(fullfile(PPTX.tempName,'ppt','slides',fileName),fileContent);
% Create new XML relationships file
fileRelsPath = cat(2,fileName,'.rels');
fileContent = { ...
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
['<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/' PPTX.SlideMaster(masterNum).Layout(layoutNum).file '"/>']
'</Relationships>'};
retCode = exportToPPTX.writeTextFile(fullfile(PPTX.tempName,'ppt','slides','_rels',fileRelsPath),fileContent) & retCode;
% Link new slide to presentation.xml
% Check if list of slides node exists
sldIdLstNode = exportToPPTX.findNode(PPTX.XML.Pres,'p:sldIdLst');
if isempty(sldIdLstNode),
% Note: order of tags within XML structure is important, slide list
% must show up after p:sldMasterIdLst and before p:sldSz
exportToPPTX.addNodeBefore(PPTX.XML.Pres,'p:presentation','p:sldIdLst','p:sldSz');
end
% Order of items in the sldIdLst node determines the order of the slides
if ~isempty(insPos),
exportToPPTX.addNodeAtPosition(PPTX.XML.Pres,'p:sldIdLst','p:sldId',insPos, ...
{'id',int2str(PPTX.lastSlideId), ...
'r:id',sprintf('rId%d',PPTX.lastRId)});
else
exportToPPTX.addNode(PPTX.XML.Pres,'p:sldIdLst','p:sldId', ...
{'id',int2str(PPTX.lastSlideId), ...
'r:id',sprintf('rId%d',PPTX.lastRId)});
end
% Link new slide filename to presentation.xml slide ID
exportToPPTX.addNode(PPTX.XML.PresRel,'Relationships','Relationship', ...
{'Id',cat(2,'rId',int2str(PPTX.lastRId)), ...
'Type','http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide', ...
'Target',cat(2,'slides/',fileName)});
% Include new slide in the table of contents
exportToPPTX.addNode(PPTX.XML.TOC,'Types','Override', ...
{'PartName',cat(2,'/ppt/slides/',fileName), ...
'ContentType','application/vnd.openxmlformats-officedocument.presentationml.slide+xml'});
% Load created files
PPTX.XML.Slide = xmlread(fullfile(PPTX.tempName,'ppt','slides',fileName));
PPTX.XML.SlideRel = xmlread(fullfile(PPTX.tempName,'ppt','slides','_rels',fileRelsPath));
% Even though masterNum and layoutNum variables are available in this
% function we still want to get actual numbers based on generated XML file
[mNum,lNum] = PPTX.parseMasterLayoutNumber();
% Assign data to slide
PPTX.Slide(PPTX.numSlides).id = PPTX.lastSlideId;
PPTX.Slide(PPTX.numSlides).rId = sprintf('rId%d',PPTX.lastRId);
PPTX.Slide(PPTX.numSlides).file = fileName;
PPTX.Slide(PPTX.numSlides).objId = 1;
PPTX.Slide(PPTX.numSlides).masterNum = mNum;
PPTX.Slide(PPTX.numSlides).layoutNum = lNum;
PPTX.currentSlide = PPTX.numSlides;
currentSlideId = PPTX.currentSlide;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function currentSlide = switchSlide(PPTX,slideId)
% switchSlide(slideId)
%
% Switches current slide to be operated on. Requires slide ID as the second
% input parameter.
%
% Examples:
% % Switch current slide to slide number 2
% pptx.switchSlide(2);
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: slide ID to switch to');
end
% Check slide numbers
if slideId<1 || slideId>PPTX.numSlides || numel(slideId)>1,
% Error condition
error('exportToPPTX:badProperty','switchSlide position must be between 1 and the total number of slides');
end
% Before creating new slide, is there a current slide that needs to be
% saved to XML file?
if isfield(PPTX.XML,'Slide') && ~isempty(PPTX.XML.Slide),
fileName = PPTX.Slide(PPTX.currentSlide).file;
xmlwrite(fullfile(PPTX.tempName,'ppt','slides',fileName),PPTX.XML.Slide);
xmlwrite(fullfile(PPTX.tempName,'ppt','slides','_rels',cat(2,fileName,'.rels')),PPTX.XML.SlideRel);
end
fileRelsPath = cat(2,PPTX.Slide(slideId).file,'.rels');
PPTX.XML.Slide = xmlread(fullfile(PPTX.tempName,'ppt','slides',PPTX.Slide(slideId).file));
PPTX.XML.SlideRel = xmlread(fullfile(PPTX.tempName,'ppt','slides','_rels',fileRelsPath));
allIDs = exportToPPTX.getAllAttribute(PPTX.XML.Slide,'id');
allIDNums = str2num(char(reshape(allIDs,[],1)));
PPTX.Slide(slideId).objId = max(allIDNums);
[mNum,lNum] = PPTX.parseMasterLayoutNumber();
PPTX.Slide(slideId).masterNum = mNum;
PPTX.Slide(slideId).layoutNum = lNum;
PPTX.currentSlide = slideId;
currentSlide = PPTX.currentSlide;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function addPicture(PPTX,imgData,varargin)
% addPicture([figureHandle|axesHandle|imageFilename|CDATA],...)
%
% Adds picture to the current slide. Requires figure or axes handle or image
% filename or CDATA to be supplied. Images supplied as handles or CDATA
% matricies are saved in PNG format. This command does not return any values.
%
% Additional parameters:
% Scale Controls how image is placed on the slide
% noscale - No scaling (place figure as is in the center of
% the slide)
% maxfixed - Max size while preserving aspect ratio (default
% when Position is not set)
% max - Max size with no aspect ratio preservation
% (default when Position is set)
% Position Four element vector: x, y, width, height (in inches) or
% template placeholder ID or name.
% Coordinates x=0, y=0 are in the upper left corner of the slide.
% LineWidth Width of the picture's edge line, a single value (in
% points). Edge is not drawn by default. Unless either
% LineWidth or EdgeColor are specified.
% EdgeColor Color of the picture's edge, a three element vector
% specifying RGB value. Edge is not drawn by default. Unless
% either LineWidth or EdgeColor are specified.
% OnClick Links text to another slide (if slide number is given as
% an integer) or URL or another file
%
% Examples:
% % Add current figure
% figure,plot(rand(10));
% pptx.addPicture(gcf);
%
% % Lower left corner picture inserted via image CDATA (height x width x 3)
% rgb = imread('ngc6543a.jpg');
% pptx.addPicture(rgb,'Position',[1 3.5 3 2]);
% Adding image to existing slide
% 1. Add <p:pic> node to slide#.xml
% 2. Update slide#.xml.rels to link new pic to an image file
%
% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: figure handle or filename or CDATA');
end
mi = false(size(varargin));
[picPositionNew,mi] = exportToPPTX.getPVPair(varargin,'Position',[],mi);
if isempty(picPositionNew)
[scaleOpt,mi] = exportToPPTX.getPVPair(varargin,'Scale','maxfixed',mi);
else
[scaleOpt,mi] = exportToPPTX.getPVPair(varargin,'Scale','max',mi);
end
[lnWNew,mi] = exportToPPTX.getPVPair(varargin,'LineWidth',[],mi);
[lnColNew,mi] = exportToPPTX.getPVPair(varargin,'EdgeColor',[],mi);
[onClick,mi] = exportToPPTX.getPVPair(varargin,'OnClick',[],mi);
if any(~mi)
error('exportToPPTX:badProperty','Unrecognized property %s',varargin{find(~mi,1)});
end
% Defaults
showLn = false;
lnW = 1;
lnCol = [0 0 0];
% Check if media folder exists
if ~exist(fullfile(PPTX.tempName,'ppt','media'),'dir'),
mkdir(fullfile(PPTX.tempName,'ppt','media'));
end
% Set object ID
PPTX.Slide(PPTX.currentSlide).objId = PPTX.Slide(PPTX.currentSlide).objId+1;
objId = PPTX.Slide(PPTX.currentSlide).objId;
% Get screen size (used in a few places)
screenSize = get(0,'ScreenSize');
screenSize = screenSize(1,3:4);
emusPerPx = max(round(PPTX.dimensions.*PPTX.CONST_IN_TO_EMU)./screenSize);
isVideoClass = false;
% Based on the input format, decide what to do about it
if ischar(imgData),
if exist(imgData,'file'),
% Image or video filename
[d,d,inImgExt] = fileparts(imgData);
inImgExt = inImgExt(2:end);
imageName = sprintf('media-%d-%d.%s',PPTX.currentSlide,objId,inImgExt);
imagePath = fullfile(PPTX.tempName,'ppt','media',imageName);
copyfile(imgData,imagePath);
if any(strcmpi({'emf','wmf','eps'},inImgExt)),
% Vector images cannot be loaded by MatLab to determine their
% native sizes, but they can be scaled to any size anyway
imdims = PPTX.dimensions([2 1])./emusPerPx.*PPTX.CONST_IN_TO_EMU;
elseif exist('VideoReader','class') && any(strcmpi(get(VideoReader.getFileFormats,'Extension'),inImgExt)),
% This is a new MatLab style access to video information
% Only format types supported on this system are allowed
% because video has to be read to create a thumbnail image
videoName = imageName;
videoPath = imagePath;
vidinfo = VideoReader(videoPath);
imdims = [vidinfo.Height vidinfo.Width];
% Video gets its own relationship ID
PPTX.Slide(PPTX.currentSlide).objId = PPTX.Slide(PPTX.currentSlide).objId+1;
vidRId = PPTX.Slide(PPTX.currentSlide).objId;
PPTX.Slide(PPTX.currentSlide).objId = PPTX.Slide(PPTX.currentSlide).objId+1;
vidR2Id = PPTX.Slide(PPTX.currentSlide).objId;
% Prepare a thumbnail image
thumbData = read(vidinfo,1);
imageName = sprintf('media-thumb-%d-%d.png',PPTX.currentSlide,objId);
imagePath = fullfile(PPTX.tempName,'ppt','media',imageName);
imwrite(thumbData,imagePath);
clear vidinfo;
isVideoClass = true;
elseif any(strcmpi({'avi'},inImgExt)),
% This is an older MatLab style, which supports only AVI
videoName = imageName;
videoPath = imagePath;
vidinfo = aviinfo(videoPath);
imdims = [vidinfo.Height vidinfo.Width];
% Video gets its own relationship ID
PPTX.Slide(PPTX.currentSlide).objId = PPTX.Slide(PPTX.currentSlide).objId+1;
vidRId = PPTX.Slide(PPTX.currentSlide).objId;
PPTX.Slide(PPTX.currentSlide).objId = PPTX.Slide(PPTX.currentSlide).objId+1;
vidR2Id = PPTX.Slide(PPTX.currentSlide).objId;
% Prepare a thumbnail image
thumbData = aviread(imgData,1);
imageName = sprintf('media-thumb-%d-%d.png',PPTX.currentSlide,objId);
imagePath = fullfile(PPTX.tempName,'ppt','media',imageName);
imwrite(thumbData.cdata,imagePath);
clear vidinfo;
isVideoClass = true;
else
imgCdata = imread(imgData);
imdims = size(imgCdata);
end
else
error('exportToPPTX:fileNotFound','Image file requested to be added to the slide was not found');
end
elseif isnumeric(imgData) && numel(imgData)>1,
% Image CDATA
imageName = sprintf('image-%d-%d.png',PPTX.currentSlide,objId);
imagePath = fullfile(PPTX.tempName,'ppt','media',imageName);
imwrite(imgData,imagePath);
imdims = size(imgData);
inImgExt = 'png';
elseif ishghandle(imgData,'Figure') || ishghandle(imgData,'Axes'),
% Either figure or axes handle
img = getframe(imgData);
imageName = sprintf('image-%d-%d.png',PPTX.currentSlide,objId);
imagePath = fullfile(PPTX.tempName,'ppt','media',imageName);
imwrite(img.cdata,imagePath);
imdims = size(img.cdata);
inImgExt = 'png';
else
% Error condition
error('exportToPPTX:badInput','addPicture command requires a valid figure/axes handle or filename or CDATA');
end
% If XML file does not support this format yet, then add it
if isVideoClass,
if ~any(strcmpi(PPTX.videoTypes,inImgExt)),
PPTX.addVideoTypeSupport(inImgExt);
end
% Make sure PNG (format for video thumbnail image) is supported
if ~any(strcmpi(PPTX.imageTypes,'png')),
PPTX.addImageTypeSupport('png');
end
else
if ~any(strcmpi(PPTX.imageTypes,inImgExt)),
PPTX.addImageTypeSupport(inImgExt);
end
end
% % Save image -- this code would be MUCH faster, but less supported: requires additional MEX file and uses unsupported hardcopy
% % Obtain a copy of fast PNG writing routine: http://www.mathworks.com/matlabcentral/fileexchange/40384
% imageName = sprintf('image%d.png',PPTX.currentSlide);
% imagePath = fullfile(PPTX.tempName,'ppt','media',imageName);
% cdata = hardcopy(figH,'-Dopengl','-r0');
% savepng(cdata,imagePath);
% Figure out picture size in PPTX units (EMUs)
imEMUs = imdims([2 1]).*emusPerPx;
% Check picture position (absolute page position, or placeholder position)
% Adding a picture to a placeholder follows a different procedure than
% textbox. Picture is added into a placeholder, but its postion attributes
% are filled out anyway, but matched to the underlying placeholder size.
picPlaceholder = [];
picPosition = [];
mNum = PPTX.Slide(PPTX.currentSlide).masterNum;
lNum = PPTX.Slide(PPTX.currentSlide).layoutNum;
if ~isempty(picPositionNew)
if ischar(picPositionNew)
% Change placeholder name into placeholder ID
posID = find(strcmp(PPTX.SlideMaster(mNum).Layout(lNum).place,picPositionNew));
if isempty(posID)
posID = find(strncmpi(PPTX.SlideMaster(mNum).Layout(lNum).place,picPositionNew,length(picPositionNew)));
end
if isempty(posID)
% Try search in ph attribute for the name match
posID = find(strcmp(PPTX.SlideMaster(mNum).Layout(lNum).ph,picPositionNew));
end
if isempty(posID)
posID = find(strncmpi(PPTX.SlideMaster(mNum).Layout(lNum).ph,picPositionNew,length(picPositionNew)));
end
if isempty(posID)
warning('exportToPPTX:badName','Placeholder "%s" does not exist in the current layout',picPositionNew);
posID = 1;
end
if numel(posID)>1
warning('exportToPPTX:badName','There are multiple matches for placeholder "%s"',picPositionNew);
posID = posID(1);
end
picPlaceholder = posID;
elseif isnumeric(picPositionNew) && numel(picPositionNew)==1,
if (picPositionNew<1 || picPositionNew>numel(PPTX.SlideMaster(mNum).Layout(lNum).ph)),
error('exportToPPTX:badProperty','Invalid placeholder index');
end
picPlaceholder = picPositionNew;
elseif isnumeric(picPositionNew) && numel(picPositionNew)==4,
picPosition = round(picPositionNew.*PPTX.CONST_IN_TO_EMU);
else
error('exportToPPTX:badProperty','Bad property value found in Position');
end
end
if ~isempty(picPlaceholder),
frameDimensions = PPTX.SlideMaster(mNum).Layout(lNum).position{picPlaceholder};
elseif ~isempty(picPosition)
frameDimensions = picPosition;
else
frameDimensions = [0 0 round(PPTX.dimensions.*PPTX.CONST_IN_TO_EMU)];
end
aspRatioAttrib = {};
switch lower(scaleOpt),
case 'noscale',
picPosition = round([frameDimensions([1 2])+(frameDimensions([3 4])-imEMUs)./2 imEMUs]);
aspRatioAttrib = [aspRatioAttrib {'noChangeAspect','1'}];
case 'maxfixed',
scaleSize = min(frameDimensions([3 4])./imEMUs);
newImEMUs = imEMUs.*scaleSize;
picPosition = round([frameDimensions([1 2])+(frameDimensions([3 4])-newImEMUs)./2 newImEMUs]);
aspRatioAttrib = [aspRatioAttrib {'noChangeAspect','1'}];
case 'max',
picPosition = round(frameDimensions);
otherwise,
error('exportToPPTX:badProperty','Bad property value found in Scale');
end
if ~isempty(lnWNew),
showLn = true;
lnW = lnWNew;
if ~isnumeric(lnW) || numel(lnW)~=1,
error('exportToPPTX:badProperty','Bad property value found in LineWidth');
end
end
if ~isempty(lnColNew),
lnCol = lnColNew;
showLn = true;
if ~isnumeric(lnCol) || numel(lnCol)~=3,
error('exportToPPTX:badProperty','Bad property value found in EdgeColor');
end
end
% Set object name
objName = 'Media File';
if ~isempty(picPlaceholder),
objName = PPTX.SlideMaster(mNum).Layout(lNum).place{picPlaceholder};
end
% Add image/video to slide XML file
picNode = exportToPPTX.addNode(PPTX.XML.Slide,'p:spTree','p:pic');
nvPicPr = exportToPPTX.addNode(PPTX.XML.Slide,picNode,'p:nvPicPr');
cNvPr = exportToPPTX.addNode(PPTX.XML.Slide,nvPicPr,'p:cNvPr',{'id',objId,'name',objName,'descr',imageName});
if isVideoClass,
exportToPPTX.addNode(PPTX.XML.Slide,cNvPr,'a:hlinkClick',{'r:id','','action','ppaction://media'});
end
cNvPicPr = exportToPPTX.addNode(PPTX.XML.Slide,nvPicPr,'p:cNvPicPr');
exportToPPTX.addNode(PPTX.XML.Slide,cNvPicPr,'a:picLocks',aspRatioAttrib);
nvPr = exportToPPTX.addNode(PPTX.XML.Slide,nvPicPr,'p:nvPr');
if ~isempty(picPlaceholder),
allAttribs = {};
if ~isempty(PPTX.SlideMaster(mNum).Layout(lNum).idx{picPlaceholder}),
allAttribs = [allAttribs {'idx',PPTX.SlideMaster(mNum).Layout(lNum).idx{picPlaceholder}}];
end
if ~isempty(PPTX.SlideMaster(mNum).Layout(lNum).ph{picPlaceholder}),
allAttribs = [allAttribs {'type',PPTX.SlideMaster(mNum).Layout(lNum).ph{picPlaceholder}}];
end
exportToPPTX.addNode(PPTX.XML.Slide,nvPr,'p:ph',allAttribs);
end
if isVideoClass,
exportToPPTX.addNode(PPTX.XML.Slide,nvPr,'a:videoFile',{'r:link',sprintf('rId%d',vidRId)});
extLst = exportToPPTX.addNode(PPTX.XML.Slide,nvPr,'p:extLst');
pExt = exportToPPTX.addNode(PPTX.XML.Slide,extLst,'p:ext',{'uri','{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}'});
exportToPPTX.addNode(PPTX.XML.Slide,pExt,'p14:media',{'xmlns:p14','http://schemas.microsoft.com/office/powerpoint/2010/main','r:embed',sprintf('rId%d',vidR2Id)});
end
blipFill = exportToPPTX.addNode(PPTX.XML.Slide,picNode,'p:blipFill');
exportToPPTX.addNode(PPTX.XML.Slide,blipFill,'a:blip',{'r:embed',sprintf('rId%d',objId)','cstate','print'});
stretch = exportToPPTX.addNode(PPTX.XML.Slide,blipFill,'a:stretch');
exportToPPTX.addNode(PPTX.XML.Slide,stretch,'a:fillRect');
spPr = exportToPPTX.addNode(PPTX.XML.Slide,picNode,'p:spPr');
axfm = exportToPPTX.addNode(PPTX.XML.Slide,spPr,'a:xfrm');
exportToPPTX.addNode(PPTX.XML.Slide,axfm,'a:off',{'x',picPosition(1),'y',picPosition(2)});
exportToPPTX.addNode(PPTX.XML.Slide,axfm,'a:ext',{'cx',picPosition(3),'cy',picPosition(4)});
prstGeom = exportToPPTX.addNode(PPTX.XML.Slide,spPr,'a:prstGeom',{'prst','rect'});
exportToPPTX.addNode(PPTX.XML.Slide,prstGeom,'a:avLst');
if showLn,
aLn = exportToPPTX.addNode(PPTX.XML.Slide,spPr,'a:ln',{'w',lnW*PPTX.CONST_PT_TO_EMU});
sFil = exportToPPTX.addNode(PPTX.XML.Slide,aLn,'a:solidFill');
exportToPPTX.addNode(PPTX.XML.Slide,sFil,'a:srgbClr',{'val',sprintf('%s',dec2hex(round(lnCol*255),2).')});
end
% Add slide timing info, node <p:timing>
if isVideoClass,
% TODO: this needs to be added at sometime later...
pTiming = exportToPPTX.addNode(PPTX.XML.Slide,'p:sld','p:timing');
tnLst = exportToPPTX.addNode(PPTX.XML.Slide,pTiming,'p:tnLst');
pPar = exportToPPTX.addNode(PPTX.XML.Slide,tnLst,'p:par');
exportToPPTX.addNode(PPTX.XML.Slide,pPar,'p:cTn',{'id',1,'dur','indefinite','restart','never','nodeType','tmRoot'});
end
% Add image reference to rels file
exportToPPTX.addNode(PPTX.XML.SlideRel,'Relationships','Relationship', ...
{'Id',sprintf('rId%d',objId), ...
'Type','http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', ...
'Target',cat(2,'../media/',imageName)});
if isVideoClass,
exportToPPTX.addNode(PPTX.XML.SlideRel,'Relationships','Relationship', ...
{'Id',sprintf('rId%d',vidRId), ...
'Type','http://schemas.openxmlformats.org/officeDocument/2006/relationships/video', ...
'Target',cat(2,'../media/',videoName)});
exportToPPTX.addNode(PPTX.XML.SlideRel,'Relationships','Relationship', ...
{'Id',sprintf('rId%d',vidR2Id), ...
'Type','http://schemas.microsoft.com/office/2007/relationships/media', ...
'Target',cat(2,'../media/',videoName)});
end
PPTX.addLink(onClick,cNvPr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function addShape(PPTX,xData,yData,varargin)
% addShape(xData,yData,...)
%
% Add lines or closed shapes to the current slide. Requires X and Y data to
% be supplied. This command does not return any values.
%
% Additional parameters:
% ClosedShape Specifies whether the shape is automatically closed or not.
% Default value is false.
% LineWidth Width of the line, a single value (in points). Default line
% width is 1 point. Set LineWidth to zero have no edge drawn.
% LineColor Color of the drawn line, a three element vector specifying
% RGB value. Default color is black.
% LineStyle Style of the drawn line. Default style is a solid line.
% The following styles are available:
% - (solid), : (dotted), -. (dash dot), -- (dashes)
% BackgroundColor Shape fill color, a three element vector specifying
% RGB value. By default shapes are drawn transparent.
%
% Examples:
% % Add lines
% xData = linspace(0,12,101);
% yData = 3+sin(xData*2)*0.3;
% pptx.addShape(xData,yData,'LineWidth',2,'LineStyle',':');
%
% % Add filled circle
% theta = linspace(0,2*pi,101); xData = sin(theta); yData = cos(theta);
% pptx.addShape(xData+4,yData+1,'LineWidth',2,'LineColor','r','LineStyle','--','BackgroundColor','g','ClosedShape',true);
% Adding a line/patch segment (custGeom) to PPTX
% 1. Add <p:sp> node to slide#.xml
%% Inputs
if nargin<3,
error('exportToPPTX:minInput','Two input argument required: X and Y data');
end
mi = false(size(varargin));
[bCol,mi] = exportToPPTX.getPVPair(varargin,'BackgroundColor',[],mi);
[isClosed,mi] = exportToPPTX.getPVPair(varargin,'ClosedShape',false,mi);
[lnWVal,mi] = exportToPPTX.getPVPair(varargin,'LineWidth',[],mi);
[lnColVal,mi] = exportToPPTX.getPVPair(varargin,'LineColor',[],mi);
[lnStyleVal,mi] = exportToPPTX.getPVPair(varargin,'LineStyle',[],mi);
if any(~mi)
error('exportToPPTX:badProperty','Unrecognized property %s',varargin{find(~mi,1)});
end
% Input error checking
if isempty(xData) || isempty(yData),
% Error condition
error('exportToPPTX:badInput','addShape command requires non-empty X and Y data');
end
if size(xData)~=size(yData),
% Error condition
error('exportToPPTX:badInput','addShape command requires X and Y data sizes to match');
end
if numel(xData)==1 || numel(yData)==1,
% Error condition
error('exportToPPTX:badInput','addShape command requires at least two X and Y data point');
end
% If needed, reshape data (dim 1 = segments of a single line, dim 2 = different lines)
if size(xData,1)==1,
xData = reshape(xData,[],1);
yData = reshape(yData,[],1);
end
% Convert to PPTX coordinates
xData = round(xData*PPTX.CONST_IN_TO_EMU);
yData = round(yData*PPTX.CONST_IN_TO_EMU);
% Defaults
showLn = true;
lnW = 1;
lnCol = exportToPPTX.validateColor([0 0 0]);
lnStyle = '';
bCol = exportToPPTX.validateColor(bCol);
if ~isempty(lnWVal),
lnW = lnWVal;
if ~isnumeric(lnW) || numel(lnW)~=1,
error('exportToPPTX:badProperty','Bad property value found in LineWidth');
end
if lnW==0,
showLn = false;
end
end
lnColVal = exportToPPTX.validateColor(lnColVal);
if ~isempty(lnColVal),
lnCol = lnColVal;
end
if ~isempty(lnStyleVal),
switch (lnStyleVal),
case '-',
lnStyle = 'solid';
case ':',
lnStyle = 'sysDot';
case '-.',
lnStyle = 'sysDashDot';
case '--',