Save chosen folder's PDFs short metadata Info as .txt file

The basic script to perform this task is written by user @StefanK.
Here: List pdf names with number of pages and security state: how?

I only refined it little for my needs and for other users.


set baseFolder to (choose folder) as text
tell application "System Events" to tell (folder baseFolder) to ¬
	set {folderName, posixPaths} to {name, POSIX path of files whose type identifier is "com.adobe.pdf"}
set targetFile to (path to desktop folder as text) & "PDFMetaData for " & folderName & ".txt"

PDFMetadataInfoAsTextFile(baseFolder, targetFile)

on PDFMetadataInfoAsTextFile(sourceFolderHFS, targetTextFileHFS)
	tell application "System Events" to set posixPaths to ¬
		POSIX path of files of folder sourceFolderHFS whose type identifier is "com.adobe.pdf"
	if posixPaths is {} then return
	set ATID to AppleScript's text item delimiters
	try
		set dataStream to open for access file targetTextFileHFS with write permission
		set eof of dataStream to 0
		repeat with posixPath in posixPaths
			set theData to do shell script "mdls " & quoted form of posixPath & " | grep '" & ¬
"_kMDItemDisplayNameWithExtensions\\|kMDItemNumberOfPages\\|kMDItemSecurityMethod'"
			set AppleScript's text item delimiters to {"_kmdItem", "kmdItem"}
			set {theData, AppleScript's text item delimiters} to {text items of theData, ""}
			set theData to theData as text
			write (theData & linefeed & linefeed) to dataStream
		end repeat
		close access dataStream
	on error
		try
			close access file targetFile
		end try
	end try
	set AppleScript's text item delimiters to ATID
end PDFMetadataInfoAsTextFile