.NET操作PDF的完整指南
本文將通過(guò)真實(shí)項(xiàng)目案例,手把手教你:
- 用iTextSharp實(shí)現(xiàn)高效讀寫(xiě)PDF
- 用PDFsharp完成跨平臺(tái)PDF生成
- 用PdfiumViewer實(shí)現(xiàn)無(wú)插件PDF預(yù)覽
- 用PDFiumCore處理復(fù)雜PDF渲染
- 避坑指南:內(nèi)存泄漏、權(quán)限異常、性能瓶頸的解決方案
第一章:iTextSharp——PDF操作的瑞士軍刀
1.1 讀取PDF文本內(nèi)容
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
public class PdfReaderExample
{
/// <summary>
/// 提取PDF指定頁(yè)面的文本
/// <param name="filePath">PDF文件路徑</param>
/// <param name="pageNumber">頁(yè)碼(從1開(kāi)始)</param>
/// <returns>提取的文本內(nèi)容</returns>
public string ExtractText(string filePath, int pageNumber)
{
// 使用using確保資源釋放
using (PdfReader reader = new PdfReader(filePath))
{
// 調(diào)用PDF解析器提取文本
return PdfTextExtractor.GetTextFromPage(reader, pageNumber);
}
}
// 示例:提取第1頁(yè)文本
public void ExampleUsage()
{
string text = ExtractText("example.pdf", 1);
Console.WriteLine("提取的文本:\n" + text);
}
}
關(guān)鍵點(diǎn):
PdfReader會(huì)自動(dòng)釋放底層資源,避免內(nèi)存泄漏。- 通過(guò)
GetTextFromPage方法,可靈活提取任意頁(yè)碼內(nèi)容。
1.2 創(chuàng)建動(dòng)態(tài)PDF文檔
using iTextSharp.text;
using iTextSharp.text.pdf;
public class PdfWriterExample
{
/// <summary>
/// 生成包含表格的PDF
/// </summary>
public void GenerateInvoice(string outputPath)
{
// 創(chuàng)建文檔對(duì)象并指定頁(yè)面大小
Document document = new Document(PageSize.A4);
// 使用try-catch確保異常時(shí)資源釋放
try
{
// 將文檔綁定到輸出流
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
// 打開(kāi)文檔
document.Open();
// 添加標(biāo)題
document.Add(new Paragraph("發(fā)票", new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD)));
// 創(chuàng)建表格(3列)
PdfPTable table = new PdfPTable(3);
table.WidthPercentage = 100; // 表格寬度占滿頁(yè)面
// 添加表頭
table.AddCell("商品");
table.AddCell("數(shù)量");
table.AddCell("單價(jià)");
// 添加數(shù)據(jù)行
table.AddCell("筆記本");
table.AddCell("5");
table.AddCell("$10");
// 添加表格到文檔
document.Add(table);
// 添加頁(yè)腳
document.Add(new Paragraph("\n感謝惠顧!"));
}
catch (Exception ex)
{
Console.WriteLine("生成PDF失?。? + ex.Message);
}
finally
{
// 關(guān)閉文檔(無(wú)論是否成功)
if (document.IsOpen())
{
document.Close();
}
}
}
}
關(guān)鍵點(diǎn):
- 使用
PdfPTable創(chuàng)建復(fù)雜的表格結(jié)構(gòu)。 - 通過(guò)
try-catch-finally確保資源正確釋放。
第二章:PDFsharp——跨平臺(tái)PDF操作利器
2.1 創(chuàng)建帶圖標(biāo)的PDF
using PdfSharp.Drawing;
using PdfSharp.Pdf;
public class PdfSharpExample
{
/// <summary>
/// 生成包含圖像和圖形的PDF
/// </summary>
public void CreatePdfWithGraphics(string outputPath)
{
// 創(chuàng)建PDF文檔
PdfDocument document = new PdfDocument();
document.Info.Title = "PDFsharp示例";
// 添加頁(yè)面
PdfPage page = document.AddPage();
page.Width = XUnit.FromMillimeter(210); // A4寬度
page.Height = XUnit.FromMillimeter(297); // A4高度
// 獲取繪圖上下文
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Arial", 20, XFontStyle.Bold);
// 繪制文本
gfx.DrawString("歡迎使用PDFsharp!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// 繪制矩形
gfx.DrawRectangle(XPens.Blue, 50, 50, 100, 50);
// 插入圖片(需確保圖片路徑存在)
using (XImage image = XImage.FromFile("logo.png"))
{
gfx.DrawImage(image, 100, 150, 100, 100);
}
// 保存文檔
document.Save(outputPath);
}
}
關(guān)鍵點(diǎn):
XGraphics類提供豐富的繪圖API。- 支持直接插入圖像文件(需處理異常)。
第三章:PdfiumViewer——無(wú)插件PDF預(yù)覽解決方案
3.1 渲染PDF為圖像并保存
using PdfiumViewer;
using System.Drawing.Imaging;
public class PdfRendererExample
{
/// <summary>
/// 將PDF頁(yè)面渲染為PNG圖像
/// </summary>
public void RenderToImage(string inputPath, string outputImagePath, int pageNumber)
{
// 加載PDF文檔
using (var document = PdfDocument.Load(inputPath))
{
// 創(chuàng)建渲染器
var renderer = new PdfRenderer(document);
// 渲染指定頁(yè)面
using (var stream = new FileStream(outputImagePath, FileMode.Create))
{
// 指定輸出格式和分辨率
renderer.RenderToStream(pageNumber - 1, stream, ImageFormat.Png, 300); // 300dpi
}
}
}
}
關(guān)鍵點(diǎn):
PdfRenderer類支持多種圖像格式(PNG/JPG)。- 通過(guò)調(diào)整分辨率參數(shù)(如300dpi)平衡質(zhì)量和性能。
第四章:PDFiumCore——高效處理大型PDF
4.1 提取PDF文本并分析
using PDFiumCore;
using System.Text;
public class PdfiumCoreExample
{
/// <summary>
/// 提取PDF全文本并統(tǒng)計(jì)關(guān)鍵詞
/// </summary>
public void AnalyzePdf(string filePath)
{
// 初始化PDFium庫(kù)
fpdfview.FPDF_InitLibrary();
// 加載文檔
IntPtr document = fpdfview.FPDF_LoadDocument(filePath, null);
if (document == IntPtr.Zero)
{
Console.WriteLine("無(wú)法加載PDF文檔。");
return;
}
// 獲取總頁(yè)數(shù)
int pageCount = fpdfview.FPDF_GetPageCount(document);
StringBuilder fullText = new StringBuilder();
// 遍歷所有頁(yè)面
for (int i = 0; i < pageCount; i++)
{
IntPtr page = fpdfview.FPDF_LoadPage(document, i);
if (page != IntPtr.Zero)
{
// 提取文本
IntPtr textHandle = fpdfview.FPDFText_GetText(page, 0, 0);
if (textHandle != IntPtr.Zero)
{
string text = Marshal.PtrToStringAnsi(textHandle);
fullText.AppendLine(text);
}
fpdfview.FPDF_ClosePage(page);
}
}
// 關(guān)閉文檔并釋放資源
fpdfview.FPDF_CloseDocument(document);
fpdfview.FPDF_DestroyLibrary();
// 分析關(guān)鍵詞(示例:統(tǒng)計(jì)“合同”出現(xiàn)次數(shù))
int contractCount = fullText.ToString().Split("合同").Length - 1;
Console.WriteLine($"關(guān)鍵詞'合同'出現(xiàn)次數(shù):{contractCount}");
}
}
關(guān)鍵點(diǎn):
- 使用
FPDF_InitLibrary/FPDF_DestroyLibrary管理全局資源。 - 通過(guò)指針操作底層PDFium庫(kù),適合處理超大文件。
第五章:實(shí)戰(zhàn)案例——發(fā)票管理系統(tǒng)
5.1 功能需求
- 自動(dòng)生成發(fā)票P(pán)DF
- 合并多張發(fā)票為單個(gè)文件
- 提取發(fā)票關(guān)鍵字段(金額、日期)
5.2 代碼實(shí)現(xiàn):合并PDF文件
using iTextSharp.text.pdf;
public class InvoiceMerger
{
/// <summary>
/// 合并多個(gè)PDF文件
/// </summary>
public void MergeInvoices(string[] inputFiles, string outputFile)
{
using (PdfCopy copy = new PdfCopy(new Document(), new FileStream(outputFile, FileMode.Create)))
{
copy.Open();
foreach (string file in inputFiles)
{
using (PdfReader reader = new PdfReader(file))
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
copy.AddPage(copy.GetImportedPage(reader, i));
}
}
}
copy.Close();
}
}
}
關(guān)鍵點(diǎn):
- 使用
PdfCopy高效合并PDF。 - 通過(guò)循環(huán)遍歷確保所有頁(yè)面被正確導(dǎo)入。
第六章:避坑指南——常見(jiàn)問(wèn)題解決方案
6.1 內(nèi)存泄漏
現(xiàn)象:長(zhǎng)時(shí)間運(yùn)行后程序占用內(nèi)存飆升。
解決方案:
- 使用
using語(yǔ)句確保PdfReader、Document等資源釋放。 - 對(duì)于大文件,避免一次性加載全部?jī)?nèi)容。
6.2 權(quán)限異常
現(xiàn)象:UnauthorizedAccessException
解決方案:
- 檢查文件路徑是否有寫(xiě)入權(quán)限。
- 使用
FileAccess.ReadWrite模式打開(kāi)文件流。
6.3 性能瓶頸
現(xiàn)象:處理大PDF時(shí)CPU占用過(guò)高。
解決方案:
- 使用異步操作(如
Task.Run)。 - 啟用緩存機(jī)制減少重復(fù)計(jì)算。
選擇最適合的PDF工具
| 庫(kù)名稱 | 優(yōu)勢(shì) | 適用場(chǎng)景 |
|---|---|---|
| iTextSharp | 功能全面,社區(qū)活躍 | 企業(yè)級(jí)PDF處理 |
| PDFsharp | 跨平臺(tái),輕量級(jí) | 移動(dòng)端/嵌入式系統(tǒng) |
| PdfiumViewer | 渲染質(zhì)量高 | 預(yù)覽/圖像轉(zhuǎn)換 |
| PDFiumCore | 高效處理超大文件 | 大數(shù)據(jù)PDF分析 |
到此這篇關(guān)于.NET操作PDF的完整指南的文章就介紹到這了,更多相關(guān).NET操作PDF內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決Entity Framework中自增主鍵的問(wèn)題
這篇文章主要介紹了解決Entity Framework中自增主鍵的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-06-06
C#中調(diào)用Windows API的技術(shù)要點(diǎn)說(shuō)明
本篇文章主要是對(duì)C#中調(diào)用Windows API的技術(shù)要點(diǎn)進(jìn)行了詳細(xì)的介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-01-01
C# 創(chuàng)建文本文件寫(xiě)入讀取實(shí)現(xiàn)代碼
C# 創(chuàng)建文本文件寫(xiě)入讀取,可以用來(lái)做系統(tǒng)日志或程序操作日志或者錯(cuò)誤記錄,需要的朋友可以參考下。2011-11-11
C#實(shí)現(xiàn)簡(jiǎn)單屏幕監(jiān)控的方法
這篇文章主要介紹了C#實(shí)現(xiàn)簡(jiǎn)單屏幕監(jiān)控的方法,涉及C#的圖標(biāo)隱藏及屏幕截圖等技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04

