補充說明: iText是Java中用於建立和操作PDF檔案的開源庫, 可取得原始碼: https://github.com/itext/itext-java 提問: 給我 C# .Net 8.0 的 Class, 包含ImportJson(), ExportJson()函數, 可將 PDF 檔案, 匯入或匯出為 Json UTF8 文字檔案. 以下是 C# .NET 8.0 的範例程式碼,包含 `ImportJson()` 和 `ExportJson()` 函數,能將 PDF 文件內容與 JSON UTF-8 文字檔案相互轉換。此程式使用 **iText7** 套件處理 PDF,並使用 `System.Text.Json` 處理 JSON。 ### **完整程式碼** ```csharp using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; public class PdfJsonHandler { // 匯出 PDF 至 JSON public void ExportJson(string pdfFilePath, string jsonFilePath) { var paragraphs = new List(); using (var pdfReader = new PdfReader(pdfFilePath)) using (var pdfDocument = new PdfDocument(pdfReader)) { for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) { var page = pdfDocument.GetPage(i); var text = PdfTextExtractor.GetTextFromPage(page); paragraphs.AddRange(text.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } } var options = new JsonSerializerOptions { WriteIndented = true }; string json = JsonSerializer.Serialize(paragraphs, options); File.WriteAllText(jsonFilePath, json, System.Text.Encoding.UTF8); Console.WriteLine($"已成功匯出 JSON 至 {jsonFilePath}"); } // 匯入 JSON 至 PDF public void ImportJson(string jsonFilePath, string pdfFilePath) { string json = File.ReadAllText(jsonFilePath, System.Text.Encoding.UTF8); var paragraphs = JsonSerializer.Deserialize>(json); using (var pdfWriter = new PdfWriter(pdfFilePath)) using (var pdfDocument = new PdfDocument(pdfWriter)) { var document = new iText.Layout.Document(pdfDocument); foreach (var text in paragraphs) { document.Add(new iText.Layout.Element.Paragraph(text)); } document.Close(); } Console.WriteLine($"已成功匯入 JSON 至 PDF,檔案儲存於 {pdfFilePath}"); } } public class Program { public static void Main() { var handler = new PdfJsonHandler(); // 匯出 PDF 至 JSON handler.ExportJson("example.pdf", "example.json"); // 匯入 JSON 至 PDF handler.ImportJson("example.json", "new_example.pdf"); } } ``` ### **程式說明** 1. **`ExportJson()` 函數**: - 使用 `iText7` 套件逐頁提取 PDF 文件的文字。 - 將提取的文字分段,並存入列表。 - 使用 `System.Text.Json` 序列化列表為 JSON,並存為 UTF-8 格式檔案。 2. **`ImportJson()` 函數**: - 讀取 JSON 檔案並反序列化為文字段落列表。 - 使用 `iText7` 套件創建新的 PDF 文件。 - 將每個段落新增到 PDF 文檔中,形成頁面內容。 3. **必要套件**: - 安裝 `iText7` 套件以處理 PDF 文件: ```bash dotnet add package itext7 ``` 4. **檔案格式**: - 匯出的 JSON 文件為 UTF-8 編碼,包含段落文字的列表。例如: ```json [ "This is the first paragraph of the PDF.", "This is the second paragraph." ] ``` ### **使用注意** - PDF 文件的提取效果受限於文件內容的結構。如果 PDF 包含大量圖像或非文字內容,提取結果可能不完整或不理想。 - JSON 文件的結構需與匯入邏輯匹配,以確保內容能正確轉換回 PDF 文件。 如果需要處理更複雜的 PDF 文件內容(如表格、圖片或樣式),可告訴我以進一步改進功能! 😊