翻譯|使用教程|編輯:李顯亮|2021-06-11 11:08:02.203|閱讀 493 次
概述:在各種情況下,PDF用于生成數據以表格形式顯示的發票。在這種情況下,您可能需要解析 PDF 以編程方式從表中讀取數據。為此,本文介紹了如何使用 C# 從 PDF 表中提取數據。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
PDF已成為眾多領域中使用最廣泛的文檔格式之一。在各種情況下,它用于生成數據以表格形式顯示的發票。在這種情況下,可能需要解析 PDF 以編程方式從表中讀取數據。為此,本文介紹了如何使用 C# 從 PDF 表中提取數據。
為了從 PDF 文件中的表格中提取數據,我們將使用Aspose.PDF for .NET,它是一個強大的 API,提供了廣泛的 PDF 操作功能。點擊下方按鈕可下載試用。
以下是使用 C# 從 PDF 表格中提取數據的步驟。
以下代碼示例展示了如何在 C# 中從 PDF 表格中提取文本。
// Load source PDF document Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document("sample.pdf"); // Loop through the pages foreach (var page in pdfDocument.Pages) { // Create a table absorber and visit the page Aspose.Pdf.Text.TableAbsorber absorber = new Aspose.Pdf.Text.TableAbsorber(); absorber.Visit(page); // Loop through each absorbed table foreach (AbsorbedTable table in absorber.TableList) { Console.WriteLine("Table"); // Loop through each row in the table foreach (AbsorbedRow row in table.RowList) { // Loop through each cell in the row foreach (AbsorbedCell cell in row.CellList) { // Loop through the text fragments foreach (TextFragment fragment in cell.TextFragments) { var sb = new StringBuilder(); foreach (TextSegment seg in fragment.Segments) sb.Append(seg.Text); Console.Write($"{sb.ToString()}|"); } } Console.WriteLine(); } } }
以下是使用 C# 從 PDF 頁面的特定部分提取表格的步驟。
以下代碼示例展示了如何從 PDF 頁面的特定區域提取表格。
// Load source PDF document Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document("sample.pdf"); // Select the page and extract its square annotation var page = pdfDocument.Pages[1]; var squareAnnotation = page.Annotations.FirstOrDefault(ann => ann.AnnotationType == Annotations.AnnotationType.Square) as Annotations.SquareAnnotation; // Create table absorber and visit the page Aspose.Pdf.Text.TableAbsorber absorber = new Aspose.Pdf.Text.TableAbsorber(); absorber.Visit(page); // Loop through each absorbed table in the list foreach (AbsorbedTable table in absorber.TableList) { var isInRegion = (squareAnnotation.Rect.LLX < table.Rectangle.LLX) && (squareAnnotation.Rect.LLY < table.Rectangle.LLY) && (squareAnnotation.Rect.URX > table.Rectangle.URX) && (squareAnnotation.Rect.URY > table.Rectangle.URY); if (isInRegion) { // Loop through each row of the table foreach (AbsorbedRow row in table.RowList) { // Loop through each cell in the row foreach (AbsorbedCell cell in row.CellList) { // Loop through the text fragments and print the text foreach (TextFragment fragment in cell.TextFragments) { var sb = new StringBuilder(); foreach (TextSegment seg in fragment.Segments) { sb.Append(seg.Text); } var text = sb.ToString(); Console.Write($"{text}|"); } } Console.WriteLine(); } } }
如果你想試用Aspose的全部完整功能,可聯系在線客服獲取30天臨時授權體驗。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn