C# 将多张图片合成PDF
程序员文章站
2024-01-01 09:30:28
...
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace JpgToPdf
{
class Program
{
static void Main(string[] args)
{
string[] files = { @"C:\101\1.jpg", @"C:\101\2.jpg" };
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
try
{
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(@"C:\101.pdf", FileMode.Create, FileAccess.ReadWrite));
document.Open();
iTextSharp.text.Image image;
for (int i = 0; i < files.Length; i++)
{
if (String.IsNullOrEmpty(files[i])) break;
image = iTextSharp.text.Image.GetInstance(files[i]);
if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
}
else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
document.NewPage();
document.Add(image);
//iTextSharp.text.Chunk c1 = new iTextSharp.text.Chunk("Hello World");
//iTextSharp.text.Phrase p1 = new iTextSharp.text.Phrase();
//p1.Leading = 150; //行间距
//document.Add(p1);
}
Console.WriteLine("转换成功!");
}
catch (Exception ex)
{
Console.WriteLine("转换失败,原因:" + ex.Message);
}
document.Close();
Console.ReadKey();
}
}
}