码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-23 14:52:31      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:pac   win   cep   center   ica   i++   odi   auth   eric   

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

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

点击下载 Itextsharp.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
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 我得第一个Pdf程序
        /// </summary>
        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);
            }
        }
        /// <summary>
        /// 设置页面大小、作者、标题等相关信息设置
        /// </summary>
        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);
                }
            }
        }

        /// <summary>
        /// 创建多个Pdf新页
        /// </summary>
        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);
                }
            }
        }

        /// <summary>
        /// 生成图片pdf页(pdf中插入图片)
        /// </summary>
        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);
                }
            }
        }

        /// <summary>
        /// iTextSharp 读取pdf 文件
        /// </summary>
        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;
            }
        }

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


        /// <summary>
        /// 创建PDF表格
        /// </summary>
        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);
                }
            }
        }

        /// <summary>
        /// 保存文件对话框
        /// </summary>
        /// <returns></returns>
        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 代码如下 :

<Window x:Class="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">
    <Grid>
        <Button Content="创建文本" Height="23" HorizontalAlignment="Left" Margin="38,268,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="btnText_Click" />
        <Button Content="创建表格" Height="23" HorizontalAlignment="Left" Margin="266,0,0,20" Name="button2" VerticalAlignment="Bottom" Width="75" Click="btnTable_Click" />
        <Button Content="创建图片" Height="23" HorizontalAlignment="Left" Margin="379,268,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="btnImage_Click" />
        <Button Content="读取PDF" Height="23" HorizontalAlignment="Left" Margin="151,0,0,20" Name="button4" VerticalAlignment="Bottom" Width="75" Click="btnRead_Click" />
        <Label Content="Hello,Welcome to use" Height="198" HorizontalAlignment="Center" Margin="23,24,0,0" Name="label1" VerticalAlignment="Top" Width="431" ToolTip="Hello,Welcome to use" FontSize="18" FontWeight="Bold" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" SnapsToDevicePixels="True" />
    </Grid>
</Window>

参考资料:

1. Git Itextsharp 官方网站

2. 其它资料  

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

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

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

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

标签:pac   win   cep   center   ica   i++   odi   auth   eric   

原文地址:https://www.cnblogs.com/wisdo/p/9354122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!