C# 多张图片生成PDF

时间:2024-03-03 22:55:31

 

//存放image路径

List<string> imageList = new List<string>();
imageList.Add(@"D:\image1.png");
imageList.Add(@"D:\image2.png");
//生成PDF路径
string fileName = string.Empty;
fileName = @"D:\testpdf.pdf";
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(300f, 250f);
Document document = new Document(page,15f, 20f, 35f, 10f);
//设置纸张横向
//document.SetPageSize(page.Rotate());
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
for (int i = 0; i < imageList.Count; i++)
{
      document.Open();
      iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageList[i]);
      img.ScaleAbsolute(170f, 170f);

      //图片居中
      img.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
      //图片绝对定位
      img.SetAbsolutePosition(55, 30);

      //图片打印到PDF
      writer.DirectContent.AddImage(img);
      document.NewPage();
}

document.Close();