使用PowerShell的ItextSharp将Tiff和PDF合并为1个大型PDF [英] ItextSharp with PowerShell Merging Tiff and PDF to 1 large PDF

查看:166
本文介绍了使用PowerShell的ItextSharp将Tiff和PDF合并为1个大型PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a powershell script that will loop through a csv file looking for Tiff & PDF files using ItextSharp dll. The desired end result is every image and page of a pdf needs to be in one large pdf.

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

My thoughts are to create two functions to accomplish this. 1 for images and the other for PDF's. The image function is working properly, but the pdf is throwing a error: Exception calling ".ctor" with "1" argument(s): " not found as file or resource."

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

Any thoughts on fixing add-pdf function?

目前的脚本如下。

[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()


推荐答案

我也不是在PowerShell中很好,但看起来你应该能够很容易地适应这个C#代码。这篇文章中的代码改编自我之前此处编写的一些代码。

I'm not too good within PowerShell but it looks like you are so you should be able to adapt this C# code very easily. The code in this post is adapted from some code I wrote earlier here.

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

First off, I really don't recommend keeping global iText abstraction objects around and binding various things to them over and over, that's just looking for trouble.

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

Instead, for images I'd recommend a simple function that takes a supplied image file and returns a byte array representing that image added to a PDF. Instead of a byte array you could also write the PDF to a temporary file and return that path instead.

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();
    }
}

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

Then just create a new Document and bind a PdfSmartCopy object to it. You can then enumerate your files, if you have an image, convert it to a PDF first, then just use the PdfSmartCopy method AddDocument() to add that entire document to the final output.

下面的代码只循环遍历单个文件夹,首先抓取图像然后抓取PDF但你应该是能够很容易地适应它。希望。

The code below just loop through a single folder, grabs images first and then PDFs but you should be able to adapt it pretty easily, hopefully.

//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();
        }
    }
}

这篇关于使用PowerShell的ItextSharp将Tiff和PDF合并为1个大型PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆