1、管理NuGet程序包中搜索并安装itext7;
2、引用库;
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using Image = iText.Layout.Element.Image;
using iText.IO.Image;
3、主程序:
private void button1_Click(object sender, EventArgs e)
{
string inputFolderPath = @"D:\待处理图库"; //图片输入路径
string outputPdfPath = @"D:\处理后图库\File1.pdf"; //图片输出路径
ConvertImagesToPdf(inputFolderPath, outputPdfPath); //图片转pdf子程序
}
//图片转pdf子程序
static void ConvertImagesToPdf(string inputFolderPath, string outputPdfPath )
{
try
{
// iTextSharp代码块
using (var pdfWriter = new PdfWriter(outputPdfPath))
{
using (var pdfDocument = new PdfDocument(pdfWriter))
{
using (var document = new Document(pdfDocument))
{
// 获取文件夹中的所有图片文件,可根据实际修改图片文件后缀名
string[] imageFiles = Directory.GetFiles(inputFolderPath, "*.png");
foreach (var imageFile in imageFiles)
{
// 将每个图片文件添加到PDF中
Image img = new Image(ImageDataFactory.Create(imageFile));
document.Add(img);
}
}
}
}
}
catch (Exception ex)
{
//Console.WriteLine("An exception occurred: " + ex.Message);
//Console.WriteLine("Stack trace: " + ex.StackTrace);
// 可能还可以输出更多信息,如异常的内部异常等
}
}
4、效果
D:\待处理图库
D:\处理后图库\File1.pdf