Trong quá trình làm project chúng ta cần phải export thông tin cần thiết ra tài liệu PDF - iTextSharp là một trong những thư viện hữu ích có thể tạo mới cũng như thao tác dễ dàng với tài liệu này.
Giới thiệu iTextSharp Library
iTextSharp là một thư viện mã nguồn mở cho phép tạo và thao tác với tài liệu PDF (Portable Document Format).
Gồm có hai version chính:
- Version chính cho Java.
- Version cho .NET được port từ Java sang.
Các tính năng chính:
- Tạo tài liệu và báo cáo từ file xml hay database.
- Tạo maps và books, khai thác các tính năng tương tác tới tài liệu PDF sẵn có.
- Thêm dấu trang, số trang, watermark, và các tính năng khác tới tài liệu PDF sẵn có.
- Chia tách hoặc ghép các trang từ các tập tin PDF sẵn có.
Cài đặt thư viện
Tiến hành tạo một Empty Project Console với ngôn ngữ C# bằng cách vào File → New → Project, chọn loại project là Console Application đặt tên là Stdio_iTextSharp
và nhấn OK để kết thúc.
Bài viết sẽ hướng dẫn 2 cách để có thể thêm bộ thư viện này vào project.
Cách 1
Để sử dụng bộ thư viện này đầu tiên cần download bộ thư viện này tại đây. Giải nén file vừa mới tải về thấy file itextSharp.dll.
Chuột phải vào References của project và chọn Add References... để mở hộp thoại Reference Manager → Stdio_iTextSharp
.
Nhấn Browser... vào tìm đến file itextSharp.dll vừa được giải nén ở trên.
Nhấn Add, sau đó nhấn OK để đóng hộp thoại References Manager - Stdio_iTextSharp.
Nếu thành công sẽ thấy hình như dưới đây:

Cách 2
Vào Tools → NuGet Package Manager → Package Manager Console để mở hộp thoại Package Manager Console:

Tại hộp thoại Package Manager Console copy đoạn text dưới đây và paste vào:
Install-Package iTextSharp

Nhấn Enter để Visual Stdio tự động download và cài đặt thư viện. Nếu thành công sẽ có kết quả tương tự cách 1.
Thao tác với tài liệu PDF
Để có thể thao tác với các lớp nằm trong trong bộ thư viện iTextSharp sử dụng trong project này cần using những thư viện cần thiết dưới đây.
using iTextSharp.text; using iTextSharp.text.pdf;
Tạo một tài liệu PDF
Các bước để tạo một tài liệu pdf với thư viện iTextSharp:
- Tạo một đối tượng Document.
- Get đối tượng PDFWriter với phương thức
PDFWriter.GetInstance()
. - Mở Document.
- Ghi nội dung xuống Document.
- Đóng Document.
static void Main(string[] args) { //Create a document object Document doc = new Document(); //get the current directory string path = Environment.CurrentDirectory; //get a PDFWriter object PdfWriter.GetInstance(doc, new FileStream(path + "/Stdio_iTextSharp_Demo.pdf", FileMode.Create)); //open the document for writting doc.Open(); //write a pharagrap to the document doc.Add(new Paragraph("Welcome you to Stdio.vn")); //close the document doc.Close(); Console.ReadLine(); }
Tại thư mục Stdio_iTextSharp\bin\Debug có một file Stdio_iTextSharp_Demo.pdf được tạo ra với nội dung "Welcome you to Stdio.vn
"
Có thể quy định kích thước cho tài liệu này bằng cách tạo đối tượng Rectangle
sau đó truyền đối tượng này vào hàm tạo của Document.
//create a rectangle object Rectangle rect = new Rectangle(100, 200); //Create a document object Document doc = new Document(rect);
Hoặc có thể chỉ định kích thước được định nghĩa sẵn bởi đối tượng PageSize
:
Document doc = new Document(PageSize.A4);
Ngoài ra còn có một số kích thước khác như A0, A1, A2, A3.
Thêm thông tin metadata
Khi tạo một tài liệu pdf, cần cung cấp những thông tin như author
, title
, subject
, keyworks
, producer
, ngày tạo
, ngày truy cập cuối cùng
, ngày sửa
để cho mọi người biết thông tin chi tiết của tài liệu này.
Những trường dữ liệu như vậy gọi là metadata của tài liệu PDF. iTextSharp có cung cấp sẵn những những phương thức như AddAuthor
, AddTittle
của đối tượng Document để có thể thêm metadata vào tài liệu.
static void Main(string[] args) { //Create a document object Document doc = new Document(); //get the current directory string path = Environment.CurrentDirectory; //get a PDFWriter object PdfWriter.GetInstance(doc, new FileStream(path + "/Stdio_iTextSharp_Demo.pdf", FileMode.Create)); //open the document for writting doc.Open(); //write a pharagrap to the document doc.Add(new Paragraph("Wellcome you to Stdio.vn")); //write Author metadata doc.AddAuthor("Nguyen Nghia"); //write title metadata doc.AddTitle("Demo Read PDF document using iTextSharp library in C#"); //write subject metadata doc.AddSubject("Read PDF document using iTextSharp library in C#"); //write keyworks metadata doc.AddKeywords("Stdio.vn"); //close the document doc.Close(); Console.ReadLine(); }
Và kết quả Properties
của tài liệu vừa mới tạo ra.

Lấy thông tin metadata
Metadata của tài liệu được lưu dưới dạng Dictionary<string, string>
. Có thể lấy metadata này thông qua Info
của đối tượng PDFReader.
PdfReader reader = new PdfReader(path + "/Stdio_iTextSharp_Demo.pdf"); Dictionary<string, string> metadata = reader.Info; foreach (KeyValuePair<string, string> item in metadata) { Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value); }
Kết quả:

Lấy toàn bộ text của tài liệu
iTextSharp cung cấp một class có tên là PdfTextExtractor
nằm trong namespace using iTextSharp.text.pdf.parser;
để có thể lấy toàn bộ text trong tài liệu.
StringBuilder content = new StringBuilder(); for (int i = 1; i <= reader.NumberOfPages; i++) { content.Append(PdfTextExtractor.GetTextFromPage(reader, i)); } Console.WriteLine(content.ToString());
Kết quả xuất ra sẽ là nội dung của tài liệu PDF: "Welcome you to Stdio.vn
"
Source demo
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; using iTextSharp.text.pdf.parser; namespace Stdio_iTextSharp { class Program { static void Main(string[] args) { //Create a document object Document doc = new Document(PageSize.A4); //get the current directory string path = Environment.CurrentDirectory; //get a PDFWriter object PdfWriter.GetInstance(doc, new FileStream(path + "/Stdio_iTextSharp_Demo.pdf", FileMode.Create)); //open the document for writting doc.Open(); //write a pharagrap to the document doc.Add(new Paragraph("Wellcome you to Stdio.vn")); //write Author metadata doc.AddAuthor("Nguyen Nghia"); //write title metadata doc.AddTitle("Demo Read PDF document using iTextSharp library in C#"); //write subject metadata doc.AddSubject("Read PDF document using iTextSharp library in C#"); //write keyworks metadata doc.AddKeywords("Stdio.vn"); //close the document doc.Close(); PdfReader reader = new PdfReader(path + "/Stdio_iTextSharp_Demo.pdf"); Dictionary<string, string> metadata = reader.Info; foreach (KeyValuePair<string, string> item in metadata) { Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value); } StringBuilder content = new StringBuilder(); for (int i = 1; i <= reader.NumberOfPages; i++) { content.Append(PdfTextExtractor.GetTextFromPage(reader, i)); } Console.WriteLine(content.ToString()); Console.ReadLine(); } } }