C#——使用iTextSharp生成pdf文件

来源:互联网 发布:知乎怎么发文章 编辑:程序博客网 时间:2024/06/08 09:39
 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

 

List<String> pages = new List<String>();//存放所有页码

iTextSharp.text.Image image;

                            //设置文档大小及边距
                            Document document = new Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
                            //生成pdf
                            PdfWriter.GetInstance(document, new FileStream(desPath + name + ".pdf", FileMode.Create));
                            document.Open();
                           
                            foreach (string p in pages)//逐个插入图片
                            {
                                //获取图片文件名
                                fileTif = Directory.GetFiles(desPath, p + ".tif", SearchOption.AllDirectories);
                                if (fileTif.Length == 0)
                                {
                                    WriteFile(textBox2.Text + "//err.txt", fileZIP[0] + "中" + p + ".tif" + "未找到!!"
                                        + desPath + filename + (ii + 1).ToString() + ".pdf中缺少该页");
                                    continue;
                                }
                               
                                image = iTextSharp.text.Image.GetInstance(fileTif[0]);
                                //调整图片大小,使之适合A4
                                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);
                            }
                           
                            document.Close();

原创粉丝点击