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:* ********************************************************************/
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Data;usingSystem.Windows.Documents;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Imaging;usingSystem.Windows.Navigation;usingSystem.Windows.Shapes;usingiTextSharp.text;usingiTextSharp.text.pdf;usingSystem.IO;namespacePdfDemo
{/// <summary>///MainWindow.xaml 的交互逻辑/// </summary>public partial classMainWindow : Window{publicMainWindow(){InitializeComponent();}/// <summary>///我得第一个Pdf程序/// </summary>private voidCreatePdf(){Microsoft.Win32.SaveFileDialog dialog=GetDialoag();Nullable<bool> result =dialog.ShowDialog();if (result == true){Document document= newDocument();PdfWriter.GetInstance(document,newFileStream(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 voidCreatePdfSetInfo(){Microsoft.Win32.SaveFileDialog dialog=GetDialoag();Nullable<bool> result =dialog.ShowDialog();if (result == true){//设置纸张大小,自定义大小iTextSharp.text.Rectangle pageSize = newiTextSharp.text.Rectangle(216f, 716f);pageSize.BackgroundColor= new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);//设置边界using (Document document = newDocument(pageSize, 36f, 72f, 108f, 180f)){//也可使用系统定义的纸张大小//Document document = new Document(PageSize.A4, 0, 0, 45, 25);var writer = PdfWriter.GetInstance(document, newFileStream(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 voidCreateTextPDF(){Microsoft.Win32.SaveFileDialog dialog=GetDialoag();Nullable<bool> result =dialog.ShowDialog();if (result == true){using (Document document = newDocument(PageSize.NOTE)){PdfWriter writer= PdfWriter.GetInstance(document, newFileStream(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 = newiTextSharp.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 voidCreatePDFImage(){//临时文件路径string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.jpg";Microsoft.Win32.SaveFileDialog dialog=GetDialoag();Nullable<bool> result =dialog.ShowDialog();if (result == true){using (Document document = newDocument()){PdfWriter writer= PdfWriter.GetInstance(document, newFileStream(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", newiTextSharp.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 voidReadPdf(){try{string fileName = AppDomain.CurrentDomain.BaseDirectory + @"File\ITextSharp Demon.pdf";//创建一个PdfReader对象PdfReader reader = newPdfReader(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){throwe;}}/// <summary>///pdf 阅读器打开 pdf 文件/// </summary>private voidReadPdfNormal(){try{string fileName = AppDomain.CurrentDomain.BaseDirectory + @"File\ITextSharp Demon.pdf";System.Diagnostics.Process.Start(fileName);}catch(Exception e){throwe;}}/// <summary>///创建PDF表格/// </summary>public voidCreatePDFTable(){Microsoft.Win32.SaveFileDialog dialog=GetDialoag();Nullable<bool> result =dialog.ShowDialog();if (result != null && result.Equals(true)){using (Document document = newDocument()){PdfWriter writer= PdfWriter.GetInstance(document, newFileStream(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>publicMicrosoft.Win32.SaveFileDialog GetDialoag(){Microsoft.Win32.SaveFileDialog dialog= newMicrosoft.Win32.SaveFileDialog();dialog.FileName= "ITextSharp Demon";dialog.DefaultExt= ".pdf";dialog.Filter= "Text documents (.pdf)|*.pdf";returndialog;}//创建表格private void btnTable_Click(objectsender, RoutedEventArgs e){CreateTextPDF();}//创建文本private void btnText_Click(objectsender, RoutedEventArgs e){CreatePDFTable();}//读取pdfprivate void btnRead_Click(objectsender, RoutedEventArgs e){//ReadPdf();
ReadPdfNormal();}//创建图片private void btnImage_Click(objectsender, 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/

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

用Itextsharp 组件导出PDF 的文档的方法相关推荐

  1. java导出pdf格式文档

    // 1.新建document对象 // 第一个参数是页面大小.接下来的参数分别是左.右.上和下页边距. Document document = new Document(PageSize.A4, 5 ...

  2. js将HTML导出生成word文档

    在项目开发中中,遇到将HTML导出生成word文档,刚开始在网上找了很多资料,基本都是jQuery中的插件jquery.wordexport.js,刚开始是不想用这个的,这个要引用另一个插件FileS ...

  3. 用js将HTML文本导出生成word文档

    在项目开发中中,遇到将HTML导出生成word文档,刚开始在网上找了很多资料,基本都是jQuery中的插件jquery.wordexport.js,刚开始是不想用这个的,这个要引用另一个插件FileS ...

  4. R语言使用compareGroups包compareGroups函数生成表统计表、createTable函数创建二元表、并导出结果到文档(doc、csv、xlsx、pdf)

    R语言使用compareGroups包compareGroups函数生成表统计表.createTable函数创建二元表.并导出结果到文档(doc.csv.xlsx.pdf) 目录 R语言使用compa ...

  5. 开票系统导出的OFD文档如何转换PDF格式?

    近年来OFD格式正在被越来越多的小伙伴所熟知,我们知道这是一种电子发票的格式,但是这种格式的文件需要特定的软件才能打开,为了方便阅览编辑OFD文件中的内容,我们一般会将其转换成PDF格式文档,那么改如 ...

  6. 将HTML导出生成word文档

    前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...

  7. 支持将数据导出到Excel文档的时候设置单元格格式的.NET控件Spire.DataExport

    Spire.DataExport for .NET是e-iceblue公司推出的一款数据导出类.NET控件.作为一款专业的数据导出控件,Spire.DataExport for .NET可以帮助开发人 ...

  8. python根据模板生成pdf文件_程序生成word与PDF文档的方法(python)

    程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用free ...

  9. python处理word或者pdf文件_利用python程序生成word和PDF文档的方法

    一.程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用fr ...

最新文章

  1. 数据绑定(Binding)
  2. mysql子查询复杂操作_MySQL 子查询操作
  3. 云原生产业联盟成立 蚂蚁金服当选为理事单位
  4. 错误:因为相同类型的其他实体已具有相同的主键值。在使用 Attach 方法或者将实体的状态设置为 Unchanged 或 Modified 解决方法...
  5. linux 使用FIO测试磁盘iops
  6. 计算机网络-基本概念(9)【传输层】TCP拥塞控制 【网络层】拥塞避免
  7. Class的 getSuperclass与getGenericSuperclass区别
  8. 动手学servlet(四) cookie和session
  9. python三方库之paramiko
  10. oracle date 隐式转换,PL/SQL中的数据类型隐式转换规则
  11. 深入理解 MVC 中的 M 与 C
  12. 物理机安装linux系统,物理机安装linux的三种方法
  13. MBR分区表详解(SD卡)
  14. MLX90614各类型芯片总结
  15. 轻量级配置的登录管理器选择---Silm[zt]
  16. u 盘安装linux系统,CentOS 7 系统安装之 U 盘安装法
  17. 免费在线图片识别文字工具
  18. 去哪找到高薪工作怎么找
  19. ybt1250 The Castle
  20. Debian系统更新apt源

热门文章

  1. python基础总结---安装、语法、变量、数据类型、计算、语句、(1-3)
  2. c 11 主要的新语言特性,关于c ++ 11:有没有办法确定C ++编译器实现的语言特性?...
  3. linuxoracle静默安装应答文件修改_Oracle 19c的examples静默安装
  4. 线性代数 矩阵 行列式基本知识(转)
  5. 第一章:初识lucene
  6. 《剑指offer》题目说明
  7. g77,g95,gfortran的关系
  8. node.js之打包工具webpack
  9. AngularStrap -- Popovers
  10. api 规则定义_API有规则,而且功能强大