如何使用C#將圖像轉換為PDF【程式碼範例教程】
從PDF文件中提取結構化表格資料是C#開發人員的常見需求,這對於資料分析、報告或整合資訊到其他系統中至關重要。 然而,PDF主要設計為一致的視覺呈現,而非直接的資料提取。 這可能使以C#程式化地從PDF文件中讀取表格成為一項具有挑戰性的任務,特別是表格的形式可以差異很大——從簡單的文字基地的網格到具有合併單元格的複雜佈局,甚至是嵌入在掃描文件中的圖像表格。
本指南提供了一個全面的C#教程,說明如何使用IronPDF進行PDF表格提取。 我們將主要探索利用IronPDF強大的文字提取能力來存取然後解析來自基於文字的PDF的表格資料。 我們將討論此方法的有效性,提供解析策略,並對處理提取的資訊提供見解。 此外,我們還將觸及更複雜情境(如掃描PDF)的處理策略。
從PDF中提取表格資料到C#的關鍵步驟
- 安裝IronPDF C#程式庫(https://nuget.org/packages/IronPdf/)以進行PDF處理。
- (選擇性展示步驟)使用IronPDF的
RenderHtmlAsPdf從HTML字串建立一個帶有表格的範例PDF。 (見部分:(展示步驟)建立一個具有表格資料的PDF文件) - 載入任何PDF文件並使用
ExtractAllText方法檢索其原始文字內容。 (See section: Extract All Text Containing Table Data from the PDF) - 實施C#邏輯以解析提取的文字並識別表格行和單元格。 (See section: Parsing Extracted Text to Reconstruct Table Data in C#)
- 輸出結構化的表格資料或將其保存為CSV文件以便進一步使用。 (See section: Parsing Extracted Text to Reconstruct Table Data in C#)
- 考慮高級技術,例如處理掃描PDF的OCR(稍後討論)。
IronPDF - C# PDF程式庫
IronPDF是針對.NET中的PDF操作的C# .NET程式庫解決方案(https://ironpdf.com/),它幫助開發者在其軟體應用中輕鬆閱讀、建立和編輯PDF文件。 其強大的Chromium引擎能夠從HTML高精確度和快速地呈現PDF文件。 它允許開發者無縫地將不同格式轉換為PDF及相反過程。 它支持包括.NET 7、.NET 6、5、4、.NET Core和Standard在內的最新.NET框架。
此外,IronPDF .NET API還能讓開發者操作和編輯PDF,新增頁眉和頁腳,重要的是,輕鬆提取文字、圖像以及(如我們將看到的)從PDF中提取表格資料。
一些重要功能包括:
在C#中使用IronPDF程式庫提取表格資料的步驟
為了從PDF文件中提取表格資料,我們將設置一個C#專案:
- Visual Studio:確保您已安裝Visual Studio(例如,2022)。 如果沒有,請從Visual Studio網站下載(https://visualstudio.microsoft.com/downloads/)。
-
建立專案:
-
打開Visual Studio 2022並點擊建立新專案。
Visual Studio的開始介面 -
選擇"控制台應用"(或您偏好的C#專案型別)並點擊下一步。
在Visual Studio中建立新的控制台應用程式 -
為您的專案命名(例如,"ReadPDFTableDemo")並點擊下一步。
配置新建立的應用程式 -
選擇您需要的.NET Framework(例如,.NET 6或更高版本)。
選擇.NET Framework - 點擊建立。 將會建立控制台專案。
-
-
安裝IronPDF:
-
使用Visual Studio NuGet包管理器:
- 在Solution Explorer中右鍵點擊您的專案並選擇"管理NuGet軟體包..."
工具及管理NuGet軟體包- 在NuGet包管理器中,搜索"IronPDF"並點擊"安裝"。
工具及管理NuGet軟體包
- 直接下載NuGet包:存取IronPDF的NuGet包頁面(https://www.nuget.org/packages/IronPdf/)。
- 下載IronPDF .DLL程式庫:從官方IronPDF網站下載並在您的專案中引用該DLL。
-
(展示步驟)建立一個具有表格資料的PDF文件
在本教程中,我們將首先從HTML字串建立一個包含簡單表格的範例PDF。 這為我們提供了一個已知的PDF結構來示範提取過程。 在實際情境中,您會載入您已有的PDF文件。
新增IronPDF命名空間並選擇性地設置您的授權金鑰(IronPDF對於開發是免費的,但商業部署需要授權以去除浮水印):
using IronPdf;
using System; // For StringSplitOptions, Console
using System.IO; // For StreamWriter
// Apply your license key if you have one. Otherwise, IronPDF runs in trial mode.
// License.LicenseKey = "YOUR-TRIAL/PURCHASED-LICENSE-KEY";
using IronPdf;
using System; // For StringSplitOptions, Console
using System.IO; // For StreamWriter
// Apply your license key if you have one. Otherwise, IronPDF runs in trial mode.
// License.LicenseKey = "YOUR-TRIAL/PURCHASED-LICENSE-KEY";
Imports IronPdf
Imports System ' For StringSplitOptions, Console
Imports System.IO ' For StreamWriter
' Apply your license key if you have one. Otherwise, IronPDF runs in trial mode.
' License.LicenseKey = "YOUR-TRIAL/PURCHASED-LICENSE-KEY";
這是我們範例表格的HTML字串:
string HTML = "<html>" +
"<style>" +
"table, th, td {" +
"border:1px solid black;" +
"}" +
"</style>" +
"<body>" +
"<h1>A Simple table example</h1>" + // Corrected typo: h1 not h2
"<table>" +
"<tr>" +
"<th>Company</th>" +
"<th>Contact</th>" +
"<th>Country</th>" +
"</tr>" +
"<tr>" +
"<td>Alfreds Futterkiste</td>" +
"<td>Maria Anders</td>" +
"<td>Germany</td>" +
"</tr>" +
"<tr>" +
"<td>Centro comercial Moctezuma</td>" +
"<td>Francisco Chang</td>" +
"<td>Mexico</td>" +
"</tr>" +
"</table>" +
"<p>To understand the example better, we have added borders to the table.</p>" +
"</body>" +
"</html>";
string HTML = "<html>" +
"<style>" +
"table, th, td {" +
"border:1px solid black;" +
"}" +
"</style>" +
"<body>" +
"<h1>A Simple table example</h1>" + // Corrected typo: h1 not h2
"<table>" +
"<tr>" +
"<th>Company</th>" +
"<th>Contact</th>" +
"<th>Country</th>" +
"</tr>" +
"<tr>" +
"<td>Alfreds Futterkiste</td>" +
"<td>Maria Anders</td>" +
"<td>Germany</td>" +
"</tr>" +
"<tr>" +
"<td>Centro comercial Moctezuma</td>" +
"<td>Francisco Chang</td>" +
"<td>Mexico</td>" +
"</tr>" +
"</table>" +
"<p>To understand the example better, we have added borders to the table.</p>" +
"</body>" +
"</html>";
現在,使用ChromePdfRenderer從此HTML建立PDF:
var renderer = new ChromePdfRenderer();
PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(HTML);
pdfDocument.SaveAs("table_example.pdf");
Console.WriteLine("Sample PDF 'table_example.pdf' created.");
var renderer = new ChromePdfRenderer();
PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(HTML);
pdfDocument.SaveAs("table_example.pdf");
Console.WriteLine("Sample PDF 'table_example.pdf' created.");
Dim renderer = New ChromePdfRenderer()
Dim pdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(HTML)
pdfDocument.SaveAs("table_example.pdf")
Console.WriteLine("Sample PDF 'table_example.pdf' created.")
SaveAs方法會保存PDF。 生成的table_example.pdf看起來像這樣(基於HTML的概念圖):
在NuGet套件管理器UI中搜索IronPDF
提取包含表格資料的所有文字從PDF中
要提取表格資料,我們首先載入PDF(無論是剛建立的還是已有的PDF),然後使用ExtractAllText方法。 此方法可取回所有PDF頁面中的文字內容。
// Load the PDF (if you just created it, it's already loaded in pdfDocument)
// If loading an existing PDF:
// PdfDocument pdfDocument = PdfDocument.FromFile("table_example.pdf");
// Or use the one created above:
string allText = pdfDocument.ExtractAllText();
// Load the PDF (if you just created it, it's already loaded in pdfDocument)
// If loading an existing PDF:
// PdfDocument pdfDocument = PdfDocument.FromFile("table_example.pdf");
// Or use the one created above:
string allText = pdfDocument.ExtractAllText();
' Load the PDF (if you just created it, it's already loaded in pdfDocument)
' If loading an existing PDF:
' PdfDocument pdfDocument = PdfDocument.FromFile("table_example.pdf");
' Or use the one created above:
Dim allText As String = pdfDocument.ExtractAllText()
allText變數現在持有從PDF中取出的整個文字內容。 您可以顯示它以查看原始提取:
Console.WriteLine("\n--- Raw Extracted Text ---");
Console.WriteLine(allText);
Console.WriteLine("\n--- Raw Extracted Text ---");
Console.WriteLine(allText);
Imports Microsoft.VisualBasic
Console.WriteLine(vbLf & "--- Raw Extracted Text ---")
Console.WriteLine(allText)
要提取文字的PDF文件
解析提取的文字以重構C#中的表格資料
有了提取的原始文字,接下來的挑戰是解析此字串以識別並結構化表格資料。 這一步驟非常依賴於您PDF中表格的格式和一致性。
一般解析策略:
- 識別行分隔符:換行符(
\r\n)是常見的行分隔符。 - 識別列分隔符:行中的單元可能由多個空格、製表符或特定已知字元分隔(如"|'或';')。 有時,如果列是視覺上對齊而缺乏清晰的文字分隔符,您可能基於一致的空格模式推斷結構,儘管這更為複雜。
- 過濾非表格內容:
ExtractAllText方法取得了所有的文字。 您需要邏輯去分離實際構成表格的文字,可以通過尋找標題關鍵字或跳過前導/後導文字實現。
C#的String.Split方法是一個基本的工具來達成此目的。 這裡有個例子,嘗試將我們的樣本僅抽取表格行,過濾掉含有句號的行(對此特定例子的簡單啟發式方法):
Console.WriteLine("\n--- Parsed Table Data (Simple Heuristic) ---");
string[] textLines = allText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in textLines)
{
// Simple filter: skip lines with a period, assuming they are not table data in this example
// and skip lines that are too short or headers if identifiable
if (line.Contains(".") || line.Contains("A Simple table example") || line.Length < 5)
{
continue;
}
else
{
// Further split line into cells based on expected delimiters (e.g., multiple spaces)
// This part requires careful adaptation to your PDF's table structure
// Example: string[] cells = line.Split(new[] { " ", "\t" }, StringSplitOptions.None);
Console.WriteLine(line); // For now, just print the filtered line
}
}
Console.WriteLine("\n--- Parsed Table Data (Simple Heuristic) ---");
string[] textLines = allText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in textLines)
{
// Simple filter: skip lines with a period, assuming they are not table data in this example
// and skip lines that are too short or headers if identifiable
if (line.Contains(".") || line.Contains("A Simple table example") || line.Length < 5)
{
continue;
}
else
{
// Further split line into cells based on expected delimiters (e.g., multiple spaces)
// This part requires careful adaptation to your PDF's table structure
// Example: string[] cells = line.Split(new[] { " ", "\t" }, StringSplitOptions.None);
Console.WriteLine(line); // For now, just print the filtered line
}
}
Imports Microsoft.VisualBasic
Console.WriteLine(vbLf & "--- Parsed Table Data (Simple Heuristic) ---")
Dim textLines() As String = allText.Split( { ControlChars.Cr, ControlChars.Lf }, StringSplitOptions.RemoveEmptyEntries)
For Each line As String In textLines
' Simple filter: skip lines with a period, assuming they are not table data in this example
' and skip lines that are too short or headers if identifiable
If line.Contains(".") OrElse line.Contains("A Simple table example") OrElse line.Length < 5 Then
Continue For
Else
' Further split line into cells based on expected delimiters (e.g., multiple spaces)
' This part requires careful adaptation to your PDF's table structure
' Example: string[] cells = line.Split(new[] { " ", "\t" }, StringSplitOptions.None);
Console.WriteLine(line) ' For now, just print the filtered line
End If
Next line
此程式碼將文字分成行。 if條件是針對這個特定例子的非表格文字的非常基本的過濾器。 在實際世界的情境中,您需要更強健的邏輯來準確識別和解析表格行和單元格。
簡單過濾文字的輸出:
主控台顯示提取的文字
關於文字解析方法的重要考慮:
- 最適合:文字基地的PDF,具有簡單、一致的表格結構和明確的文字分隔符。
- 限制:此方法可能在以下情況中苦難:
- 具有合併單元格或複雜巢狀結構的表格。
- 列是由視覺間隔而非文字分隔定義的表格。
- 嵌入為圖像的表格(需要OCR)。
- 不同的PDF生成導致不一致的文字抽取順序。
您可將過濾後的行(通常代表表格行)保存到CSV文件中。
using (StreamWriter file = new StreamWriter("parsed_table_data.csv", false))
{
file.WriteLine("Company,Contact,Country"); // Write CSV Header
foreach (string line in textLines)
{
if (line.Contains(".") || line.Contains("A Simple table example") || line.Length < 5)
{
continue;
}
else
{
// For a real CSV, you'd split 'line' into cells and join with commas
// E.g., string[] cells = line.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
// string csvLine = string.Join(",", cells);
// file.WriteLine(csvLine);
file.WriteLine(line.Replace(" ", ",").Trim()); // Basic replacement for this example
}
}
}
Console.WriteLine("\nFiltered table data saved to parsed_table_data.csv");
using (StreamWriter file = new StreamWriter("parsed_table_data.csv", false))
{
file.WriteLine("Company,Contact,Country"); // Write CSV Header
foreach (string line in textLines)
{
if (line.Contains(".") || line.Contains("A Simple table example") || line.Length < 5)
{
continue;
}
else
{
// For a real CSV, you'd split 'line' into cells and join with commas
// E.g., string[] cells = line.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
// string csvLine = string.Join(",", cells);
// file.WriteLine(csvLine);
file.WriteLine(line.Replace(" ", ",").Trim()); // Basic replacement for this example
}
}
}
Console.WriteLine("\nFiltered table data saved to parsed_table_data.csv");
Imports Microsoft.VisualBasic
Using file As New StreamWriter("parsed_table_data.csv", False)
file.WriteLine("Company,Contact,Country") ' Write CSV Header
For Each line As String In textLines
If line.Contains(".") OrElse line.Contains("A Simple table example") OrElse line.Length < 5 Then
Continue For
Else
' For a real CSV, you'd split 'line' into cells and join with commas
' E.g., string[] cells = line.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
' string csvLine = string.Join(",", cells);
' file.WriteLine(csvLine);
file.WriteLine(line.Replace(" ", ",").Trim()) ' Basic replacement for this example
End If
Next line
End Using
Console.WriteLine(vbLf & "Filtered table data saved to parsed_table_data.csv")
在C#中對更複雜PDF表格提取的策略
從複雜或圖像基礎的PDF表格中提取資料通常需要比簡單的文字解析更高階的技術。 IronPDF提供的功能可幫助您:
- 使用IronOCR功能處理掃描表格:若表格處在影像中(例如,掃描的PDFs),單靠
ExtractAllText()無法取得它們。 IronOCR的文字檢測功能可以首先將這些圖像轉換為文字。
// Conceptual OCR usage (refer to IronOCR's documentation for detailed implementation)
// Install Package IronOcr
using IronOcr;
using (var ocrInput = new OcrInput("scanned_pdf_with_table.pdf"))
{
ocrInput.TargetDPI = 300; // Good DPI for OCR accuracy
var ocrResult = new IronOcr().Read(ocrInput);
string ocrExtractedText = ocrResult.Text;
// Now, apply parsing logic to 'ocrExtractedText'
Console.WriteLine("\n--- OCR Extracted Text for Table Parsing ---");
Console.WriteLine(ocrExtractedText);
}
// Conceptual OCR usage (refer to IronOCR's documentation for detailed implementation)
// Install Package IronOcr
using IronOcr;
using (var ocrInput = new OcrInput("scanned_pdf_with_table.pdf"))
{
ocrInput.TargetDPI = 300; // Good DPI for OCR accuracy
var ocrResult = new IronOcr().Read(ocrInput);
string ocrExtractedText = ocrResult.Text;
// Now, apply parsing logic to 'ocrExtractedText'
Console.WriteLine("\n--- OCR Extracted Text for Table Parsing ---");
Console.WriteLine(ocrExtractedText);
}
' Conceptual OCR usage (refer to IronOCR's documentation for detailed implementation)
' Install Package IronOcr
Imports Microsoft.VisualBasic
Imports IronOcr
Using ocrInput As New OcrInput("scanned_pdf_with_table.pdf")
ocrInput.TargetDPI = 300 ' Good DPI for OCR accuracy
Dim ocrResult = (New IronOcr()).Read(ocrInput)
Dim ocrExtractedText As String = ocrResult.Text
' Now, apply parsing logic to 'ocrExtractedText'
Console.WriteLine(vbLf & "--- OCR Extracted Text for Table Parsing ---")
Console.WriteLine(ocrExtractedText)
End Using
有關詳細的指導,請存取IronOCR文件(https://ironsoftware.com/csharp/ocr/)。 進行OCR之後,您可以解析產生的文字字串。
-
基於座標的文字提取(進階):雖然IronPDF的
ExtractAllText()供應了文字流,但某些情況下獲取每個文字段的x,y位置可能更具優勢。 如果IronPDF提供API以獲得文字及其邊界框資訊(請參閱當前文件),可以基於視覺對齊進行更複雜的空間解析以重構表格。 - PDF轉換為其他格式:IronPDF能將PDF轉為結構化格式如HTML。 通常,解析HTML表格比原始PDF文字更為簡單。
PdfDocument pdfToConvert = PdfDocument.FromFile("your_document.pdf");
string htmlOutput = pdfToConvert.ToHtmlString();
// Then use an HTML parsing library (e.g., HtmlAgilityPack) to extract tables from htmlOutput.
PdfDocument pdfToConvert = PdfDocument.FromFile("your_document.pdf");
string htmlOutput = pdfToConvert.ToHtmlString();
// Then use an HTML parsing library (e.g., HtmlAgilityPack) to extract tables from htmlOutput.
Dim pdfToConvert As PdfDocument = PdfDocument.FromFile("your_document.pdf")
Dim htmlOutput As String = pdfToConvert.ToHtmlString()
' Then use an HTML parsing library (e.g., HtmlAgilityPack) to extract tables from htmlOutput.
- 模式識別與正則表達式:對於具有非常可預測模式但分隔符不一致的表格,應用於提取文字的複雜正則表達式有時能分離出表格資料。
選擇正確的策略取決於您的原始PDF的複雜性和一致性。 對於許多常見商務文件上的文字基地表格,IronPDF的ExtractAllText與智能C#解析邏輯結合是非常有效的。而對於基於圖像的表格而言,其OCR功能是必不可少的。
總結
本文展示了如何使用IronPDF在C#中從PDF文件提取表格資料,主要關注於利用ExtractAllText()方法和後續的字串解析。 我們了解到,儘管此方法對基於文字的表格非常強大,但像圖片基礎的表格一樣的更為複雜的情況,可以使用IronPDF的OCR功能或先將PDF轉換為其他格式來解決。
IronPDF為.NET開發人員提供了一個多功能的工具包,簡化了許多PDF相關任務,從建立和編輯到全面的資料提取。 它提供了ExtractTextFromPage等方法來進行頁面指定的提取,並支持從格式如markdown或DOCX轉換為PDF。
IronPDF在開發中是免費的,並提供了免費試用授權以測試其全部商業功能。 對於生產部署,提供了多種授權選項。
更多詳情和高級使用例探索官方IronPDF文件和例子(https://ironpdf.com/)
常見問題
如何以程式化方式在C#中從PDF文件讀取表格?
您可以使用IronPDF的`ExtractAllText`方法從PDF文件中提取原始文字。提取後,您可以在C#中解析此文字以識別表格行和單元格,從而實現結構化資料提取。
使用C#從PDF中提取表格資料涉及哪些步驟?
該過程包括安裝IronPDF程式庫,使用`ExtractAllText`方法檢索文字,解析此文字以識別表格,並可選將結構化資料保存為CSV格式。
如何用C#處理包含表格的掃描PDF文件?
對於掃描PDF,IronPDF可以利用OCR(光學字元識別)將表格圖像轉換為文字,然後可以解析以提取表格資料。
IronPDF可以將PDF轉換為其他格式以便於表格提取嗎?
可以。IronPDF可以將PDF轉換為HTML,這可以通過允許開發人員使用HTML解析技術來簡化表格提取。
IronPDF適合從複雜PDF表格中提取資料嗎?
IronPDF提供了OCR和基於座標的文字提取等高級功能,可以用於處理包括合併單元格或不一致分隔符的複雜表格布局。
如何將IronPDF整合到.NET Core應用程式中?
IronPDF相容.NET Core應用程式。您可以通過Visual Studio中的NuGet套件管理器安裝該程式庫來整合它。
在C#中使用IronPDF進行PDF操作的好處是什麼?
IronPDF提供了多種功能,用於建立、編輯和從PDF中提取資料,包括對OCR的支持和轉換為多種格式,這使得它成為.NET開發者的強大工具。
從PDF中提取表格資料時常見的挑戰是什麼?
挑戰包括處理複雜的表格布局,例如合併單元格、作為圖像嵌入的表格以及不一致的分隔符,這可能需要高級解析策略或OCR。
如何開始使用IronPDF進行PDF處理?
首先通過NuGet套件管理器安裝IronPDF程式庫或從IronPDF網站下載。此設置對於在您的C#項目中利用其PDF處理功能至關重要。
使用IronPDF是否需要授權?
IronPDF對於開發用途是免費的,但商業部署需要授權以去除水印。有免費試用授權可供測試其完整功能。
IronPDF在從PDF中提取表格時是否相容.NET 10?
是的。IronPDF支持.NET 10(以及.NET 9、8、7、6、Core、Standard和Framework),因此所有表格提取功能在.NET 10應用程式中無需修改即可使用。




