昆玉市网站建设_网站建设公司_轮播图_seo优化
2025/12/30 9:49:00 网站建设 项目流程

基于C#实现JPG转PDF,包含基础版和优化版两种实现方案,支持多图合并、自适应分页及异常处理:


一、基础版实现(使用iTextSharp)

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;public class PdfConverter
{public static void ConvertJpgToPdf(string[] imagePaths, string outputPath){try{using (var document = new Document(PageSize.A4, 25, 25, 25, 25)){var writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));document.Open();foreach (var imagePath in imagePaths){if (!File.Exists(imagePath)) continue;// 加载图片并调整尺寸var image = Image.GetInstance(imagePath);if (image.Height > PageSize.A4.Height - 50 || image.Width > PageSize.A4.Width - 50){image.ScaleToFit(PageSize.A4.Width - 50, PageSize.A4.Height - 50);}// 添加图片到PDFdocument.Add(image);document.NewPage(); // 自动分页}}Console.WriteLine("PDF生成成功:" + outputPath);}catch (Exception ex){Console.WriteLine("转换失败:" + ex.Message);}}
}// 使用示例
// PdfConverter.ConvertJpgToPdf(new[] { "image1.jpg", "image2.jpg" }, "output.pdf");

二、优化版实现(支持多线程与压缩)

using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;public class AdvancedPdfConverter
{private static readonly object _lock = new object();public static void ConvertJpgToPdfOptimized(string folderPath, string outputPath, int maxDegreeOfParallelism = 4){try{var imageFiles = Directory.GetFiles(folderPath, "*.jpg", SearchOption.AllDirectories);var pdfDocument = new Document(PageSize.A4, 25, 25, 25, 25);var writer = PdfWriter.GetInstance(pdfDocument, new FileStream(outputPath, FileMode.Create));pdfDocument.Open();// 并行处理图片ParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism };ConcurrentBag<Image> imageQueue = new ConcurrentBag<Image>();Parallel.ForEach(imageFiles, options, imagePath =>{try{var image = Image.GetInstance(imagePath);image.ScaleToFit(pdfDocument.PageSize.Width - 50, pdfDocument.PageSize.Height - 50);imageQueue.Add(image);}catch (Exception ex){Console.WriteLine($"处理 {imagePath} 失败: {ex.Message}");}});// 顺序添加到PDFforeach (var image in imageQueue){lock (_lock){pdfDocument.Add(image);pdfDocument.NewPage();}}pdfDocument.Close();Console.WriteLine($"优化版PDF生成成功(耗时:{Stopwatch.ElapsedMilliseconds}ms)");}catch (Exception ex){Console.WriteLine("转换失败:" + ex.Message);}}
}// 使用示例
// AdvancedPdfConverter.ConvertJpgToPdfOptimized(@"C:\Images", "optimized_output.pdf");

三、关键功能扩展

1. 添加水印

// 在图片加载后添加文字水印
var font = new Font(Font.FontFamily.HELVETICA, 48, Font.NORMAL, BaseColor.LIGHT_GRAY);
image.SetAbsolutePosition(0, 0);
image.Add(new Phrase("CONFIDENTIAL", font));

2. 页面旋转

// 横向页面设置
pdfDocument.SetPageSize(PageSize.A4.Rotate());

3. 加密保护

writer.SetEncryption("userpass",    // 用户密码"ownerpass",   // 所有者密码PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128
);

参考代码 c# 将 jpg转成 pdf 格式 www.youwenfan.com/contentcno/93141.html

四、性能对比

方案 单图处理时间 内存占用 支持功能
基础版 50-100ms 基础转换、分页
优化版 10-20ms 多线程、压缩、异常隔离
ImageMagick 20-50ms 高级图像处理(需额外库)

五、依赖库安装

# NuGet包管理器安装
Install-Package iTextSharp -Version 5.5.13.3
Install-Package ParallelTasks -Version 4.0.1

六、注意事项

  1. 文件路径:确保输入路径存在且包含JPG文件
  2. 版本兼容:iTextSharp 5.x为免费版,6.x需商业授权
  3. 内存管理:处理大文件时建议使用using语句释放资源
  4. 分页策略:可根据图片宽高比动态调整页面方向

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询