Я пытаюсь объединить несколько PDF-файлов в один PDF-файл, а также добавляю закладку в итоговый PDF-файл, который переместит вас к началу каждого из этих PDF-файлов, которые теперь объединены в один документ. Слияние работает отлично, однако закладки были проблемой.
Я не могу на всю жизнь заставить работать форматирование кода. Извините: (
$output = [System.IO.Path]::Combine($workingDirectory, 'output.pdf');
$fileStream = New-Object System.IO.FileStream($output,
[System.IO.FileMode]::OpenOrCreate);
$document = New-Object iTextSharp.text.Document;
$pdfCopy = New-Object iTextSharp.text.pdf.PdfCopy($document, $fileStream);
$document.Open();
## Variables needed to create Outline.
#
# $currentPagesCount - keeps track of current number of pages so we can
# jump to the correct page in out Outline
#
# $outlinesAL - contains hashmaps what will eventually be written to the
# output.pdf
###
$currentPagesCount = 0;
## This is where the IList<> should be created, i've been using ArrayList
## because I am wanting to call .add()
$outlinesAL = New-Object System.Collections.ArrayList;
foreach ($item in $sectionsArray) {
if ($item.split("]")[0] -match "\[n") {
$tempPath =
[io.path]::combine($pdfDirectory, $item.split("]")[-1] +".pdf");
if(Test-Path($tempPath)){
Write-Color $tempPath -Color Green
$reader = New-Object iTextSharp.text.pdf.PdfReader($tempPath);
$numPages = $reader.NumberOfPages;
$pdfCopy.AddDocument($reader);
## Here is where the dictionary object is added, must be this... the
## iTextSharp library expects an IList<Dictionary<String, Object>>
$dict = New-Object
'System.Collections.Generic.Dictionary[string,Object]';
$dict.Add("Title", $tempPath.FullName);
$dict.Add("Action", $GoTo);
$dict.Add("Page", $pageString);
$outlinesAL.Add($dict);
$currentPagesCount += $numPages;
$reader.Close();
} else {
Write-Color $tempPath -Color Red
}
}
}
## Finished with merge, we can close this stuff.
## Page numbers are effed, need to see about renumbering the pages in the
.pdfs
$pdfCopy.Close();
$document.Close();
$fileStream.Close();
$finalOutput = [System.IO.Path]::Combine($workingDirectory,
'FinalDocument.pdf');
$finalReader = New-Object iTextSharp.text.pdf.PdfReader($output);
$finalStream = New-Object System.IO.FileStream($finalOutput,
[System.IO.FileMode]::OpenOrCreate);
## Add the bookmarks hashtable to the pdf somehow.
$pdfStamper = New-Object iTextSharp.text.pdf.PdfStamper($finalReader,
$finalStream);
$outlinesAL.gettype();
$pdfStamper.set_Outlines($outlinesAL);
$pdfStamper.Close();
$finalStream.Close();
$finalReader.Close();
Невозможно преобразовать аргумент "значение" со значением:
«System.Collections.Generic.Dictionary2 [System.String, System.Object]
... ", для" set_Outlines "набрать
"System.Collections.Generic.IList 1 [System.Collections.G
eneric.Dictionary 2 [System.String, System.Object]] ":" Не удается преобразовать
значение типа "System.Collections.ArrayList"
"System.Collections.ArrayList" для ввода
"System.Collections.Generic.IList 1 [System.Collections.Generic.Dictionary
2 [System.String, System.Object]] "" На ~ merge.ps1: 150 char: 1
+ $ pdfStamper.set_Outlines ($ outlinesAL);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo: NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId: MethodArgumentConversionInvalidCastArgument
Это похоже на довольно простую проблему с типами, входящими в метод set_Outlines в PDFStamper, проблема в том, что он ожидает generic.IList, и когда я пытаюсь использовать этот тип, я больше не могу добавлять элементы.
Вот отражение от iTextSharp.dll:
// iTextSharp.text.pdf.PdfStamper
using System.Collections.Generic;
/// Sets the bookmarks. The list structure is defined in
/// {@link SimpleBookmark}.
/// @param outlines the bookmarks or <CODE>null</CODE> to remove any
public virtual IList<Dictionary<string, object>> Outlines
{
set
{
stamper.Outlines = value;
}
}