Itextsharp 是一个很强大,开源的,轻量级的 PDF 生成组件,官方网上好像没有相应的API 说明文档,以下是在工作中使用的心得与体会,并附上源码,功能包含了pdf 的创建,table 的创建, 图片的创建以及pdf 文件的读取 。 欢迎转载,转载时,请注明出处。
首先,从Git Itextsharp 官方网站中 ,下载itextsharp.dll 文件,或从VS 的NUGET 管理包中进行添加引用,然后在项目中引用,Demon 中使用的是最新的版本 itextsharp.5.5.13.0 ,或使用该Demon 中的Itextsharp.dll, Git 官网会不定时进行更新,建议使用最新的 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 = ; i < ; 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 = ; k < ; k++)
{
// 添加新页面,第k 页
document.NewPage();
// 重新开始页面计数
// document.ResetPageCount();
for (int i = ; i < ; 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) / , (PageSize.A4.Height - img.ScaledHeight) / );
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();
float width = psize.Width;
float height = psize.Height;
// 创建一个文档变量
Document document = new Document(psize, , , , );
// 创建该文档
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:\Read.pdf", FileMode.Create));
// 打开文档
document.Open();
// 添加内容
PdfContentByte cb = writer.DirectContent;
int i = ;
int p = ;
Console.WriteLine("一共有 " + n + " 页.");
while (i < n)
{
document.NewPage();
p++;
i++;
PdfImportedPage page1 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page1, .5f, , , .5f, , height / );
Console.WriteLine("处理第 " + i + " 页");
if (i < n)
{
i++;
PdfImportedPage page2 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page2, .5f, , , .5f, width / , height / );
Console.WriteLine("处理第 " + i + " 页");
}
if (i < n)
{
i++;
PdfImportedPage page3 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page3, .5f, , , .5f, , );
Console.WriteLine("处理第 " + i + " 页");
}
if (i < n)
{
i++;
PdfImportedPage page4 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page4, .5f, , , .5f, width / , );
Console.WriteLine("处理第 " + i + " 页");
}
cb.SetRGBColorStroke(, , );
cb.MoveTo(, height / );
cb.LineTo(width, height / );
cb.Stroke();
cb.MoveTo(width / , height);
cb.LineTo(width / , );
cb.Stroke();
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(bf, );
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / ) + (n % > ? : )), width / , , );
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();
for (int i = ; i < ; i++)
{
PdfPCell cell = new PdfPCell(new Phrase("Cell " + i + "colspan 4 rowspan 1"));
// 单元格占的列数,5列
cell.Colspan = ;
// 单元格占的行数,3行
cell.Rowspan = ;
// 边框
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="" Width="">
<Grid>
<Button Content="创建文本" Height="" HorizontalAlignment="Left" Margin="38,268,0,0" Name="button1" VerticalAlignment="Top" Width="" Click="btnText_Click" />
<Button Content="创建表格" Height="" HorizontalAlignment="Left" Margin="266,0,0,20" Name="button2" VerticalAlignment="Bottom" Width="" Click="btnTable_Click" />
<Button Content="创建图片" Height="" HorizontalAlignment="Left" Margin="379,268,0,0" Name="button3" VerticalAlignment="Top" Width="" Click="btnImage_Click" />
<Button Content="读取PDF" Height="" HorizontalAlignment="Left" Margin="151,0,0,20" Name="button4" VerticalAlignment="Bottom" Width="" Click="btnRead_Click" />
<Label Content="Hello,Welcome to use" Height="" HorizontalAlignment="Center" Margin="23,24,0,0" Name="label1" VerticalAlignment="Top" Width="" ToolTip="Hello,Welcome to use" FontSize="" FontWeight="Bold" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" SnapsToDevicePixels="True" />
</Grid>
</Window>
参考资料:
2. 其它资料
https://wenku.baidu.com/view/032eb56aaf1ffc4ffe47ac1d.html