ItextSharp使用PowerShell将Tiff和PDF合并为1个大PDF

时间:2015-10-01 13:13:19

标签: powershell pdf itextsharp itext

我试图编写一个PowerShell脚本,它将遍历一个csv文件,寻找Tiff&使用ItextSharp dll的PDF文件。期望的最终结果是每个图像和pdf的页面需要在一个大的pdf中。

我的想法是创造两个功能来实现这一目标。 1用于图像,另一个用于PDF' s。图像功能正常工作,但pdf抛出错误:异常调用" .ctor"用" 1"论证:"找不到文件或资源。"

有关修复add-pdf功能的想法吗?

目前的脚本如下。

[System.Reflection.Assembly]::LoadFrom("C:\Temp\itextsharp`enter code here`\itextsharp.dll")
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$doc = New-Object itextsharp.text.document
#output PDF with all combined tiff and pdfs
$stream = [IO.File]::OpenWrite("C:\temp\itext\test.pdf")
$writer = [itextsharp.text.pdf.PdfWriter]::GetInstance($doc, $stream)

#$pdfCopy =New-Object iTextSharp.text.pdf.PdfCopy($doc, $stream)
$doc.Open()
$doc.SetMargins(0, 0, 0, 0)

#get the size of image and change pdf
function add-picture( $file2use){
    $pic = New-Object System.Drawing.Bitmap($file2use )
    $rect = New-Object iTextSharp.text.Rectangle($pic.Width, $pic.Height)

    ## Set the next page size to those dimensions and add a new page
    $doc.SetPageSize( $rect )
    $doc.NewPage()
#add image jpg
$img = [iTextSharp.text.Image]::GetInstance($file2use )
$doc.Add($img);

$pic.dispose()

}

function add-pdf( $newPDF){

$pdf2Merge = [System.IO.Path]::Combine("",$newPDF)
$pdfCopy = New-Object iTextSharp.text.pdf.PdfCopy($doc, $stream);
$reader = New-Object iTextSharp.text.pdf.PdfReader($pdf2Merge);
$pageCount = $reader.NumberOfPages;

for ($i = 1; $i -lt $pageCount ; $i++) {



        $pdfCopy.AddPage(
            $pdfCopy.GetImportedPage($reader, $i  ))
                                             # ^^^^^
                                             # your page number here

}
#$pdfCopy.FreeReader($reader);

}

add-picture  -file2use "C:\Temp\itext\3-26-04 (1).JPG"
add-picture  -file2use "C:\Temp\itext\CCITT_1.TIF" 
add-picture  -file2use "C:\Temp\itext\CCITT_2.TIF" 
add-pdf  -file2use "C:\Temp\itext\test2.pdf"

 ## Cleanup


#$doc.Close()
$stream.Close()

1 个答案:

答案 0 :(得分:1)

我在PowerShell中不太好,但看起来你是这样的,你应该能够很容易地适应这个C#代码。这篇文章中的代码改编自我编写的earlier here

代码

首先,我真的不建议保持全局iText抽象对象并反复绑定各种各样的东西,这只是在寻找麻烦。

相反,对于图像,我建议使用一个简单的函数,该函数获取提供的图像文件并返回表示添加到PDF的图像的字节数组。您也可以将PDF写入临时文件而不是字节数组,而是返回该路径。

private static byte[] ImageToPdf(string imagePath) {
    //Get the size of the current image
    iTextSharp.text.Rectangle pageSize = null;
    using (var srcImage = new Bitmap(imagePath)) {
        pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
    }

    //Simple image to PDF
    using (var m = new MemoryStream()) {
        using (var d = new Document(pageSize, 0, 0, 0, 0)) {
            using (var w = PdfWriter.GetInstance(d, m)) {
                d.Open();
                d.Add(iTextSharp.text.Image.GetInstance(imagePath));
                d.Close();
            }
        }

        //Grab the bytes before closing out the stream
        return m.ToArray();
    }
}

然后只需创建一个新的Document并将PdfSmartCopy对象绑定到它。然后,您可以枚举文件,如果您有图像,请先将其转换为PDF,然后使用PdfSmartCopy方法AddDocument()将整个文档添加到最终输出中。

下面的代码只循环浏览一个文件夹,首先抓取图像,然后抓取PDF,但你应该能够很容易地调整它,希望如此。

//Folder that contains our sample files
var sourceFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "MergeTest");

//Final file that we're going to emit
var finalFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");

//Create our final file, standard iText setup here
using (var fs = new FileStream(finalFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {

        //Use a smart object copies to merge things
        using (var copy = new PdfSmartCopy(doc, fs)) {

            //Open the document for writing
            doc.Open();

            //Loop through each image in our test folder
            foreach (var img in System.IO.Directory.EnumerateFiles(sourceFolder, "*.jpg")) {

                //Convert the image to a byte array
                var imageAsPdf = ImageToPdf(img);

                //Bind a reader to that PDF
                using( var r = new PdfReader(imageAsPdf) ){

                    //Add that entire document to our final PDF
                    copy.AddDocument(r);
                }
            }

            //Loop through each PDF in our test folder
            foreach (var pdf in System.IO.Directory.EnumerateFiles(sourceFolder, "*.pdf")) {

                //Bind a reader to that PDF
                using (var r = new PdfReader(pdf)) {

                    //Add that entire document to our final PDF
                    copy.AddDocument(r);
                }
            }

            doc.Open();
        }
    }
}