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 {/// <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/