Использование Automator или Applescript или и того, и другого для рекурсивной печати документов в PDF - PullRequest
1 голос
/ 22 марта 2012

У меня есть огромный набор файлов (4000+) в старом формате Apple (Appleworks).Мои работники нуждаются в их обновлении в PDF.Открывая документы в Appleworks и используя системный диалог печати, я могу сохранить их в PDF - это идеально.Тем не менее, я полный нюх с Applescript / Automator.

Используя скрипт Python, я смог собрать все файлы Appleworks со своего компьютера боссов и поместить их в каталог;затем каждый файл находится в подкаталоге с файлом .txt, содержащим его исходное местоположение (куда, в конце концов, мне придется их вернуть).

Мне нужен скрипт для рекурсивного перемещения по этому массивному каталогу, получая каждыйфайл, который не является ни папкой, ни документом .txt, и сохраните его в формате PDF в том же каталоге, в котором был найден исходный файл .т. е.

/Appleworks/Boss_File_1/

будет содержать

/Appleworks/Boss_File_1/Boss_file_1.cwk и /Appleworks/Boss_File_1/path.txt

Но в конечном итоге также должно содержать /Appleworks/Boss_File_1/Boss_File_1.pdf

Я могу пройти половину пути с любым решением, но не знаю, как заставить их работать вместе.Я использую Applescript выглядит следующим образом:

set appleworksFolder to choose folder

tell application "Finder"
set folderItems to (files of entire contents of appleworksFolder)
repeat with I from 1 to number of items in folderItems
    set the_doc to item I of folderItems
    if name of the_doc is not "path.txt" then
        try
            tell application "AppleWorks 6"
                open the_doc
                tell application "System Events"
                    tell process "Appleworks"
                        keystroke "p" using command down
                        click menu button "PDF" of window "Print"
                        click menu item "Save as PDF…" of menu 1 of menu button "PDF" of window "Print"
                        click button "Save" of window "Save"

                    end tell
                end tell
            end tell
        end try
    else
        tell application "Finder"
            delete the_doc
        end tell
    end if
end repeat

end tell`

Это открывает диалог печати, но никогда не идет дальше, и я понятия не имею, почему.Я понимаю, что этот сценарий также не предназначен для помещения документа обратно в его исходную папку, но в Applescript я мог бы достаточно легко сделать это, если бы смог преодолеть фактический бит печати в PDF.

Между тем,в Automator, используя этот рабочий процесс:

Get Specified Finder Items
Get Folder Contents
Filter Finder Items (by kind and then by file extension is not .txt)
Open Finder Items (with Appleworks)

Я тогда застрял;использование фактического Print Finder Items и выбор Adobe PDF, похоже, на самом деле ничего не делают, а запись самой себя с использованием процесса печати в pdf в реальном времени бесполезна, поскольку я не знаю, как заставить Automator сохранить путь, по которому был создан файл, иубедитесь, что он напечатан на нем.

Если кто-нибудь может мне помочь как-нибудь собрать это, я был бы чрезвычайно благодарен.Спасибо.

Ответы [ 3 ]

2 голосов
/ 22 марта 2012

Преобразование с использованием страниц

Если у вас есть Страницы (часть iWork), он может открывать файлы .cwk и сохранять их в формате PDF: просто замените блок if следующим:

if (the_doc's name extension is not "txt") then
    set newName to my makeNewFileName(the_doc, "pdf")
    try
        tell application "Pages"
            open (the_doc as alias)
            set thisDoc to front document
            save thisDoc as "SLDocumentTypePDF" in newName
            close thisDoc saving no
        end tell
    on error
        display dialog "Error: cannot export " & (name of the_doc) & " to PDF."
    end try
end if

(вам понадобится эта пользовательская функция makeNewFileName):

(* prepare new file name with extension ext *)
on makeNewFileName(finderItem, ext)
    tell application "Finder"
        set fname to finderItem's name
        set thePath to (finderItem's container) as alias as text
        return (thePath & (text 1 thru ((length of fname) - (length of (finderItem's name extension as text))) of fname) & ext)
    end tell
end makeNewFileName

( полный рабочий скрипт )

Сценарии графического интерфейса

В качестве альтернативы, вы можете создавать сценарии графического интерфейса на AppleWorks при попытке, но у него есть недостаток, заключающийся в том, что вы не можете программно указать, где сохранить файл PDF.

Этот фрагмент работает для меня:

tell application "AppleWorks 6"
    open the_doc
    activate

    tell application "System Events" to tell process "AppleWorks"
        keystroke "p" using command down
        delay 1 -- or longer, if it takes longer
        click menu button "PDF" of window "Print"
        click menu item "Save as PDF…" of menu 1 of menu button "PDF" of window "Print"
        delay 1 -- or longer
        click button "Save" of window "Save"
    end tell
end tell

К сожалению, AppleWorks, похоже, неправильно слушает команду AppleScript close, поэтому вам может потребоваться закрыть файл, также имитируя нажатия клавиш cmd + W.

1 голос
/ 22 марта 2012

Попробуйте это:

set appleworksFolder to choose folder
set thePath to POSIX path of appleworksFolder as string

tell application "Finder"
set folderItems to files of appleworksFolder
repeat with aFile in folderItems
    set {name:fileName, name extension:nameExtension} to aFile
    set filePath to POSIX path of (aFile as alias) as string

    if nameExtension is not "txt" then
        set theLocation to POSIX path of (aFile as text)
        set baseName to text 1 thru ((get offset of "." & nameExtension in fileName) - 1) of fileName
        set destLocation to (thePath & baseName & ".pdf")
        set theCommand to "/System/Library/Printers/Libraries/./convert -f \"" & filePath & "\"" & " -o " & "\"" & destLocation & "\"" & " -j \"application/pdf\""
        do shell script theCommand

    else
        tell application "Finder" to delete aFile
    end if
end repeat
end tell
0 голосов
/ 13 декабря 2012

Мне нужно было сделать это сегодня на Горе Льва с кучей квитанций RTF; вот как я это сделал:

#!/bin/bash
for file in *.rtf ; do
filename=$(basename "$file")
/usr/sbin/cupsfilter "$file" > "$filename.pdf"
done

Отлично сработало; супер просто. Нет глупости Automator или AppleScript.

...