HTML Image to Notes

Can someone help me here please. I am trying to transfer a number of images from a folder into a newly created Notes document using AppleScript and html. I think the problem is something to do with my file path but I can’t work out what is wrong.
The following code produces a new note with the correct text but no picture.

(Notes is already configured for images)

Thanks

-- Send the result to Notes
tell application "Notes"
	set the chosenBackgroundColorAsHTML to "#FFFFFF" -- White	
	set the chosenFontColorAsHTML to "#21FF06" -- Green
	set the AltFontColorAsHTML to "#000000" -- Black
	
	set the noteBody to "<html>
<head>
<style type=\"text/css\">
div.background{background-color:" & chosenBackgroundColorAsHTML & ";margin:0;height:100%;width:100%;position:absolute;top:0;left:0;z-index:-1;-webkit-user-select:none;}
ol, ul, li{color:" & AltFontColorAsHTML & "}
</style>
</head>
<body style=\"color:" & AltFontColorAsHTML & ";margin:0;padding:24px;\">
<p> <span style=\"color:#FF0000\">Building Picture: </span>
<p><img src=\"/Users/MyName/Images/Image_001.jpg\">
<p>
</body>
</html>"

Personally, I prefer to leave the task of “embedding” an image or PDF to the application itself.

And providing the text for the title and body of the note as HTML is a good way to provide rich text for me too. Such HTML for personal notes can, for example, be borrowed from beautifully organized web pages.


-- script: Create new note with embedded image 
-- written: by KniazidisR, right now

set theImage to choose file of type "public.image"

set backgroundColor to "white"
set titleFontColor to "green"
set messageFontColor to "red"
set title to "Building Picture"
set message to "New image added"

set |note body| to "
	<body>
         <h1 style=\"color:" & titleFontColor & ";background-color:" & backgroundColor & ";font-family:Helvetica,sans-serif;font-size:18;bold:false\">" & title & "</h1> 
         <p style=\"color:" & messageFontColor & ";background-color:" & backgroundColor & ";font-family:Helvetica,sans-serif;font-size:24;bold:false;\" >" & message & "</p>
      </body>"

tell application "Notes"
	tell account "On My Mac" to tell folder "Notes"
		-- make new note
		set theNote to make new note with properties {body:|note body|}
		-- get its id
		try
			set theID to id of theNote -- UPDATED
		on error errorMessage
			set ATID to AppleScript's text item delimiters
			set AppleScript's text item delimiters to "\""
			set theID to text item 2 of errorMessage
			set AppleScript's text item delimiters to ATID
		end try
		-- embed the picture
		make new attachment at end of attachments of note id theID with data theImage
	end tell
	save
end tell

.
.
Adding clickable reference to some file is other task. In this case I use the code like following. Note that I use https:// reference in my example, but the user can use other-form references as well (like file://, mailto:// and so on).


-- script: create note with clickable reference
-- written: by me, in the past

set urlText to "επικοινωνήσετε"
set urlDescription to "Επικοινωνία"
set theURL to "https://macscripter.net/viewtopic.php?id=48007"
set noteTitle to "Test: Add clickable link to note"
set noteHTMLText to "<pre style=\"font-family:Helvetica,sans-serif;\">" & ¬
	"<a target=\"_blank\" href=" & theURL & ¬
	" data-linkname=" & urlDescription & " data-tag=\"GEN\" title=" & urlDescription & ¬
	" style=\"font-size: inherit; font-family: inherit; line-height: inherit;\">" & ¬
	urlText & "</a>" & ¬
	"</pre>"

tell application "Notes" to tell account (name of account 1)
	make new note at folder "Notes" with properties {name:noteTitle, body:noteHTMLText}
end tell

Thanks for this. I tried the script but got an error:

in the following line

	make new attachment at end of attachments of note id theID with data theImage

any ideas please?

Replace the code line id of theNote with set theID to id of theNote. I updated the script above. The error processing is due to the fact that on some systems (like mine, the Catalina) the direct way (set theID to id of theNote) doesn’t work fore some reason. It is most likely Notes.app bug.

If that doesn’t work again, then you need to see what the errorMessage variable contains. The whole point of the try block is that you must somehow get the note ID - in a normal way, or - in an indirect way (i.e. by parsing the error message)

Also, providing information about your personal computer’s OS on this site is important, because there will always be experienced users (with the same OS as yours) who can help with specific problems.

Thanks, that’s now working fine and I can get a single picture into the Notes file.

I don’t want to have to manually pick the picture, so I replaced the “choose file” command with the actual file reference…

set theImage to "Macintosh HD:Users:My Name:Images:Image_000.jpg"

…which works fine.

There will be a random number of images to be transferred (normally between 1 and 12). I was hoping that I could link the Images together like this…

set theImage to "Macintosh HD:Users:My Name:Images:Image_000.jpg" & return & "Macintosh HD:Users:My Name:Images:Image_001.jpg"

…but that doesn’t work.

Is it possible to get multiple Images please?

PS - Added the system info

You can use repeat loop to embed them one by one:


-- script: Create new note with embedded images

set theImages to {alias "Macintosh HD:Users:My Name:Images:Image_000.jpg", alias "Macintosh HD:Users:My Name:Images:Image_001.jpg"}

set backgroundColor to "white"
set titleFontColor to "green"
set messageFontColor to "red"
set title to "Building Picture"
set message to "New image added"

set |note body| to "
   <body>
<h1 style=\"color:" & titleFontColor & ";background-color:" & backgroundColor & ";font-family:Helvetica,sans-serif;font-size:18;bold:false\">" & title & "</h1> 
<p style=\"color:" & messageFontColor & ";background-color:" & backgroundColor & ";font-family:Helvetica,sans-serif;font-size:24;bold:false;\" >" & message & "</p>
</body>"

tell application "Notes"
	tell account "On My Mac" to tell folder "Notes"
		-- make new note
		set theNote to make new note with properties {body:|note body|}
		-- get its id
		try
			set theID to id of theNote -- UPDATED
		on error errorMessage
			set ATID to AppleScript's text item delimiters
			set AppleScript's text item delimiters to "\""
			set theID to text item 2 of errorMessage
			set AppleScript's text item delimiters to ATID
		end try
		repeat with aListReference in theImages
			-- embed the picture
			make new attachment at end of attachments of note id theID with data (contents of aListReference)
		end repeat
	end tell
	save
end tell

Many thanks for your help with this. I am now able to get more than one image into the Notes document. Thanks.

Now, here is the problem! Long story short but with a great deal of help from members on this site, I wrote a script that interacted with a secure webpage (I have to sign in). Using the info from the webpage the script produced a new Notes document in the following format:

Text…

Image (front of building)

Text…

A collection of images (Observations from the inspection) with a white space gap between them. (Image Return Image Return Image)… and so on for the number of images in the report.

This is why I was using html. The relevant images and text were in variables that sat in fixed positions within the html - perfect.

This was working really well until the Company changed the format of their website:( I knew that I would have to tweak my code to make it work again and I have done that for the text but I just can’t get the images to work again.

As a temporary work around, I have a script that finds the images on the webpage and copies them to a directory on my Mac. I was hoping that I could use those saved images within my html to get me back up and running again - but I can’t understand how to do that (hence my first question about adding saved images to html within AppleScript).

Sorry for the long post, but I really am stuck here…

-- Images not working  
-- The first attempt via variable is ignored
-- The second attempt via direct coding just produces the 'alt' text

set BuildingPicture to "Macintosh HD:Users:MyName:Images:Front.jpg"

-- Send the result to Notes
tell application "Notes"
	set the chosenBackgroundColorAsHTML to "#FFFFFF" -- White	
	set the chosenFontColorAsHTML to "#21FF06" -- Green
	set the AltFontColorAsHTML to "#000000" -- Black
	
	set the noteBody to "<html>
<head>
<style type=\"text/css\">
div.background{background-color:" & chosenBackgroundColorAsHTML & ";margin:0;height:100%;width:100%;position:absolute;top:0;left:0;z-index:-1;-webkit-user-select:none;}
ol, ul, li{color:" & AltFontColorAsHTML & "}
</style>
</head>
<body style=\"color:" & AltFontColorAsHTML & ";margin:0;padding:24px;\">
<p> <span style=\"color:#FF0000\">Building Picture: <p></span>
<img src=\" & buildingpicture 
<img src=\"Macintosh HD:Users:MyName:Images:Front.jpg\" alt=\"Front of the building\"/>
</body>
</html>"
	
	set thisAccountName to "My Name" -- For testing (images appear immediately)
	--set thisAccountName to "Icloud"
	
	-- make a new note at the top application-level:
	make new note at folder "Notes" of account thisAccountName with properties {body:noteBody}
end tell
noteBody

There is a strong suspicion that embedding an image in HTML text won’t help. I’ve been digging into the secrets of Notes.app before, and I know that a nested in its bundle HTML Converter helper application is responsible for handling the HTMLs. The internals and principles of this HTML converter, at least for me, are a big mystery.

I strained for the last time and tried the simplest code:


set BuildingPicture to "/Users/123/Desktop/TESTfiles/cameringo20160514150918copy.png"

tell application "Notes"
	set the noteBody to "<img src=3D" & quote & BuildingPicture & quote & " alt=3D" & quote & "Front of the building" & quote & ">"
	make new note at folder "Notes" of account "On My Mac" with properties {body:noteBody}
	save
end tell

Pay attention: the viewer tells us that an attacment (1 attacment) was found in the note, that is, the attacment was added possibly correctly, it stubbornly refuses to show it …

Try specifying that the image is a ‘file’ (url scheme). And use a posix file type of URL for the image.

Normally, there is an ‘http’ or ‘https’ involved in the image URL — even if it’s not included in the html, it’s implicit (i.e. there is a web server that is serving the file). That isn’t the case here so results are often weird and unsatisfactory. I’m not sure whether they’re defined or not.

So if it’s a local file, try prefacing it with ‘file://’ (with the third ‘/’ being the opening slash of the file specification). I imagine that the Notes app is a strange beast (as KniazidisR suggests) and who knows exactly how it handles the url without the ‘file’.

Separately, on the line beginning with ‘

<span’, move the second

outside of the span tags.

Also, ‘background’ isn’t a tag. The note’s background is an attribute of the ‘body’ tag. ‘Body’ represents the canvas of the page so you don’t need to have any dimensional styles for it. I think that the only valid attribute is ‘background-color’ but whatever styles you want to add, do so to the body tag in the styles, for example:

[format]body {background-color:#F3FFEE;}[/format]

Thank, Fredrik71,

Very cool. Your script works. It works multiple times as well, but need save command and restarting Notes.app:


use framework "Foundation"
use scripting additions

set imageAlias to choose file of type "png"
tell application "System Events" to set theImageURL to URL of file (imageAlias as text)

set theURL to current application's |NSURL|'s URLWithString:theImageURL
set theData to current application's NSData's dataWithContentsOfURL:theURL
set base64 to theData's base64EncodedDataWithOptions:(current application's NSDataBase64EncodingEndLineWithLineFeed)
set theString to current application's NSString's alloc()'s initWithData:base64 encoding:(current application's NSUTF8StringEncoding)

set theStart to "<div><img style=\"max-width: 100%; max-height: 100%;\" src=\"data:image/png;base64,"
set theEnd to "\"/><br></div>"
set theBody to theStart & theString & theEnd

tell application "Notes"
	tell account "On My Mac" to tell folder "Notes" to set theBody to make new note at end with properties {body:theBody}
	save
	quit
	repeat while running
		delay 0.2
	end repeat
	activate
end tell

I’m afraid that’s just more raw data than I can cope with :slight_smile:

FWIW, I can’t help wonder if it wouldn’t make things sluggish with large images. When I scroll down this page, the browser chokes part of the way through. Is there zero effect on the notes? Dunno.

Here would be my attempt. I have it set to use ‘choose file’ but it’s easy enough to set it to any image alias. I included the ‘set bodynn’ to see what Notes transforms the input into.

Unfortunately, I wasn’t able to get it to accept multiple images. For whatever reason, the script wouldn’t relinquish the backslash before each quote. So the html would be valid and the note would accept a ‘caption’ for each image but only the first image would be attached. I tried appending the rest of the images but to no avail.

Not sure how to get around the backslash thing as I thought it would be handled automatically but it wasn’t. Whenever I attempted to search/replace the backslashes, either the text would suddenly not have them anymore or it would error out. Anyway, here is the script with a single image.

-- set bgColor to "#EFFFEF;" -- pale green
set chosenFontColorHex to "#14B900;" -- green
set altFontColorHex to "#0014B9;" -- blue
set captionColorHex to "#b90014;" -- red

set noteHead to "<html>
<head>
<style type=\"text/css\">
p{color:" & chosenFontColorHex & "}
.desc{color:" & captionColorHex & "}
.blue{color:" & altFontColorHex & "}
</style>
</head>
"

set imgFile to choose file of type "public.image"
set imgFileString to "<div><p class=\"desc\">Building Picture 1 (caption)</p><img src=\"file://" & POSIX path of imgFile & "\" alt=\"building\"><br></div>"

set noteBody to "
<body>
<div><p>This is yet another note with images. (chosen)</p><br></div>
" & imgFileString & "
<div><p class=\"blue\">And this is some more text, formatted as the 'alt' colour. (alt)</p></div>
</body>
</html>
"

set note2 to noteHead & noteBody
set the clipboard to note2 as text
tell application "Notes"
	set nn to make new note at folder "Notes" with properties {name:"Is this new? (name)", body:note2}
	set bodynn to body of nn
end tell

Looks like a lot of the formatting is simply dropped, for example the background colour. Maybe I need to strip out the ‘class’ attributes and start again.

@Mockman, your last script doesn’t generate any image in the note for me. Maybe, @Fredrik71 is right and Notes.app accepts only base64-encoded images. For those who want create the note with chosen multiple images (photos), here is adapted @Fredrik71 script with choosing multiple images on the local disk:

AsObjC solution:


use framework "Foundation"
use scripting additions

set imageAliases to (choose file of type "public.image" with multiple selections allowed) as list
set theStart to "<div><img style=\"max-width: 100%; max-height: 100%;\" src=\"data:image/png;base64,"
set theEnd to "\"/><br></div>"

set theBody to ""
repeat with imageAlias in imageAliases
	tell application "System Events" to set theImageURL to URL of file (imageAlias as text)
	set base64String to imageAsBase64String(theImageURL)
	set theBody to theBody & theStart & base64String & theEnd
end repeat

tell application "Notes"
	tell account "On My Mac" to tell folder "Notes"
		make new note at end with properties {body:theBody}
	end tell
	save
end tell
seeTheChangesTookPlace() -- optional


on imageAsBase64String(theImageURL)
	set theURL to (current application's |NSURL|'s URLWithString:theImageURL)
	set theData to (current application's NSData's dataWithContentsOfURL:theURL)
	set base64 to (theData's base64EncodedDataWithOptions:(current application's NSDataBase64EncodingEndLineWithLineFeed))
	return (current application's NSString's alloc()'s initWithData:base64 encoding:(current application's NSUTF8StringEncoding))
end imageAsBase64String


on seeTheChangesTookPlace() -- optional
	tell application "Notes"
		quit
		repeat while running
			delay 0.2
		end repeat
		activate
	end tell
end seeTheChangesTookPlace

.
.
The same using plain AppleScript instead of AsObjC:


set imageAliases to (choose file of type "public.image" with multiple selections allowed) as list
set theStart to "<div><img style=\"max-width: 100%; max-height: 100%;\" src=\"data:image/png;base64,"
set theEnd to "\"/><br></div>"

set theBody to ""
repeat with imageAlias in imageAliases
	set base64String to imageAsBase64String(contents of imageAlias)
	set theBody to theBody & theStart & base64String & theEnd
end repeat

tell application "Notes"
	tell account "On My Mac" to tell folder "Notes"
		make new note at end with properties {body:theBody}
	end tell
	save
end tell
seeTheChangesTookPlace() -- optional


on imageAsBase64String(imagePath) -- hfs path or alias as parameter
	do shell script "openssl base64 -in " & quoted form of POSIX path of imagePath
end imageAsBase64String


on seeTheChangesTookPlace() -- optional
	tell application "Notes"
		quit
		repeat while running
			delay 0.2
		end repeat
		activate
	end tell
end seeTheChangesTookPlace

@KniazidisR Weird, and frustrating. Thanks for trying it out.

How about this?

set imgFile to choose file

tell application "Notes"
	set n1 to make new note at folder "Notes" with properties {name:"Note name", body:"Note body"}
	
	make new attachment at n1 with data imgFile
end tell

Or, for multiples…

set imgList to choose file with multiple selections allowed
tell application "Notes"
	set n1 to make new note at folder "Notes" with properties {name:"Note name", body:"Note body"}
	
	delay 1
	repeat with i in imgList
		make new attachment at n1 with data i
	end repeat
end tell

This doesn’t work for me for 2 reasons : 1) on Catalina make new note command doesn’t return the reference to note, but weird property list item object. I think, this is bug. 2) the body should be HTML and you provide plain TEXT, which works for text creating but doesn’t allow adding attachment to note further…

See my post @2 how it works. The weird property list item object returned by make new note command, has the same ID with correct note , so I retrieve this ID with error parsing to refer to note by this ID. The body I provide, is HTML, so I can make attachment further.

As the OP, I would like to thank all contributors - I am making slow progress in getting my script to work again. This has been useful,
Thanks.