C# 多张JPG合成PDF
网上找的多张JPG合成PDF多是iTextSharp的老版本,iTextSharp5.5.13.3是比较新的版本,现在最新的全新版本是itext7。老版本用iTextSharp,System.Drawing.Bitmap和会有内存溢出的问题。
引用
using iTextSharp.text;
using iTextSharp.text.pdf;
private void button_TurnImagesToPdf_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Multiselect = true;//等于true表示可以选择多个文件
openFile.DefaultExt = "*.jpg";
openFile.Filter = "图片|*.jpg";
if (openFile.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
int jpg_i = 0;
string filePathOnly = Path.GetDirectoryName(openFile.FileName);
string folderName = Path.GetFileName(filePathOnly);
string pdfPath = filePathOnly + "\\" + folderName + ".pdf";
using (Document document = new Document())
{
using (FileStream PdfStream = new FileStream(pdfPath, FileMode.Create, FileAccess.ReadWrite))
{
using (iTextSharp.text.pdf.PdfWriter write = PdfWriter.GetInstance(document, PdfStream))
{
document.SetMargins(0, 0, 0, 0);
document.Open();
iTextSharp.text.Image jpg=null;
foreach (string file in openFile.FileNames)
{
try
{
System.Drawing.Image SImage = System.Drawing.Image.FromFile(file);
int Width = SImage.Width;
int Height = SImage.Height;
SImage.Dispose();
jpg = iTextSharp.text.Image.GetInstance(file);
document.SetPageSize(new iTextSharp.text.Rectangle(Width, Height));
document.NewPage();
document.Add(jpg);
jpg_i++;
}
catch
{ }
}
write.Flush();
document.Close();
}
}
}
sw.Stop();
double double_sec = sw.ElapsedMilliseconds / 1000.0;
MessageBox.Show("合并" + jpg_i.ToString() + "个,且用时" +
double_sec.ToString() + "秒");
}
GC.Collect();
}