安装 iTextSharp: 可以通过 NuGet 包管理器安装 iTextSharp:
Install-Package itext7
创建 PDF 文件:
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;class Program
{static void Main(){string pdfPath = "example.pdf";// 创建 PDF 文档using (PdfWriter writer = new PdfWriter(pdfPath)){using (PdfDocument pdf = new PdfDocument(writer)){Document document = new Document(pdf);document.Add(new Paragraph("Hello, World!"));document.Close();}}Console.WriteLine("PDF created successfully!");}
}
读取 PDF 文件:
using System;
using iText.Kernel.Pdf;class Program
{static void Main(){string pdfPath = "example.pdf";// 读取 PDF 文档using (PdfReader reader = new PdfReader(pdfPath)){using (PdfDocument pdf = new PdfDocument(reader)){for (int i = 1; i <= pdf.GetNumberOfPages(); i++){var page = pdf.GetPage(i);Console.WriteLine($"Page {i}: {page.GetTextContent()}");}}}}
}