使用IText7和miniExcel處理pdf並輸出內容

有了一个点子發表於2024-08-07

使用框架:.net 8.0、winform

作業系統:windows 11

編譯器:vs 2022

內容:使用iText7miniExcel,介紹如何簡單讀取pdf檔案文字內容,並做處理後輸出至excel檔案中

秉承著一貫的風格,還是隻講操作,囫圇吞棗就是要講究一個穩準狠🤓

讀取PDF

iText7讀取操作十分簡單,只要有檔案地址即可,程式碼如下

PdfDocument pdfDoc = new PdfDocument(new PdfReader(yourFilPath));
for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
{
    LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();
    new PdfCanvasProcessor(strategy).ProcessPageContent(pdfDoc.GetPage(i));
    string pageText = strategy.GetResultantText();

    //對pdf內容進行處理
}

winform中,一般讀取本地檔案時都是使用OpenFileDialog控制元件,這裡直接程式碼中建立。透過該控制元件讀取到檔名及檔案地址

using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.Title = "選擇檔案";
    openFileDialog.Multiselect = true;    //是否多選
    openFileDialog.Filter = "所有檔案 (*.*)|*.*";    //過濾檔案型別

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {

        foreach (string fileName in openFileDialog.FileNames)
        {
            string fileNameOnly = System.IO.Path.GetFileName(fileName);
            dic.Add(fileNameOnly, fileName);
            lstPaper.Items.Add(fileNameOnly);
        }
    }
}

輸出Excel

使用miniExcel進行表格的簡單輸出也十分簡單。

建立輸出模型

透過miniExcel所提供的一系列特性,對輸出的表格屬性進行定義

public class ExportDto
{
    [ExcelColumnWidth(70),ExcelColumnName("名稱1")]
    public string Name1 { get; set; }

    [ExcelColumnWidth(100),ExcelColumnName("名稱2")]
    public string Name2 { get; set; }
}


private async Task Process(L)
{
    List<ExportDto> values = new List<ExportDto>()
    {
        //將輸出內容賦值
    }

    //輸出路徑
    var preFileName = DateTime.Now.ToString("yyyyMMddHHmmssyyyy");
    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    var basePath = Path.Combine(desktopPath, "temp");
    if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
    var filePath = Path.Combine(basePath, $"{preFileName}.xlsx");
    //輸出檔案
    await MiniExcel.SaveAsAsync(filePath, values);
}

總結

本篇僅僅使用[IText7](Chapter 1: Introducing basic building blocks (itextpdf.com))和[miniExcel](MiniExcel: 簡單、高效避免OOM的.NET處理Excel查、寫、模版填充資料工具。 (gitee.com))的最基本的功能,在此貼出官方文件。

待筆者繼續研習發現好玩的功能後,另行更新之事大概不會

相關文章