将子文件夹中的所有图像添加到iTextSharp中的PDF文档作为新页面?

时间:2011-02-24 18:35:57

标签: c# pdf pdf-generation itextsharp

我有如下文件夹结构:

D:\myphotos\2011-02-09\1.jpg
D:\myphotos\2011-02-10\2.jpg
....
......
............
D:\myphotos\2011-02-23\10.jpg

我需要使用iTextSharp将所有这些图像作为新页面添加到pdf文档中。怎么能 我最低限度地达到了这个目标吗?

1 个答案:

答案 0 :(得分:4)

这是基本想法。您可能需要调整图像大小。如果是这样,只需像在.Net中那样调整图像大小,将图像保存到MemoryStream并从原始字节创建Jpeg对象。

//Create a new document
iTextSharp.text.Document Doc = new iTextSharp.text.Document(PageSize.LETTER, 20, 20, 20, 20);
//Store the document on the desktop
string PDFOutput = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
PdfWriter writer = PdfWriter.GetInstance(Doc, new FileStream(PDFOutput, FileMode.Create, FileAccess.Write, FileShare.Read));

//Open the PDF for writing
Doc.Open();

string Folder = "C:\\Images";
foreach (string F in System.IO.Directory.GetFiles(Folder, "*.jpg")) {
    //Insert a page
    Doc.NewPage();
    //Add image
    Doc.Add(new iTextSharp.text.Jpeg(new Uri(new FileInfo(F).FullName)));
}

//Close the PDF
Doc.Close();