Глубокое использование iText 5 в powershell 7 - PullRequest
0 голосов
/ 30 мая 2020

Я новичок в PowerShell, но с помощью этого сайта я уже создал несколько полезных скриптов (для меня) для автоматизации некоторых скучных операций на моем P C.

Теперь я пытаюсь с разной удачей, чтобы установить некоторые настройки в файлах pdf на моем P C (более 8000), которые я сейчас опишу:

Прежде всего, скрипт читает, является ли данный pdf пароль паролем защищен (в этом случае я не хочу выполнять никаких операций) или нет. Во втором случае сценарий продолжается.
Продолжая читать из меню -> Файл -> Свойства документа, Описание вкладки, поля «Заголовок», «Автор», «Тема», и если они содержат данные, я хочу сначала очистить их, а затем заполнить данные, которые я объясню далее.

Затем из меню -> Файл -> Вкладка «Свойства документа» Начальный вид Я хочу, чтобы вы установили вкладку «Навигация» на «Панель страниц и закладок», если есть хотя бы одна закладка, в противном случае «Только страница», макет страницы на «Одной странице», увеличение «По высоте».

Вы должны знать, что имя КАЖДОГО pdf файла на моем p c имеет следующий формат: Имя Фамилия автор (s) - Название. Возможные субтитры (Издатель, год публикации) [Язык PDF]

Например:

  • Озен Озкая, Гирей Йылликчи - Программирование компьютерного зрения Arduino. Проектируйте и разрабатывайте реальные приложения для компьютерного зрения с помощью мощной комбинации OpenCV и Arduino (Packt, 2015) [ENG]
  • Джон Уокенбах, Майкл Александер, Дик Куслейка - Microsoft® Excel® 2019 Библия (Дж. Вили & Sons, 2019) [ENG]

Затем указанные выше поля должны быть извлечены из имени файла.
Язык PDF-файла в меню -> Файл -> Вкладка «Расширенные свойства документа» Я хочу он устанавливается путем извлечения данных из квадратных скобок [] в имени файла.

Автор PDF-файла, если он есть, я хочу, чтобы его очистили.
Любая другая информация, представленная в метаданных , если не обязательно, я хочу его удалить.

Вот что я сделал до сих пор. Как всегда, многие строки кода закомментированы.

        # (ENG) Clear console.
        Clear-Host
        # (ENG) Set in $WorkingDir variable the complete path, removing script name and his extension, that we are running. 
        $WorkingDir = Split-Path $PSCommandPath
        # (ENG) Set in $DllToLoad variable the string in $WorkingDir variable, add a slash, add the library name with its extension.
        $DllToLoad = "$WorkingDir" + "\" + "itextsharp.dll"
        # (ENG) Read the dll.
        [System.Reflection.Assembly]::LoadFrom($DllDaCaricare)
        # (ENG) New Array with all pdf files in working dir.
        $Pdf = Get-ChildItem $DirectoryDiLavoro -Filter *.pdf
        # (ENG) Loop for all pdf files in the Array.
        foreach ($CurrentPdf in $Pdf)
            {
                # Set in $filename the current pdf file.
                $filename = $CurrentPdf.Name
                # Set in $Basename the current pdf file without extension.
                $Basename = $CurrentPdf.BaseName
                Try
                    {
                        # (ENG) Open reader with the current pdf file.
                        $CheckPdf = New-Object iTextSharp.text.pdf.PdfReader ($CurrentPdf.FullName)
                        #$pdfWriter = New-Object iTextSharp.text.pdf.PdfWriter ($CurrentPdf.FullName) [I found this somewhere but I don't know how iterate]              
                        #$doc = New-Object iTextSharp.text.Document ($CurrentPdf.FullName) [I found this somewhere but I don't know how iterate] 
                        if ($CheckPdf.IsEncrypted())
                                {
                                    Write-Host $filename "`nProtected" -ForegroundColor Red
                                    Write-Host $CheckPdf.Info.Title 
                                    Write-Host $CheckPdf.Info.Author
                                    Write-Host $CheckPdf.Info.Subject
                                }
                            else
                                {
                                    Write-Host $filename "`nUnprotected" -ForegroundColor Green
                                    if ($CheckPdf.Info.Title -ne "") [How check if the field is NOT empty, to continue the routine?]
                                        {
                                            Write-Host " * * * Build Pdf title ... * * * "
                                            Write-Host "Old title: " $CheckPdf.Info.Title
                                            $Doc.AddTitle("") | Out-Null [How to empty the field?]
                                            Write-Host "Title now is empty: " $CheckPdf.Info.Title
                                            $Basename -match "\-\s(.*)\s\("   [The Regexp is OK]
                                            $Doc.AddTitle("$Matches.1") | Out-Null [How to fill the field?]
                                        }    
                                    if ($CheckPdf.Info.Author -ne "") [How check if the field is NOT empty, to continue the routine?]
                                        {
                                            Write-Host " * * * Build pdf author ...* * * "
                                            Write-Host "Old author: " $CheckPdf.Info.Author
                                            $Doc.AddAuthor("") | Out-Null [How to empty the field?]
                                            Write-Host "Authr now is empty: " $CheckPdf.Info.Author
                                            $Basename -match "(.*)\s\-"   [The Regexp is OK]
                                            $Doc.AddAuthor("$Matches.1") | Out-Null [How to fill the field?]
                                        }
                                    if ($CheckPdf.Info.Subject -ne "") [How check if the field is NOT empty, to continue the routine?]
                                        {
                                            Write-Host " * * * Build pdf subject ...* * * "
                                            Write-Host "Old subject: " $CheckPdf.Info.Subject
                                            $Doc.AddSubject("") | Out-Null [How to empty the field?]
                                            Write-Host "Subject now is empty: " $CheckPdf.Info.Subject
                                        }

                                    if [... How to read language field and build the if statement?]**
                                                Write-Host " * * * Build pdf language ...* * * "
                                                Write-Host "Old language: " [...]
                                                $Doc.AddLanguage("") | Out-Null [How to empty the field?]
                                                Write-Host "Language now is empty: " [....]
                                                $Basename -match "\[([A-Z]{3})\]"   [The Regexp is OK]
                                                $Doc.AddLanguage("$Matches.1") | Out-Null [How to fill the field?]
                                }

                      # [Here all the code to empty unnecessary metadata]                        

                      # [Here all the code to set the initial view settings. I found on google:]                        

                      # [If there are NO bookmarks: The page layout to be used when the document is opened
PageLayoutSinglePage, otherwise... ???]

# [setMagnification: MAGNIFICATION_FIT_HEIGHT I don't know how to write this part]                        
                    }
                Catch
                    {
                        write-host $filename " Problems with the file. Control." -ForegroundColor Yellow
                    }
                }

Некоторая информация:

Я использую код Visual Studio для написания моего скрипта (последней и обновленной версии) с PowerShell 7.0 (обновлено). Версия iTextSharp - 5.5.13.1 в том же каталоге, где находится скрипт и где хранятся файлы PDF.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...