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

轉載于:https://www.cnblogs.com/wisdo/p/9354122.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/249907.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/249907.shtml
英文地址,請注明出處:http://en.pswp.cn/news/249907.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

正則基礎知識

創建正則表達式 1.使用new來創建 var exp new RegExp(box , gi );g 全局匹配 i 忽略大小寫 m 多行匹配2.使用字面量 var exp /box/gi; 直接用2個 / ; 在倆個斜杠后加上模式修飾符&#xff1b; 倆種創建方式比較: 1.使用字面量方式創建用的更加廣泛; 2.當要匹配的內容是變量時,…

詳解 vue-cli 的打包配置文件代碼

一、前言 對于webpack基礎不好&#xff0c;node指令不通的童鞋。估計對自己搭建Vue、react腳手架是相當頭疼的&#xff0c;有種無從下手的感覺。然而&#xff0c;從頭看這2塊&#xff0c;耗時太長&#xff0c;而且說實話得練才行&#xff0c;不練練手看不明白。那大多數人就采…

室內定位(一)

轉自&#xff1a;http://www.cnblogs.com/rubbninja/ 各種室內定位方法 具體的室內無線定位技術可以這樣來分類&#xff1a; 無線設備&#xff1a;WIFI、藍牙、ZigBee、RFID、UWB、LED、紅外線、超聲波、麥克風等定位信息&#xff1a;主要是RSS&#xff08;接收信號強度&#x…

不同瀏覽器css引入外部字體的方式

/*** 字體后綴和瀏覽器有關&#xff0c;如下所示* .TTF或.OTF&#xff0c;適用于Firefox 3.5、Safari、Opera * .EOT&#xff0c;適用于Internet Explorer 4.0 * .SVG&#xff0c;適用于Chrome、IPhone * 比如:*/ font-face {font-family: MyFont;/*定義字體名稱*/src: url(fon…

Promise實踐

var doSomething function() { return new Promise((resolve, reject) > { resolve(返回值); }); };let doSomethingElse function() { return 新的值; }doSomething().then(function () { return doSomethingElse(); }).then(resp > { console.warn(resp); console.wa…

JsonBuilder初出茅廬

互聯網這股東風不久前刮到了甘涼國&#xff0c;國王老甘獨具慧眼&#xff0c;想趕緊趁著東風未停大力發展移動互聯網&#xff0c;因為他篤信布斯雷的理論&#xff1a;“站在風口上&#xff0c;豬都能飛起來”。無奈地方偏僻落后&#xff0c;國內無可用之才啊。老甘一籌莫展的低…

vue-cli 打包部署

1、一般打包 &#xff1a;直接 npm run build。&#xff08;webpack的文件&#xff0c;根據不同的命令&#xff0c;執行不同的代碼的&#xff09; 注&#xff1a;這種打包的靜態文件&#xff0c;只能放在web服務器中的根目錄下才能運行。 2、在服務器中 非根目錄下 運行的 打包…

EXCEL怎么打20位以上的數字?

EXCEL怎么打20位以上的數字&#xff1f; 轉載于:https://www.cnblogs.com/macT/p/10208794.html

vue render函數

Vue中的Render渲染函數 VUE一般使用template來創建HTML&#xff0c;然后在有的時候&#xff0c;我們需要使用javascript來創建html&#xff0c;這時候我們需要使用render函數。比如如下我想要實現如下html&#xff1a; <div id"container"><h1><a hre…

Nexus介紹

轉自&#xff1a;https://www.cnblogs.com/wincai/p/5599282.html 開始在使用Maven時&#xff0c;總是會聽到nexus這個詞&#xff0c;一會兒maven&#xff0c;一會兒nexus&#xff0c;當時很是困惑&#xff0c;nexus是什么呢&#xff0c;為什么它總是和maven一起被提到呢&#…

vue-cli 打包

一項目打包 1 打包的配置在 build/webpack.base.conf.js文件下 常量config在vue/config/index.js 文件下配置&#xff0c;__dirname是定義在項目的全局變量&#xff0c;是當前文件所在項目的文件夾的絕對路徑。 2 需要修改vue/config/index.js 文件下的將build對象下的assets…

乘風破浪:LeetCode真題_010_Regular Expression Matching

乘風破浪&#xff1a;LeetCode真題_010_Regular Expression Matching 一、前言 關于正則表達式我們使用得非常多&#xff0c;但是如果讓我們自己寫一個&#xff0c;卻是有非常大的困難的&#xff0c;我們可能想到狀態機&#xff0c;確定&#xff0c;非確定狀態機確實是一種解決…

python——獲取數據類型

在python中&#xff0c;可使用type()和isinstance()內置函數獲取數據類型 如&#xff1a; &#xff08;1&#xff09;type()的使用方法&#xff1a;    >>> a 230 >>> type(a) <class str> >>> a 230 …

vue項目工程中npm run dev 到底做了什么

npm install 安裝了webpack框架中package.json中所需要的依賴 2.安裝完成之后&#xff0c;需要啟動整個項目運行&#xff0c;npm run 其實執行了package.json中的script腳本&#xff0c;npm run dev的執行如下 3.底層相當執行webpack-dev-server --inline --progress --confi…

JavaScript回顧與學習——條件語句

一、if...else // if elsevar age 16;if(0 < age && age < 6){console.log("兒童");}else if(6 < age && age < 14){console.log("少年");}else if(14 < age && age < 35){console.log("青年");}els…

bat等大公司常考java多線程面試題

1、說說進程,線程,協程之間的區別 簡而言之,進程是程序運行和資源分配的基本單位,一個程序至少有一個進程,一個進程至少有一個線程.進程在執行過程中擁有獨立的內存單元,而多個線程共享內存資源,減少切換次數,從而效率更高.線程是進程的一個實體,是cpu調度和分派的基本單位,是比…

webpack.config.js和package.json

webpack.config.js 是webpakc的配置文件&#xff0c;webpack是當今很火的一個打包工具 使用webpack.config.js在你的項目里 可以對你的項目進行模塊化打包&#xff0c;并且也可使組件按需加載&#xff0c;還可將圖片變成base64格式減少網絡請求。 而package.json 是指你項目的…

七牛云圖片加載優化

?imageView2/2/w/80https://developer.qiniu.com/dora/manual/1279/basic-processing-images-imageview2 ?imageView2/1/w/80/h/80會裁剪 ?imageView2/3/w/80/h/80不會裁剪 轉載于:https://www.cnblogs.com/smzd/p/9025393.html

org.apache.maven.archiver.mavenarchiver.getmanifest怎么解決

原因就是你的maven的配置文件不是最新的 1.help ->Install New Software -> add ->https://otto.takari.io/content/sites/m2e.extras/m2eclipse-mavenarchiver/0.17.2/N/LATEST 或者&#xff08;更新于2018年4月18日17:07:53&#xff09; http://repo1.maven.org/mav…

npm中package.json詳解

通常我們使用npm init命令來創建一個npm程序時&#xff0c;會自動生成一個package.json文件。package.json文件會描述這個NPM包的所有相關信息&#xff0c;包括作者、簡介、包依賴、構建等信息&#xff0c;格式是嚴格的JSON格式。 常用命令 npm i --save packageName 安裝依賴…