LibreOffice Writer Macro - Add Pictures in the right place - image

I have a template file with several pages with text, and I want to make a Macro to add one image per page under the text.
I tried to adapt a script from Andrew Pitonyak, but the result is not as expected, I probably missed something to force a page break.
Sub Main
InsertImage("file1.jpg", 25000, 12158, 3000, 5500)
InsertImage("file2.jpg", 25000, 12158, 3000, 30500)
End Sub
Sub InsertImage(sURL$, sizeW, sizeH, posX, posY)
REM Author: Andrew Pitonyak
Dim oSize As New com.sun.star.awt.Size
Dim oPos As New com.sun.star.awt.Point
Dim oGraph
oDoc = ThisComponent
REM First, create a graphic object shape
oGraph = oDoc.createInstance("com.sun.star.drawing.GraphicObjectShape")
REM Size and place the graphic object.
oSize.width=sizeW
oSize.height=sizeH
oGraph.setSize(oSize)
oPos.X = posX
oPos.Y = posY
oGraph.setposition(oPos)
REM Assuming a text document, add it to the single draw page.
oDoc.getDrawpage().add(oGraph)
REM Set URL to the image.
oGraph.GraphicURL = sURL
End Sub
Here what I
expected
And what is
done
Did anyone can help me to understand how it works ?

Related

VBA download and embed images using url from adjacent cell

I've attempted the solution in the following.
Inserting an Online Picture to Excel with VBA
Unfortunately I get a run-time error '1004'
"Unable to get the Insert property of the Picture class"
which stops on the following code :
Set myPicture = ActiveSheet.Pictures.Insert(pic)
Could this be due to my Office version 2016 (64bit) ?
If not, are there any suggestions of how I might get embed images to adjacent cells in column AK using the image urls from column AJ ?
Thanks in advance
There's some evidence that Excel has trouble downloading from AWS, and I've recreated your issue using the URL you mentioned. In this case, if I were on a deadline I'd put in this fall-back method when the first one fails: download the file, then insert it into the document, then delete the file.
directDownloadFailed:
Dim FileNum As Long
Dim TempFile As String
Dim FileData() As Byte
Dim WHTTP As Object
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
WHTTP.Open "GET", imgURL, False
WHTTP.Send
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
TempFile = "path\to\save\img.jpg"
Open TempFile For Binary Access Write As #FileNum
Put #FileNum, 1, FileData
Close #FileNum
Set img = ActiveSheet.Pictures.Insert(TempFile)
SetAttr TempFile, vbNormal
Kill TempFile
GoTo resumeProcessingImg
#keydemographic
I appreciate the response and that definitely sounds like an option but I cannot get that code to work or incorporate it into the code I'm using. I get a compile error "Label Not defined" on GoTo resumeProcessingImg
The following will download and embed the images into the cells but the code stops once it gets to the s3 aws image urls.
I'll try a few other ways to incorporate your code but I'm not having much luck with it so far.
This is my test file
Sub URL2IMG()
Dim pic As String 'path of pic
Dim myPicture As Picture 'embedded pic
Dim rng As Range 'range over which we will iterate
Dim cl As Range 'iterator
Set rng = Range("b2:b12") '<~~ as needed, Modify range to where the images are to be embedded.
For Each cl In rng
pic = cl.Offset(0, -1) '<~~ defines image link URL in column to the left of the embedded column
Set myPicture = ActiveSheet.Pictures.Insert(pic)
'you can play with the following to manipulate the size & position of the picture.
With myPicture
.ShapeRange.LockAspectRatio = msoFalse
' currently this shrinks the picture to fit inside the cell.
.Width = cl.Width
.Height = cl.Height
.Top = Rows(cl.Row).Top
.Left = Columns(cl.Column).Left
End With
Next
End Sub

How should I copy and paste a powerpoint slide KEEPING SOURCE FORMATTING with VBScript?

I'm trying to write a subroutine that will copy and paste all (and later only some) of the slides from a powerpoint file to another keeping source formatting.
This is the closest I have gotten:
Dim objPowerpointApp, objPresentations
Set objPowerpointApp = CreateObject("Powerpoint.Application")
Set objPresentations = objPowerpointApp.Presentations
Dim objNewPresentation
Set objNewPresentation = objPresentations.Open(strTemplateFile, 0, 0, -1)
Dim objOldPresentation : Set objOldPresentation = objPresentations.Open(tempSlideSet.Path, 0, 0, 0)
Dim tempCurrentSlide
For Each tempCurrentSlide in objOldPresentation.Slides
tempCurrentSlide.Copy
objNewPresentation.Application.CommandBars.ExecuteMso("PasteSourceFormatting")
Next
It throws no errors and even pastes the correct slide masters, but it doesn't actually paste any of the slides.
I've also tried this:
Dim objPowerpointApp, objPresentations
Set objPowerpointApp = CreateObject("Powerpoint.Application")
Set objPresentations = objPowerpointApp.Presentations
Dim objNewPresentation
Set objNewPresentation = objPresentations.Open(strTemplateFile, 0, 0, -1)
Dim objOldPresentation : Set objOldPresentation = objPresentations.Open(tempSlideSet.Path, 0, 0, 0)
Dim tempCurrentSlide
For Each tempCurrentSlide in objOldPresentation.Slides
tempCurrentSlide.Copy
objNewPresentation.Slides.Paste
objNewPresentation.Application.CommandBars.ExecuteMso("PasteSourceFormatting")
Next
Which pastes the correct slide master as well as the slide, but the slide is pasted with the destination formatting.
Naturally, this pastes all the slides correctly, but without any of the source formatting:
Dim objPowerpointApp, objPresentations
Set objPowerpointApp = CreateObject("Powerpoint.Application")
Set objPresentations = objPowerpointApp.Presentations
Dim objNewPresentation
Set objNewPresentation = objPresentations.Open(strTemplateFile, 0, 0, -1)
Dim objOldPresentation : Set objOldPresentation = objPresentations.Open(tempSlideSet.Path, 0, 0, 0)
Dim tempCurrentSlide, lngSlideIndex
For Each tempCurrentSlide in objOldPresentation.Slides
lngSlideIndex = objNewPresentation.Slides.Count
objNewPresentation.Slides.InsertFromFile tempSlideSet.Path, lngSlideIndex
Next
From what I can find in documentation and others' experience, the first option should work as I need, so I really am stuck at this point.
How can I copy and paste a powerpoint slide using VBScript and keep its source formatting??
To anyone struggling with the same issue, here is the subroutine that I managed to create. The objDestPresentation should be a Presentation Object and the sourceSlideRange should be a SlideRange Object.
This will copy the slides from sourceSlideRange to the end of the objDestPresentation. Hopefully this will save someone some of the struggle that I went through!
Private Sub InsertSlide_Source(ByRef objDestPresentation, byVal sourceSlideRange)
sourceSlideRange.Copy
If Not objDestPresentation.Slides.Count = 0 Then
objDestPresentation.Windows(1).View.GotoSlide(objDestPresentation.Slides.Count)
End If
objDestPresentation.Application.CommandBars.ExecuteMso("PasteSourceFormatting")
End Sub
This helped me resolve a long-term frustration with PowerPoint. Thank you so much for posting this. A nuance I found is was important to activate the presentation I wanted to affect before pasting, otherwise the slide could end up in the wrong place. In my case I'm juggling things between three different presentations:
I start out with an empty shell presentation that I then populate
I have a "blank slide" template that I'm using for most of the slides.
I also sometimes have other one-off slides that I need to include.
With regard to activating the proper presentation I used the answer from here:
http://answers.microsoft.com/en-us/msoffice/forum/msoffice_powerpoint-msoffice_custom/powerpoint-vba-making-right-window-active/32c9fa95-fa1d-46f8-912a-09771a63a27a
Code
You first need to Activate the Window of the target slidedeck before pasting with the "PasteSourceFormatting" option
when TargetPPT is the destination presentation in VBA, and if I want to copy all slides of SourcePPT:
SourcePPT.Slides.Range.Copy
TargetPPT.Windows(1).Activate
TargetPPT.Application.CommandBars.ExecuteMso ("PasteSourceFormatting")
The slides are pasted at the current active slide
Use
Application.ActiveWindow.View.GotoSlide (5)
to position f.i. on slide 5 first, and paste the new slides after slide 5.

Is there a way to read images from a folder and save it in powerpoint

I have approx. 100 images , I want to read those images, do the resizing and save it in a power point using matlab, Is it way to save those images in a power point giving title to each slide.
I am reading images using this code:
for i = 1:numel(pngfiles)
im{i} = imread(pngfiles{i});
imrgb{i} = rgb2gray(im{i});
imrgb_z{i} = imrgb{i}(160:350,280:450);
end
It seems to me that the best approach would be to use a VBA script inside Powerpoint, rather than manipulating ppt from Matlab. The steps would be
Create your list of images in a folder - using a sensible naming scheme
Open Powerpoint; go to the VBA editor (Alt-F11) and add a module with the following lines of code in it (note - this is taken straight from https://stackoverflow.com/a/5038907/1967396 with minimal edits):
-
Sub CreatePictureSlideshow( )
Dim presentation
Dim layout
Dim slide
Dim FSO
Dim folder
Dim file
Dim folderName
Dim fileType
' Set this to point at the folder you wish to import JPGs from
' Note: make sure this ends with a backslash \
fileType = ".jpg" ' <<< change this to the type you want
folderName = "c:\somedirectory\" ' <<< change this to the directory you want
' setup variables
Set presentation = Application.ActivePresentation
' choose the layout you want: e.g. if the title needs a particular format
Set layout = Application.ActivePresentation.SlideMaster.CustomLayouts(1)
Set FSO = CreateObject("Scripting.FileSystemObject")
' Retrieve the folder's file listing and process each file
Set folder = FSO.GetFolder(folderName)
For Each file In folder.Files
' Filter to only process JPG images
If LCase(Right(file.Name), 4)) = fileType Then
' Create the new slide and delete any pre-existing contents
Set slide = presentation.Slides.AddSlide(presentation.Slides.count + 1, layout)
While slide.Shapes.count > 0
slide.Shapes(1).Delete ' <<< You might not want to do this is you want to keep the title placeholder
Wend
' Add the picture
slide.Shapes.AddPicture folderName + file.Name, False, True, 10, 10
' Optional: create a textbox with the filename on the slide for reference
' alternatively, add text to the title shape
Dim textBox
Set textBox = slide.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 10, 200, 200)
textBox.TextFrame.TextRange.Text = file.Name ' <<< or whatever "title" you wanted
End If
Next
End Sub
You can modify this further to get the title in the format you want, etc.
you could try this:
Is there an example of using MATLAB to create PowerPoint slides?
For example:
% before the following, you have to create the ppt as explained, see link above!
% I prefer using some name instead of i or j
for img_ind = 1:numel(pngfiles)
% this depends on the ppt-version (see link above)-> here for 2007 and higher
mySlide = Presentation.Slides.Add(1,'ppLayoutBlank')
% Note: Change the image file full path names to where you save them
Image1 = mySlide.Shapes.AddPicture('<full path>\name_of_image(img_ind).png','msoFalse','msoTrue',100,20,500,500)
end
% then you have to save it, see link above!
In your case, I guess you have to save the image first as shown in the example:
print('-dpng','-r150','<full path>\test1.png')
edit
This will only work when using Matlab on Windows, because COM is needed. See comments on Floris answer!
Coming late to this party: Here's a "Matlab Pick of the Week" tool:
http://www.mathworks.com/matlabcentral/fileexchange/30124-smart-powerpoint-exporter
Take note of some of the comments at that page, as apparently the tool has not been updated in a few years.

Partition powerpoint lines into different objects

I have many power point slides and each slide has many lines but all those lines are in the same objects. I want now to add some animation including appears for each line with click.
How I can partition the lines in each slide such that every line will be in its own object
Note, I am using powerpoint 2010
Thanks,
AA
This isn't perfect; you'll need to add more code to pick up ALL of the formatting from the original text, but it's a start. Click within the text box you want to modify, then run the TEST sub. Once it's adjusted to your taste, it's a fairly simple matter to extend it to act on every text box in the entire presentation (though not tables, charts, smartart, stuff like that)
Sub Test()
TextBoxToLines ActiveWindow.Selection.ShapeRange(1)
End Sub
Sub TextBoxToLines(oSh As Shape)
Dim oSl As Slide
Dim oNewShape As Shape
Dim oRng As TextRange
Dim x As Long
With oSh
Set oSl = .Parent
With .TextFrame.TextRange
For x = 1 To .Paragraphs.Count
Set oRng = .Paragraphs(x)
Set oNewShape = oSl.Shapes.AddTextbox(msoTextOrientationHorizontal, _
oRng.BoundLeft, oRng.BoundTop, oRng.BoundWidth, oRng.BoundHeight)
With oNewShape
.TextFrame.AutoSize = ppAutoSizeNone
.Left = oRng.BoundLeft
.Top = oRng.BoundTop
.Width = oSh.Width
.Height = oSh.Height
With .TextFrame.TextRange
.Text = oRng.Text
.Font.Name = oRng.Font.Name
.Font.Size = oRng.Font.Size
' etc ... pick up any other font formatting you need
' from oRng, which represents the current paragraph of
' the original text
' Bullets, tabs, etc.
End With
End With
Next
End With
End With
oSh.Delete
End Sub

Is there an Alternative to using the LoadPicture("bmp_or_icon_file_path") to loading Images in Excel 2007 VBA

I have an Excel 2007 Worksheet with many buttons and labels that act as menu options (i.e. user clicks the buttons, labels with images) and is presented with forms, or some thing else.
These images / icons for the buttons and labels are loaded in VBA by assigning the Picture property of the Control and calling LoadPicture() method with the full image file path as parameter, like So.
With SomeFormObject
.cmdOpenFile.Picture = LoadPicture("F:\projectname\images\fileopen.BMP")
End With
This method of loading images for buttons, other controls is causing 2 issues.
1) It creates a dependency on the image files and physical location for every user, so if a user does not have the drive mapped and files present, the VBA fails with runtime error of file or path not found.
2)
The app gets very slow if the images are on a shared drive (which is the case)
I want to eliminate both issues and somehow load icons, images into control internally, without any external dependencies on external image files.
What is the best way to achieve this in Excel 2007 VBA?
I could not file any Visual Basic 6.0 / Visual Studio style "Resource File Editor" / feature with which to accomplish this.
Please advice! thank you
-Shiva #
mycodetrip.com
I really hope that there is a easier way to do this, but this is the only one I found:
The Idea is:
You keep the Pictures embedded in a Sheet and every time you want to set the pictures for the Command you export them from your worksheet to a file and load them through LoadPicture. The only way to export an embedded Picture through VBA that I found is by making it a Chart first.
The following code is based on 'Export pictures from Excel' from johnske
Option Explicit
Sub setAllPictures()
setPicture "Picture 18", "CommandButtonOpen"
setPicture "Picture 3", "CommandButtonClose"
End Sub
Sub setPicture(pictureName As String, commandName As String)
Dim pictureSheet As Worksheet
Dim targetSheet As Worksheet
Dim embeddedPicture As Picture
Dim pictureChart As Chart
Dim MyPicture As String
Dim PicWidth As Long
Dim PicHeight As Long
Set pictureSheet = Sheets("NameOfYourPictureSheet") ' <- to Change '
Set targetSheet = Sheets("NameOfYourSheet") ' <- to Change '
Set embeddedPicture = pictureSheet.Shapes(pictureName).OLEFormat.Object
With embeddedPicture
MyPicture = .Name
PicHeight = .ShapeRange.Height
PicWidth = .ShapeRange.Width
End With
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=pictureSheet.Name
Set pictureChart = ActiveChart
embeddedPicture.Border.LineStyle = 0
With pictureChart.Parent
.Width = PicWidth
.Height = PicHeight
End With
With pictureSheet
.Select
.Shapes(MyPicture).Copy
With pictureChart
.ChartArea.Select
.Paste
End With
.ChartObjects(1).Chart.Export Filename:="temp.jpg", FilterName:="jpg"
End With
pictureChart.Parent.Delete
Application.ScreenUpdating = True
targetSheet.Shapes(commandName).OLEFormat.Object.Object.Picture = LoadPicture("temp.jpg")
Set pictureChart = Nothing
Set embeddedPicture = Nothing
Set targetSheet = Nothing
Set pictureSheet = Nothing
End Sub
Sub listPictures()
' Helper Function to get the Names of the Picture-Shapes '
Dim pictureSheet As Worksheet
Dim sheetShape As Shape
Set pictureSheet = Sheets("NameOfYourSheet")
For Each sheetShape In pictureSheet.Shapes
If Left(sheetShape.Name, 7) = "Picture" Then Debug.Print sheetShape.Name
Next sheetShape
Set sheetShape = Nothing
Set pictureSheet = Nothing
End Sub
To Conclude:
Loading the Images from a Mapped Networked Drive seems less messy, and there shouldn't be that much of a speed difference.
2 alternatives i can think of: form.img.picture=pastepicture , and = oleobjects("ActiveXPictureName").object.picture.

Resources