用Itextsharp 组件导出PDF 的文档的方法

Itextsharp 是一个很强大,开源的,轻量级的 PDF 生成组件,官方网上好像没有相应的API 说明文档,以下是在工作中使用的心得与体会,并附上源码,功能包含了pdf 的创建,table 的创建, 图片的创建以及pdf 文件的读取 。 欢迎转载,转载时,请注明出处。

首先,从Git Itextsharp 官方网站中 ,下载itextsharp.dll 文件,或从VS 的NUGET 管理包中进行添加引用,然后在项目中引用,Demon 中使用的是最新的版本 itextsharp.5.5.13.0 ,或使用该Demon 中的Itextsharp.dll, Git 官网会不定时进行更新,建议使用最新的 Itextsharp.dll 版本。

点击下载 Itextsharp5.5.13.0.dll

 

 

Demon 是个wpf 窗体文件,MainWindow.xaml.cs代码如下:


 * Copyright: ©2016-2018 dell  All Rights Reserved.
 *
 * Current CLR Version: 4.0.30319.18063
 *
 * ProjectName: iTextSharp Demon
 *
 * Assembly:1.0.0.0 
 *
 * Author:Will
 * 
 * Created:2018/7/23 10:04:06
 * 
 * Description:
 *
 *
 ******************************************************************
 *
 * Modify By:
 * 
 * Modify On:
 * 
 * Modify Description:
 * 
 *
 *****************************************************************
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace PdfDemo
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        /// 
        /// 我得第一个Pdf程序
        /// 
        private void CreatePdf()
        {
            Microsoft.Win32.SaveFileDialog dialog = GetDialoag();
            Nullable<bool> result = dialog.ShowDialog();
            if (result == true)
            {
                Document document = new Document();
                PdfWriter.GetInstance(document, new FileStream(dialog.FileName, FileMode.Create));
                document.Open();
                iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph("Hello World");
                document.Add(paragraph);
                document.Close();
                System.Diagnostics.Process.Start(dialog.FileName);
            }
        }
        /// 
        /// 设置页面大小、作者、标题等相关信息设置
        /// 
        private void CreatePdfSetInfo()
        {
            Microsoft.Win32.SaveFileDialog dialog = GetDialoag();
            Nullable<bool> result = dialog.ShowDialog();
            if (result == true)
            {
                //设置纸张大小,自定义大小
                iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
                pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);
                //设置边界
                using (Document document = new Document(pageSize, 36f, 72f, 108f, 180f))
                {
                    // 也可使用系统定义的纸张大小
                    // Document document = new Document(PageSize.A4, 0, 0, 45, 25);
                    var writer = PdfWriter.GetInstance(document, new FileStream(dialog.FileName, FileMode.Create));
                    document.Open();
                    // 添加文档信息
                    document.AddTitle("PDF Document Create by iTextSharp");
                    document.AddSubject("Welcome to use iTextSharp");
                    document.AddKeywords("PDF,iTextSharp");
                    document.AddCreator("Create by will");
                    document.AddAuthor("Will");
                    // 添加文档内容
                    for (int i = 0; i < 5; i++)
                    {
                        document.Add(new iTextSharp.text.Paragraph("Hello World! Successfuly Create PDF document! "));
                    }
                    writer.Flush();
                    document.Close();
                    System.Diagnostics.Process.Start(dialog.FileName);
                }
            }
        }

        /// 
        /// 创建多个Pdf新页
        /// 
        private void CreateTextPDF()
        {
            Microsoft.Win32.SaveFileDialog dialog = GetDialoag();
            Nullable<bool> result = dialog.ShowDialog();
            if (result == true)
            {
                using (Document document = new Document(PageSize.NOTE))
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dialog.FileName, FileMode.Create));
                    document.Open();
                    // 新宋体字,后面的1是索引,索引从0开始,索引的可选项: 0, 1 ;不可省略,因宋体字有两种,宋体,新宋
                    string fontFile = @"C:\Windows\Fonts\SIMSUN.TTC,1";
                    // 字体
                    BaseFont bFont = BaseFont.CreateFont(fontFile, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    iTextSharp.text.Font font = new iTextSharp.text.Font(bFont, 9.0f);
                    for (int k = 1; k < 4; k++)
                    {
                        // 添加新页面,第k 页
                        document.NewPage();
                        // 重新开始页面计数
                        // document.ResetPageCount();
                        for (int i = 1; i < 21; i++)
                        {
                            // 使用chuck 可有效的输出文字
                            // 也可使用 document.Add(new iTextSharp.text.Paragraph("Hello World, Hello World, Hello World, Hello World, Hello World"));
                            Chunk chuck = new iTextSharp.text.Chunk("Hello,Hello,Hello,Hello, How are you?");
                            // 文字字体
                            chuck.Font = font;
                            var paragraph = new iTextSharp.text.Paragraph(chuck);
                            // 对齐方式,剧中对齐
                            paragraph.Alignment = Element.ALIGN_CENTER;
                            paragraph.SpacingAfter = 5.0f;
                            document.Add(paragraph);
                        }
                    }
                    writer.Flush();
                    document.Close();
                    System.Diagnostics.Process.Start(dialog.FileName);
                }
            }
        }

        /// 
        /// 生成图片pdf页(pdf中插入图片)
        /// 
        public void CreatePDFImage()
        {
            //临时文件路径
            string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.jpg";
            Microsoft.Win32.SaveFileDialog dialog = GetDialoag();
            Nullable<bool> result = dialog.ShowDialog();
            if (result == true)
            {
                using (Document document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dialog.FileName, FileMode.Create));
                    document.Open();
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
                    // 图片位置
                    img.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2, (PageSize.A4.Height - img.ScaledHeight) / 2);
                    writer.DirectContent.AddImage(img);
                    iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Hi,I am Wang Wang", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 22f));
                    p.Alignment = Element.ALIGN_CENTER;
                    document.Add(p);
                    writer.Flush();
                    document.Close();
                    System.Diagnostics.Process.Start(dialog.FileName);
                }
            }
        }

        /// 
        /// iTextSharp 读取pdf 文件
        /// 
        private void ReadPdf()
        {
            try
            {
                string fileName = AppDomain.CurrentDomain.BaseDirectory + @"File\ITextSharp Demon.pdf";
                // 创建一个PdfReader对象
                PdfReader reader = new PdfReader(fileName);
                // 获得文档页数
                int n = reader.NumberOfPages;
                // 获得第一页的大小
                iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                // 创建一个文档变量
                Document document = new Document(psize, 50, 50, 50, 50);
                // 创建该文档
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:\Read.pdf", FileMode.Create));
                // 打开文档
                document.Open();
                // 添加内容
                PdfContentByte cb = writer.DirectContent;
                int i = 0;
                int p = 0;
                Console.WriteLine("一共有 " + n + " 页.");
                while (i < n)
                {
                    document.NewPage();
                    p++;
                    i++;
                    PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                    cb.AddTemplate(page1, .5f, 0, 0, .5f, 0, height / 2);
                    Console.WriteLine("处理第 " + i + "");
                    if (i < n)
                    {
                        i++;
                        PdfImportedPage page2 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page2, .5f, 0, 0, .5f, width / 2, height / 2);
                        Console.WriteLine("处理第 " + i + "");
                    }
                    if (i < n)
                    {
                        i++;
                        PdfImportedPage page3 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page3, .5f, 0, 0, .5f, 0, 0);
                        Console.WriteLine("处理第 " + i + "");
                    }
                    if (i < n)
                    {
                        i++;
                        PdfImportedPage page4 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page4, .5f, 0, 0, .5f, width / 2, 0);
                        Console.WriteLine("处理第 " + i + "");
                    }
                    cb.SetRGBColorStroke(255, 0, 0);
                    cb.MoveTo(0, height / 2);
                    cb.LineTo(width, height / 2);
                    cb.Stroke();
                    cb.MoveTo(width / 2, height);
                    cb.LineTo(width / 2, 0);
                    cb.Stroke();
                    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    cb.BeginText();
                    cb.SetFontAndSize(bf, 14);
                    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 4) + (n % 4 > 0 ? 1 : 0)), width / 2, 40, 0);
                    cb.EndText();
                }
                // 关闭文档
                document.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// 
        /// pdf 阅读器打开 pdf 文件
        /// 
        private void ReadPdfNormal()
        {
            try
            {
                string fileName = AppDomain.CurrentDomain.BaseDirectory + @"File\ITextSharp Demon.pdf";
                System.Diagnostics.Process.Start(fileName);
            }
            catch (Exception e)
            {
                throw e;
            }
        }


        /// 
        /// 创建PDF表格
        /// 
        public void CreatePDFTable()
        {
            Microsoft.Win32.SaveFileDialog dialog = GetDialoag();
            Nullable<bool> result = dialog.ShowDialog();
            if (result != null && result.Equals(true))
            {
                using (Document document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dialog.FileName, FileMode.Create));
                    document.Open();
                    PdfPTable table = new PdfPTable(5);
                    for (int i = 1; i < 100; i++)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase("Cell " + i + "colspan 4 rowspan 1"));
                        // 单元格占的列数,5列
                        cell.Colspan = 4;
                        // 单元格占的行数,3行
                        cell.Rowspan = 1;
                        // 边框
                        cell.BorderWidth = 0.2f;
                        // 边框颜色
                        cell.BorderColor = BaseColor.BLACK;
                        // 水平对齐方式,剧中
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        // 垂直对齐方式: 剧中
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        // 添加单元格
                        table.AddCell(cell);


                        PdfPCell cell2 = new PdfPCell(new Phrase("Cell " + i + "colspan 1 rowspan 1"));
                        // 边框
                        cell2.BorderWidth = 0.2f;
                        // 边框颜色
                        cell2.BorderColor = BaseColor.BLACK;
                        // 水平对齐方式,剧中
                        cell2.HorizontalAlignment = Element.ALIGN_CENTER;
                        // 垂直对齐方式: 剧中
                        cell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                        // 添加单元格
                        table.AddCell(cell2);
                    }
                    document.Add(table);
                    writer.Flush();
                    document.Close();
                    System.Diagnostics.Process.Start(dialog.FileName);
                }
            }
        }

        /// 
        /// 保存文件对话框
        /// 
        /// 
        public Microsoft.Win32.SaveFileDialog GetDialoag()
        {
            Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();
            dialog.FileName = "ITextSharp Demon";
            dialog.DefaultExt = ".pdf";
            dialog.Filter = "Text documents (.pdf)|*.pdf";
            return dialog;
        }


        // 创建表格
        private void btnTable_Click(object sender, RoutedEventArgs e)
        {
            CreateTextPDF();
        }

        // 创建文本
        private void btnText_Click(object sender, RoutedEventArgs e)
        {
            CreatePDFTable();
        }

        // 读取pdf 
        private void btnRead_Click(object sender, RoutedEventArgs e)
        {
            //ReadPdf();
            ReadPdfNormal();
        }

        // 创建图片
        private void btnImage_Click(object sender, RoutedEventArgs e)
        {
            CreatePDFImage();
        }
    }
}

MainWindow.xaml 代码如下 :

"PdfDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    
        

参考资料:

1. Git Itextsharp 官方网站

2. 其它资料  

https://wenku.baidu.com/view/032eb56aaf1ffc4ffe47ac1d.html

https://www.cnblogs.com/loyung/p/6879917.html

https://sourceforge.net/projects/itextsharp/

转载于:https://www.cnblogs.com/wisdo/p/9354122.html

你可能感兴趣的:(用Itextsharp 组件导出PDF 的文档的方法)