From 5315dfa486f3f04dc3415ca119f49e8ba57ed915 Mon Sep 17 00:00:00 2001 From: Aspose-Tester Date: Fri, 8 May 2026 14:59:02 +0500 Subject: [PATCH] Add 91 example(s) for working-with-tables --- .../add-auto-numbered-column-to-pdf-table.cs | 95 + .../add-centered-paragraph-to-table-cell.cs | 59 + .../add-footnote-references-in-table-cells.cs | 71 + .../add-hyperlink-to-table-cell.cs | 64 + .../add-multiline-text-to-table-cell.cs | 93 + .../add-radio-button-group-to-table-cell.cs | 109 + .../add-repeating-footer-row-to-pdf-table.cs | 105 + .../add-rotated-table-to-pdf-page.cs | 59 + .../add-styled-text-to-table-cell.cs | 74 + .../add-table-inside-paragraph-to-pdf.cs | 82 + .../add-table-to-specific-pdf-page.cs | 62 + .../add-table-to-textbox-form-field.cs | 104 + ...d-table-with-proportional-column-widths.cs | 61 + ...add-transparent-background-to-pdf-table.cs | 81 + working-with-tables/agents.md | 135 ++ ...nt-autofit-behaviors-to-multiple-tables.cs | 86 + .../apply-solid-border-to-pdf-table.cs | 68 + .../auto-fit-row-height-in-pdf-table.cs | 87 + .../auto-fit-table-columns-to-content.cs | 73 + .../batch-add-table-with-logo-to-pdfs.cs | 86 + .../batch-replace-tables-in-pdfs.cs | 76 + ...alculate-remaining-page-space-add-table.cs | 80 + working-with-tables/center-table-in-pdf.cs | 74 + .../check-table-isbroken-property.cs | 88 + .../conditional-formatting-table-cells.cs | 79 + working-with-tables/count-tables-in-pdf.cs | 33 + .../create-fixed-width-table.cs | 67 + .../create-pdf-table-from-datatable.cs | 72 + .../create-pdf-table-from-datatable__v2.cs | 90 + .../create-repeating-table-header.cs | 79 + .../create-table-stretched-to-page-width.cs | 77 + .../create-table-with-2-point-border.cs | 65 + .../create-table-with-colspan.cs | 83 + .../create-table-with-rows-in-pdf.cs | 95 + .../detect-merged-cells-in-pdf-tables.cs | 61 + .../embed-html-fragment-in-table-cell.cs | 72 + ...enable-table-splitting-across-pdf-pages.cs | 76 + .../export-pdf-table-to-csv.cs | 33 + .../export-tagged-table-structure-to-json.cs | 126 + .../extract-modify-tables-rotated-pages.cs | 64 + .../extract-pdf-tables-to-csv.cs | 81 + .../extract-pdf-tables-to-datatable.cs | 89 + .../extract-table-coordinates-from-pdf.cs | 43 + .../extract-tables-from-pdf.cs | 57 + .../extract-text-from-pdf-tables.cs | 56 + .../import-datatable-auto-fit-columns.cs | 68 + .../import-datatable-into-pdf-table.cs | 81 + ...import-filtered-dataview-into-pdf-table.cs | 87 + ...rt-filtered-dataview-into-pdf-table__v2.cs | 100 + working-with-tables/index.json | 2152 +++++++++++++++++ .../insert-column-into-pdf-table.cs | 76 + ...-from-memory-stream-into-pdf-table-cell.cs | 70 + .../insert-image-into-table-cell.cs | 66 + .../insert-page-break-after-table-row.cs | 60 + .../insert-svg-into-table-cell.cs | 84 + .../insert-table-after-paragraph.cs | 82 + .../insert-table-at-specific-position.cs | 71 + .../insert-table-before-image.cs | 82 + .../insert-table-into-pdf-page.cs | 76 + .../landscape-pdf-with-wide-table.cs | 100 + .../map-datatable-columns-to-pdf-table.cs | 136 ++ .../merge-table-cells-vertically-rowspan.cs | 78 + .../offset-table-left-margin.cs | 44 + .../pdf-table-alternating-row-colors.cs | 94 + .../populate-pdf-table-from-linq.cs | 88 + .../prevent-table-splitting.cs | 86 + .../read-rendered-table-width.cs | 98 + .../remove-all-tables-from-pdf.cs | 44 + .../remove-first-table-from-pdf.cs | 46 + .../remove-table-column-from-pdf.cs | 49 + .../remove-tables-containing-keyword.cs | 69 + .../render-table-from-xml-to-pdf.cs | 33 + .../render-table-high-dpi-images.cs | 89 + .../render-table-on-new-page.cs | 52 + .../reorder-pdf-table-columns.cs | 81 + .../repeat-header-column-row-in-pdf-table.cs | 101 + .../replace-keyword-in-pdf-table-cells.cs | 61 + .../replace-merged-table-cells.cs | 103 + working-with-tables/replace-table-in-pdf.cs | 73 + .../right-align-table-in-pdf.cs | 66 + .../rotate-table-90-degrees.cs | 88 + working-with-tables/serialize-table-to-xml.cs | 102 + .../set-cell-background-color-in-pdf-table.cs | 68 + .../set-cell-vertical-alignment-middle.cs | 71 + .../set-custom-cell-margins-in-pdf-table.cs | 76 + .../set-custom-row-height-in-pdf-table.cs | 60 + .../set-default-cell-padding-for-pdf-table.cs | 79 + .../set-fixed-row-height-table-rows.cs | 91 + .../set-maximum-column-width-for-pdf-table.cs | 94 + .../set-minimum-column-width-for-pdf-table.cs | 59 + .../set-table-width-80-percent.cs | 45 + .../set-table-zindex-in-pdf.cs | 91 + .../style-table-header-row-pdf.cs | 92 + 93 files changed, 9232 insertions(+) create mode 100644 working-with-tables/add-auto-numbered-column-to-pdf-table.cs create mode 100644 working-with-tables/add-centered-paragraph-to-table-cell.cs create mode 100644 working-with-tables/add-footnote-references-in-table-cells.cs create mode 100644 working-with-tables/add-hyperlink-to-table-cell.cs create mode 100644 working-with-tables/add-multiline-text-to-table-cell.cs create mode 100644 working-with-tables/add-radio-button-group-to-table-cell.cs create mode 100644 working-with-tables/add-repeating-footer-row-to-pdf-table.cs create mode 100644 working-with-tables/add-rotated-table-to-pdf-page.cs create mode 100644 working-with-tables/add-styled-text-to-table-cell.cs create mode 100644 working-with-tables/add-table-inside-paragraph-to-pdf.cs create mode 100644 working-with-tables/add-table-to-specific-pdf-page.cs create mode 100644 working-with-tables/add-table-to-textbox-form-field.cs create mode 100644 working-with-tables/add-table-with-proportional-column-widths.cs create mode 100644 working-with-tables/add-transparent-background-to-pdf-table.cs create mode 100644 working-with-tables/agents.md create mode 100644 working-with-tables/apply-different-autofit-behaviors-to-multiple-tables.cs create mode 100644 working-with-tables/apply-solid-border-to-pdf-table.cs create mode 100644 working-with-tables/auto-fit-row-height-in-pdf-table.cs create mode 100644 working-with-tables/auto-fit-table-columns-to-content.cs create mode 100644 working-with-tables/batch-add-table-with-logo-to-pdfs.cs create mode 100644 working-with-tables/batch-replace-tables-in-pdfs.cs create mode 100644 working-with-tables/calculate-remaining-page-space-add-table.cs create mode 100644 working-with-tables/center-table-in-pdf.cs create mode 100644 working-with-tables/check-table-isbroken-property.cs create mode 100644 working-with-tables/conditional-formatting-table-cells.cs create mode 100644 working-with-tables/count-tables-in-pdf.cs create mode 100644 working-with-tables/create-fixed-width-table.cs create mode 100644 working-with-tables/create-pdf-table-from-datatable.cs create mode 100644 working-with-tables/create-pdf-table-from-datatable__v2.cs create mode 100644 working-with-tables/create-repeating-table-header.cs create mode 100644 working-with-tables/create-table-stretched-to-page-width.cs create mode 100644 working-with-tables/create-table-with-2-point-border.cs create mode 100644 working-with-tables/create-table-with-colspan.cs create mode 100644 working-with-tables/create-table-with-rows-in-pdf.cs create mode 100644 working-with-tables/detect-merged-cells-in-pdf-tables.cs create mode 100644 working-with-tables/embed-html-fragment-in-table-cell.cs create mode 100644 working-with-tables/enable-table-splitting-across-pdf-pages.cs create mode 100644 working-with-tables/export-pdf-table-to-csv.cs create mode 100644 working-with-tables/export-tagged-table-structure-to-json.cs create mode 100644 working-with-tables/extract-modify-tables-rotated-pages.cs create mode 100644 working-with-tables/extract-pdf-tables-to-csv.cs create mode 100644 working-with-tables/extract-pdf-tables-to-datatable.cs create mode 100644 working-with-tables/extract-table-coordinates-from-pdf.cs create mode 100644 working-with-tables/extract-tables-from-pdf.cs create mode 100644 working-with-tables/extract-text-from-pdf-tables.cs create mode 100644 working-with-tables/import-datatable-auto-fit-columns.cs create mode 100644 working-with-tables/import-datatable-into-pdf-table.cs create mode 100644 working-with-tables/import-filtered-dataview-into-pdf-table.cs create mode 100644 working-with-tables/import-filtered-dataview-into-pdf-table__v2.cs create mode 100644 working-with-tables/index.json create mode 100644 working-with-tables/insert-column-into-pdf-table.cs create mode 100644 working-with-tables/insert-image-from-memory-stream-into-pdf-table-cell.cs create mode 100644 working-with-tables/insert-image-into-table-cell.cs create mode 100644 working-with-tables/insert-page-break-after-table-row.cs create mode 100644 working-with-tables/insert-svg-into-table-cell.cs create mode 100644 working-with-tables/insert-table-after-paragraph.cs create mode 100644 working-with-tables/insert-table-at-specific-position.cs create mode 100644 working-with-tables/insert-table-before-image.cs create mode 100644 working-with-tables/insert-table-into-pdf-page.cs create mode 100644 working-with-tables/landscape-pdf-with-wide-table.cs create mode 100644 working-with-tables/map-datatable-columns-to-pdf-table.cs create mode 100644 working-with-tables/merge-table-cells-vertically-rowspan.cs create mode 100644 working-with-tables/offset-table-left-margin.cs create mode 100644 working-with-tables/pdf-table-alternating-row-colors.cs create mode 100644 working-with-tables/populate-pdf-table-from-linq.cs create mode 100644 working-with-tables/prevent-table-splitting.cs create mode 100644 working-with-tables/read-rendered-table-width.cs create mode 100644 working-with-tables/remove-all-tables-from-pdf.cs create mode 100644 working-with-tables/remove-first-table-from-pdf.cs create mode 100644 working-with-tables/remove-table-column-from-pdf.cs create mode 100644 working-with-tables/remove-tables-containing-keyword.cs create mode 100644 working-with-tables/render-table-from-xml-to-pdf.cs create mode 100644 working-with-tables/render-table-high-dpi-images.cs create mode 100644 working-with-tables/render-table-on-new-page.cs create mode 100644 working-with-tables/reorder-pdf-table-columns.cs create mode 100644 working-with-tables/repeat-header-column-row-in-pdf-table.cs create mode 100644 working-with-tables/replace-keyword-in-pdf-table-cells.cs create mode 100644 working-with-tables/replace-merged-table-cells.cs create mode 100644 working-with-tables/replace-table-in-pdf.cs create mode 100644 working-with-tables/right-align-table-in-pdf.cs create mode 100644 working-with-tables/rotate-table-90-degrees.cs create mode 100644 working-with-tables/serialize-table-to-xml.cs create mode 100644 working-with-tables/set-cell-background-color-in-pdf-table.cs create mode 100644 working-with-tables/set-cell-vertical-alignment-middle.cs create mode 100644 working-with-tables/set-custom-cell-margins-in-pdf-table.cs create mode 100644 working-with-tables/set-custom-row-height-in-pdf-table.cs create mode 100644 working-with-tables/set-default-cell-padding-for-pdf-table.cs create mode 100644 working-with-tables/set-fixed-row-height-table-rows.cs create mode 100644 working-with-tables/set-maximum-column-width-for-pdf-table.cs create mode 100644 working-with-tables/set-minimum-column-width-for-pdf-table.cs create mode 100644 working-with-tables/set-table-width-80-percent.cs create mode 100644 working-with-tables/set-table-zindex-in-pdf.cs create mode 100644 working-with-tables/style-table-header-row-pdf.cs diff --git a/working-with-tables/add-auto-numbered-column-to-pdf-table.cs b/working-with-tables/add-auto-numbered-column-to-pdf-table.cs new file mode 100644 index 00000000..949a2da6 --- /dev/null +++ b/working-with-tables/add-auto-numbered-column-to-pdf-table.cs @@ -0,0 +1,95 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Paths (adjust as needed) + const string outputPath = "AutoNumberedTable.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table with two columns + Table table = new Table + { + // Optional: set table position and width + Left = 50, + Top = 700, + ColumnWidths = "50 200" // first column 50 units, second column 200 units + }; + + // Sample data for the second column + string[] data = { "Apple", "Banana", "Cherry", "Date", "Elderberry" }; + + // Add rows: first column will be filled later with numbers + foreach (string item in data) + { + // Add a new row + Row row = table.Rows.Add(); + + // Add empty cell for the auto‑numbered column + row.Cells.Add(new Cell()); + + // Add cell with actual data + Cell dataCell = new Cell(); + dataCell.Paragraphs.Add(new TextFragment(item)); + row.Cells.Add(dataCell); + } + + // Insert sequential numbers into the first cell of each row + for (int i = 0; i < table.Rows.Count; i++) + { + Row row = table.Rows[i]; + // Ensure the first cell exists + if (row.Cells.Count > 0) + { + // Clear any existing content (if any) and add the number + row.Cells[0].Paragraphs.Clear(); + row.Cells[0].Paragraphs.Add(new TextFragment((i + 1).ToString())); + } + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/add-centered-paragraph-to-table-cell.cs b/working-with-tables/add-centered-paragraph-to-table-cell.cs new file mode 100644 index 00000000..38b915a6 --- /dev/null +++ b/working-with-tables/add-centered-paragraph-to-table-cell.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Input and output file paths + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + + // Ensure the input file exists + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + // Open the existing PDF document + using (Document doc = new Document(inputPdf)) + { + // Get the first page (pages are 1‑based) + Page page = doc.Pages[1]; + + // Create a table and add it to the page + Table table = new Table + { + // Optional: set table position and column widths + Left = 50, + Top = 700, + ColumnWidths = "200" + }; + page.Paragraphs.Add(table); + + // Add a row to the table + Row row = table.Rows.Add(); + + // Add a cell to the row + Cell cell = row.Cells.Add(); + + // Create a paragraph (TextFragment) with centered alignment + TextFragment paragraph = new TextFragment("Centered text in cell") + { + // HorizontalAlignment is defined in BaseParagraph + HorizontalAlignment = HorizontalAlignment.Center + }; + + // Add the paragraph to the cell's Paragraphs collection + cell.Paragraphs.Add(paragraph); + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"PDF saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/add-footnote-references-in-table-cells.cs b/working-with-tables/add-footnote-references-in-table-cells.cs new file mode 100644 index 00000000..0c214113 --- /dev/null +++ b/working-with-tables/add-footnote-references-in-table-cells.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Tagged; +using Aspose.Pdf.LogicalStructure; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_footnotes.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the source PDF + using (Document doc = new Document(inputPath)) + { + // Enable tagged content and set basic properties + ITaggedContent tagged = doc.TaggedContent; + tagged.SetLanguage("en-US"); + tagged.SetTitle("Document with footnotes"); + + // Work with the first page + Page page = doc.Pages[1]; + + // Create a simple table (2 columns) + Table table = new Table + { + ColumnWidths = "200 200" + }; + page.Paragraphs.Add(table); + + // Header row + Row header = table.Rows.Add(); + header.Cells.Add("Item"); + header.Cells.Add("Description"); + + // Data row with a footnote reference in the second cell + Row dataRow = table.Rows.Add(); + dataRow.Cells.Add("Widget A"); // first cell + + // Second cell – contains superscript number and a footnote + Cell footnoteCell = dataRow.Cells.Add(); + + // TextFragment with superscript "1" (Unicode U+00B9) + TextFragment tf = new TextFragment("Widget A description\u00B9"); + tf.TextState.Font = FontRepository.FindFont("Helvetica"); + tf.TextState.FontSize = 12; + + // Create the footnote content + Note footNote = new Note("This widget is a prototype used for testing."); + + // Associate the footnote with the TextFragment + tf.FootNote = footNote; + + // Add the TextFragment to the cell + footnoteCell.Paragraphs.Add(tf); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Saved PDF with footnotes to '{outputPath}'."); + } +} diff --git a/working-with-tables/add-hyperlink-to-table-cell.cs b/working-with-tables/add-hyperlink-to-table-cell.cs new file mode 100644 index 00000000..e9005047 --- /dev/null +++ b/working-with-tables/add-hyperlink-to-table-cell.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Annotations; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the existing PDF + using (Document doc = new Document(inputPath)) + { + // Get the first page (1‑based indexing) + Page page = doc.Pages[1]; + + // Create a table and add it to the page + Table table = new Table(); + page.Paragraphs.Add(table); + + // Add a single row and a single cell + Row row = table.Rows.Add(); + Cell cell = row.Cells.Add(); + + // Add visible text to the cell + cell.Paragraphs.Add(new TextFragment("Click here for more info")); + + // Define the rectangle area for the hyperlink. + // Coordinates are in points, origin is bottom‑left of the page. + // Adjust these values to fit the actual cell position as needed. + Aspose.Pdf.Rectangle linkRect = new Aspose.Pdf.Rectangle( + llx: 100, // left + lly: 500, // bottom + urx: 250, // right + ury: 520 // top + ); + + // Create a LinkAnnotation that points to an external URL + LinkAnnotation link = new LinkAnnotation(page, linkRect) + { + // Use GoToURIAction for external web links (preferred over Hyperlink property) + Action = new GoToURIAction("https://www.example.com") + }; + + // Add the annotation to the cell's paragraph collection. + // LinkAnnotation derives from BaseParagraph, so it can be added here. + cell.Paragraphs.Add(link); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"PDF with hyperlink saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/add-multiline-text-to-table-cell.cs b/working-with-tables/add-multiline-text-to-table-cell.cs new file mode 100644 index 00000000..43fb0043 --- /dev/null +++ b/working-with-tables/add-multiline-text-to-table-cell.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "multiline_cell.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page + Page page = doc.Pages.Add(); + + // Create a table and add it to the page + Table table = new Table + { + // Optional: set column widths (single column in this example) + ColumnWidths = "200" + }; + page.Paragraphs.Add(table); + + // Add a row to the table + Row row = table.Rows.Add(); + + // Add a cell to the row + Cell cell = row.Cells.Add(); + + // First line of text + TextFragment line1 = new TextFragment("First line of text"); + line1.TextState.FontSize = 12; + line1.TextState.Font = FontRepository.FindFont("Helvetica"); + line1.TextState.ForegroundColor = Color.Black; + + // Line break fragment (empty text with a newline) + TextFragment lineBreak = new TextFragment("\n"); + + // Second line of text + TextFragment line2 = new TextFragment("Second line of text"); + line2.TextState.FontSize = 12; + line2.TextState.Font = FontRepository.FindFont("Helvetica"); + line2.TextState.ForegroundColor = Color.Black; + + // Third line of text + TextFragment line3 = new TextFragment("Third line of text"); + line3.TextState.FontSize = 12; + line3.TextState.Font = FontRepository.FindFont("Helvetica"); + line3.TextState.ForegroundColor = Color.Black; + + // Add the fragments to the cell, separating them with line‑break fragments + cell.Paragraphs.Add(line1); + cell.Paragraphs.Add(lineBreak); + cell.Paragraphs.Add(line2); + cell.Paragraphs.Add(lineBreak); + cell.Paragraphs.Add(line3); + + // Save the document (guard against missing GDI+ on non‑Windows platforms) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException + static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/add-radio-button-group-to-table-cell.cs b/working-with-tables/add-radio-button-group-to-table-cell.cs new file mode 100644 index 00000000..c417f801 --- /dev/null +++ b/working-with-tables/add-radio-button-group-to-table-cell.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Forms; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "radio_table.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table with two columns + Table table = new Table + { + ColumnWidths = "200 200" + }; + page.Paragraphs.Add(table); + + // Add a row to the table + Row row = table.Rows.Add(); + + // First cell: label text + Cell labelCell = row.Cells.Add(); + labelCell.Paragraphs.Add(new TextFragment("Choose an option:")); + + // Second cell: will contain the radio button group + Cell radioCell = row.Cells.Add(); + + // Create a radio button field that will act as the group container + RadioButtonField radioGroup = new RadioButtonField(doc) + { + PartialName = "OptionGroup" // All options with this name belong to the same group + }; + + // ----- Option 1 ----- + Aspose.Pdf.Rectangle rect1 = new Aspose.Pdf.Rectangle(0, 0, 20, 20); + RadioButtonOptionField opt1 = new RadioButtonOptionField(page, rect1) + { + OptionName = "Option1", + Caption = new TextFragment("Option 1") + }; + radioGroup.Add(opt1); // Add to the group + radioCell.Paragraphs.Add(opt1); // Place visual representation in the cell + + // ----- Option 2 ----- + Aspose.Pdf.Rectangle rect2 = new Aspose.Pdf.Rectangle(0, 30, 20, 50); + RadioButtonOptionField opt2 = new RadioButtonOptionField(page, rect2) + { + OptionName = "Option2", + Caption = new TextFragment("Option 2") + }; + radioGroup.Add(opt2); + radioCell.Paragraphs.Add(opt2); + + // ----- Option 3 ----- + Aspose.Pdf.Rectangle rect3 = new Aspose.Pdf.Rectangle(0, 60, 20, 80); + RadioButtonOptionField opt3 = new RadioButtonOptionField(page, rect3) + { + OptionName = "Option3", + Caption = new TextFragment("Option 3") + }; + radioGroup.Add(opt3); + radioCell.Paragraphs.Add(opt3); + + // Register the radio button group with the document's form collection + doc.Form.Add(radioGroup); + + // Save the PDF document – guard against missing libgdiplus on non‑Windows platforms + try + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + } + else + { + // Attempt to save; if libgdiplus is missing, catch the TypeInitializationException + doc.Save(outputPath); + } + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF could not be saved using Aspose.Pdf's default renderer."); + // Optionally, you could implement an alternative saving strategy here. + } + } + } + + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/add-repeating-footer-row-to-pdf-table.cs b/working-with-tables/add-repeating-footer-row-to-pdf-table.cs new file mode 100644 index 00000000..092d013c --- /dev/null +++ b/working-with-tables/add-repeating-footer-row-to-pdf-table.cs @@ -0,0 +1,105 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Tagged; +using Aspose.Pdf.LogicalStructure; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_with_footer.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the source PDF + using (Document doc = new Document(inputPath)) + { + // ------------------------------------------------- + // 1. Create a visual table and add it to the first page + // ------------------------------------------------- + Page page = doc.Pages[1]; + + Table table = new Table + { + // Ensure the last row repeats on each page as a footer. + // Aspose.Pdf versions prior to 23.10 do not expose the RepeatingRowsStyle enum. + // In such cases, setting RepeatingRowsCount to 1 makes the last row repeat. + // The visual appearance (header vs. footer) is handled by the logical structure below. + RepeatingRowsCount = 1, + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Color.Black), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Header row (optional) + Row header = new Row(); + header.Cells.Add("Column A"); + header.Cells.Add("Column B"); + table.Rows.Add(header); + + // Body rows + for (int i = 1; i <= 20; i++) + { + Row body = new Row(); + body.Cells.Add($"Item {i}"); + body.Cells.Add($"Value {i * 10}"); + table.Rows.Add(body); + } + + // Footer row (visual) – this will repeat on each page because RepeatingRowsCount = 1 + Row footer = new Row(); + footer.Cells.Add("Total"); + footer.Cells.Add("2000"); + table.Rows.Add(footer); + + // Add the table to the page + page.Paragraphs.Add(table); + + // ------------------------------------------------- + // 2. Create logical structure for the table with a TFoot element + // ------------------------------------------------- + ITaggedContent tagged = doc.TaggedContent; + + // Root element of the tagged content tree + StructureElement root = tagged.RootElement; + + // Create the table structure element + TableElement tableStruct = tagged.CreateTableElement(); + tableStruct.AlternativeText = "Sample data table with footer"; + root.AppendChild(tableStruct); + + // Create TFoot (table footer) logical element + TableTFootElement tFoot = tagged.CreateTableTFootElement(); + tableStruct.AppendChild(tFoot); + + // Create a table row inside the TFoot + TableTRElement footRow = tFoot.CreateTR(); + + // First cell of the footer row + TableTDElement footCell1 = tagged.CreateTableTDElement(); + footCell1.SetText("Total"); + footRow.AppendChild(footCell1); + + // Second cell of the footer row + TableTDElement footCell2 = tagged.CreateTableTDElement(); + footCell2.SetText("2000"); + footRow.AppendChild(footCell2); + + // Append the footer row to the TFoot element + tFoot.AppendChild(footRow); + + // ------------------------------------------------- + // 3. Save the modified PDF + // ------------------------------------------------- + doc.Save(outputPath); + } + + Console.WriteLine($"PDF with footer row saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/add-rotated-table-to-pdf-page.cs b/working-with-tables/add-rotated-table-to-pdf-page.cs new file mode 100644 index 00000000..1064f987 --- /dev/null +++ b/working-with-tables/add-rotated-table-to-pdf-page.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "rotated_table.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Rotate the first page 90 degrees clockwise + Page page = doc.Pages[1]; + page.Rotate = Rotation.on90; // correct enum value + + // Create a table + Table table = new Table + { + // Position of the table (coordinates are in user space; rotation is handled automatically) + Left = 100, + Top = 100, + // Optional visual styling + Border = new BorderInfo(BorderSide.All, 1f, Aspose.Pdf.Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Define column widths (two columns, each 200 units wide) + table.ColumnWidths = "200 200"; + + // Add a header row + Row header = table.Rows.Add(); + header.Cells.Add("Header 1"); + header.Cells.Add("Header 2"); + + // Add a data row + Row data = table.Rows.Add(); + data.Cells.Add("Cell A1"); + data.Cells.Add("Cell B1"); + + // Insert the table into the page + page.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Document saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/add-styled-text-to-table-cell.cs b/working-with-tables/add-styled-text-to-table-cell.cs new file mode 100644 index 00000000..f5194443 --- /dev/null +++ b/working-with-tables/add-styled-text-to-table-cell.cs @@ -0,0 +1,74 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "table_with_text.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and add it to the page + Table table = new Table(); + page.Paragraphs.Add(table); + + // Add a row to the table + Row row = table.Rows.Add(); + + // Add a cell to the row + Cell cell = row.Cells.Add(); + + // Allow the cell to use the TextFragment's TextState for styling + cell.IsOverrideByFragment = true; + + // Create a TextFragment with the desired text + TextFragment tf = new TextFragment("Hello Aspose!"); + + // Set the font and size via the TextState of the fragment + tf.TextState.Font = FontRepository.FindFont("Helvetica"); + tf.TextState.FontSize = 24; + + // Add the TextFragment to the cell's content + cell.Paragraphs.Add(tf); + + // Save the PDF document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to {outputPath}"); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to {outputPath}"); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/add-table-inside-paragraph-to-pdf.cs b/working-with-tables/add-table-inside-paragraph-to-pdf.cs new file mode 100644 index 00000000..194e0c76 --- /dev/null +++ b/working-with-tables/add-table-inside-paragraph-to-pdf.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_with_table.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing PDF (using the recommended lifecycle rule) + using (Document doc = new Document(inputPath)) + { + // Get the first page (Aspose.Pdf uses 1‑based indexing) + Page page = doc.Pages[1]; + + // ------------------------------------------------------------ + // 1. Create a text fragment (BaseParagraph) and add it to the page + // ------------------------------------------------------------ + TextFragment txtFragment = new TextFragment("Below is a sample table added inside a paragraph:") + { + // Position the fragment on the page (coordinates are from the bottom‑left corner) + Position = new Position(50, 750) + }; + // Append the fragment to the page's paragraph collection + page.Paragraphs.Add(txtFragment); + + // ------------------------------------------------------------ + // 2. Create a Table (also a BaseParagraph) and configure it + // ------------------------------------------------------------ + Table table = new Table + { + // Position the table below the text fragment + // (Top coordinate is measured from the bottom of the page) + Top = 700, // Y‑coordinate of the top edge + Left = 50, // X‑coordinate of the left edge + // Optional visual settings + Border = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Add header row + Row header = table.Rows.Add(); + header.Cells.Add("Product"); + header.Cells.Add("Quantity"); + header.Cells.Add("Price"); + + // Add a few data rows + Row row1 = table.Rows.Add(); + row1.Cells.Add("Widget A"); + row1.Cells.Add("10"); + row1.Cells.Add("$15.00"); + + Row row2 = table.Rows.Add(); + row2.Cells.Add("Widget B"); + row2.Cells.Add("5"); + row2.Cells.Add("$25.00"); + + // ------------------------------------------------------------ + // 3. Insert the Table into the page's paragraph collection + // ------------------------------------------------------------ + // The Table itself is a BaseParagraph, so we add it directly. + page.Paragraphs.Add(table); + + // ------------------------------------------------------------ + // Save the modified PDF (using the provided lifecycle rule) + // ------------------------------------------------------------ + doc.Save(outputPath); + } + + Console.WriteLine($"PDF with table saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/add-table-to-specific-pdf-page.cs b/working-with-tables/add-table-to-specific-pdf-page.cs new file mode 100644 index 00000000..26cd465c --- /dev/null +++ b/working-with-tables/add-table-to-specific-pdf-page.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const int targetPageNumber = 2; // 1‑based page number where the table will be placed + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the existing PDF inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Validate the requested page number (Aspose.Pdf pages are 1‑based) + if (targetPageNumber < 1 || targetPageNumber > doc.Pages.Count) + { + Console.Error.WriteLine($"Page {targetPageNumber} is out of range (1‑{doc.Pages.Count})."); + return; + } + + // Create a simple 2×2 table + Table table = new Table + { + Border = new BorderInfo(BorderSide.All, 1.0f, Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // First row + Row row1 = table.Rows.Add(); + Cell cell11 = row1.Cells.Add(); + cell11.Paragraphs.Add(new TextFragment("R1C1")); + Cell cell12 = row1.Cells.Add(); + cell12.Paragraphs.Add(new TextFragment("R1C2")); + + // Second row + Row row2 = table.Rows.Add(); + Cell cell21 = row2.Cells.Add(); + cell21.Paragraphs.Add(new TextFragment("R2C1")); + Cell cell22 = row2.Cells.Add(); + cell22.Paragraphs.Add(new TextFragment("R2C2")); + + // Insert the table into the specified page + Page page = doc.Pages[targetPageNumber]; // Pages collection is 1‑based + page.Paragraphs.Add(table); + + // Save the modified document + doc.Save(outputPath); + } + + Console.WriteLine($"Table added to page {targetPageNumber} and saved as '{outputPath}'."); + } +} diff --git a/working-with-tables/add-table-to-textbox-form-field.cs b/working-with-tables/add-table-to-textbox-form-field.cs new file mode 100644 index 00000000..ad81ee55 --- /dev/null +++ b/working-with-tables/add-table-to-textbox-form-field.cs @@ -0,0 +1,104 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Forms; +using Aspose.Pdf.Tagged; +using Aspose.Pdf.LogicalStructure; +using Aspose.Pdf.Annotations; // Added for Border class + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_with_table_field.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the source PDF + using (Document doc = new Document(inputPath)) + { + // ------------------------------------------------------------ + // 1. Create a TextBoxField that will host the table appearance + // ------------------------------------------------------------ + // Define the rectangle where the field will be placed (coordinates in points) + Aspose.Pdf.Rectangle fieldRect = new Aspose.Pdf.Rectangle(100, 500, 400, 700); + TextBoxField txtField = new TextBoxField(doc, fieldRect) + { + // Optional visual settings + Color = Aspose.Pdf.Color.LightGray, // Use Aspose.Pdf.Color + Multiline = true, + Name = "TableField" + }; + + // Set the border after the TextBoxField instance has been created + txtField.Border = new Border(txtField) { Width = 1 }; + // Border color is controlled by the annotation's Color property (already set above) + + // Add the field to the document's form (page number is 1‑based) + doc.Form.Add(txtField, 1); + + // ------------------------------------------------------------ + // 2. Build a tagged Table structure (will appear as a separate + // element in the PDF's logical structure) + // ------------------------------------------------------------ + ITaggedContent tagged = doc.TaggedContent; + + // Ensure the document is marked as tagged (presence of TaggedContent implies tagging) + StructureElement root = tagged.RootElement; + + // Create the table element + TableElement table = tagged.CreateTableElement(); + table.AlternativeText = "Sample data table"; + + // Create table header (THead) with two columns + TableTHeadElement thead = tagged.CreateTableTHeadElement(); + table.AppendChild(thead); + TableTRElement headerRow = tagged.CreateTableTRElement(); + thead.AppendChild(headerRow); + + TableTHElement th1 = tagged.CreateTableTHElement(); + th1.SetText("Product"); + headerRow.AppendChild(th1); + + TableTHElement th2 = tagged.CreateTableTHElement(); + th2.SetText("Price"); + headerRow.AppendChild(th2); + + // Create table body (TBody) with one data row + TableTBodyElement tbody = tagged.CreateTableTBodyElement(); + table.AppendChild(tbody); + TableTRElement dataRow = tagged.CreateTableTRElement(); + tbody.AppendChild(dataRow); + + TableTDElement td1 = tagged.CreateTableTDElement(); + td1.SetText("Widget A"); + dataRow.AppendChild(td1); + + TableTDElement td2 = tagged.CreateTableTDElement(); + td2.SetText("$123.45"); + dataRow.AppendChild(td2); + + // Attach the table to the root of the logical structure + root.AppendChild(table); + + // ------------------------------------------------------------ + // 3. Add an additional appearance for the TextBoxField that + // visually aligns with the table rectangle (optional) + // ------------------------------------------------------------ + // The appearance rectangle can be the same as the field rectangle + doc.Form.AddFieldAppearance(txtField, 1, fieldRect); + + // ------------------------------------------------------------ + // 4. Save the modified PDF + // ------------------------------------------------------------ + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved with TextBoxField and embedded table: {outputPath}"); + } +} diff --git a/working-with-tables/add-table-with-proportional-column-widths.cs b/working-with-tables/add-table-with-proportional-column-widths.cs new file mode 100644 index 00000000..d0ebc734 --- /dev/null +++ b/working-with-tables/add-table-with-proportional-column-widths.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using System.Linq; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Define the desired column widths (in points or any unit) + double[] columnWidths = { 120, 80, 100 }; + + // Calculate the total width of all columns + double totalWidth = columnWidths.Sum(); + + // Convert each width to a percentage of the total width + string[] widthPercentages = columnWidths + .Select(w => (w / totalWidth * 100).ToString("0.##") + "%") + .ToArray(); + + // Build the ColumnWidths string expected by Aspose.Pdf (e.g., "40% 27% 33%") + string columnWidthsString = string.Join(" ", widthPercentages); + + // Load the source PDF and add a table with proportional column widths + using (Document doc = new Document(inputPath)) + { + // Create a table and set its column widths using percentages + Table table = new Table + { + ColumnWidths = columnWidthsString, + ColumnAdjustment = ColumnAdjustment.AutoFitToWindow + }; + + // Add a single row with cells (placeholder content) + Row row = table.Rows.Add(); + foreach (var _ in columnWidths) + { + Cell cell = row.Cells.Add(); + cell.Paragraphs.Add(new TextFragment("Cell")); + } + + // Insert the table into the first page of the document + doc.Pages[1].Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Proportional table saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/add-transparent-background-to-pdf-table.cs b/working-with-tables/add-transparent-background-to-pdf-table.cs new file mode 100644 index 00000000..0f7d5c61 --- /dev/null +++ b/working-with-tables/add-transparent-background-to-pdf-table.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Drawing; // Table resides in Aspose.Pdf namespace, but drawing helpers are useful + +class Program +{ + static void Main() + { + const string outputPath = "table_with_background.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and set its position + Table table = new Table + { + // Position the table (optional) + Left = 50, + Top = 700, + // Set the background color with desired opacity (e.g., 50% transparent red) + // Aspose.Pdf.Color.FromArgb(alpha, red, green, blue) where alpha 0-255 + BackgroundColor = Aspose.Pdf.Color.FromArgb(128, 255, 0, 0) + }; + + // Define column widths (optional) + table.ColumnWidths = "100 150"; + + // Add a header row + Row header = table.Rows.Add(); + header.BackgroundColor = Aspose.Pdf.Color.LightGray; // distinct header background + header.Cells.Add("Product"); + header.Cells.Add("Price"); + + // Add a data row + Row data = table.Rows.Add(); + data.Cells.Add("Widget A"); + data.Cells.Add("$25.00"); + + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF could not be saved using Aspose.Pdf's default renderer."); + // Optionally, you could implement an alternative saving strategy here. + } + } + } + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/agents.md b/working-with-tables/agents.md new file mode 100644 index 00000000..8f257f15 --- /dev/null +++ b/working-with-tables/agents.md @@ -0,0 +1,135 @@ +--- +name: working-with-tables +description: C# examples for working-with-tables using Aspose.PDF for .NET +language: csharp +framework: net10.0 +parent: ../agents.md +--- + +# AGENTS - working-with-tables + +## Persona + +You are a C# developer specializing in PDF processing using Aspose.PDF for .NET, +working within the **working-with-tables** category. +This folder contains standalone C# examples for working-with-tables operations. +See the root [agents.md](../agents.md) for repository-wide conventions and boundaries. + +## Scope +- This folder contains examples for **working-with-tables**. +- Files are standalone `.cs` examples stored directly in this folder. + +## Required Namespaces + +- `using Aspose.Pdf;` (91/91 files) ← category-specific +- `using Aspose.Pdf.Text;` (75/91 files) ← category-specific +- `using Aspose.Pdf.Drawing;` (9/91 files) +- `using Aspose.Pdf.LogicalStructure;` (6/91 files) +- `using Aspose.Pdf.Tagged;` (5/91 files) +- `using Aspose.Pdf.Annotations;` (3/91 files) +- `using Aspose.Pdf.Forms;` (2/91 files) +- `using Aspose.Pdf.Operators;` (1/91 files) +- `using System;` (91/91 files) +- `using System.IO;` (79/91 files) +- `using System.Runtime.InteropServices;` (43/91 files) +- `using System.Data;` (9/91 files) +- `using System.Linq;` (8/91 files) +- `using System.Collections.Generic;` (5/91 files) +- `using System.Globalization;` (1/91 files) +- `using System.Text.Json;` (1/91 files) + +## Common Code Pattern + +Most files follow this pattern: + +```csharp +using (Document doc = new Document("input.pdf")) +{ + // ... operations ... + doc.Save("output.pdf"); +} +``` + +## Files in this folder + +| File | Title | Key APIs | Description | +|------|-------|----------|-------------| +| [add-auto-numbered-column-to-pdf-table](./add-auto-numbered-column-to-pdf-table.cs) | Add Auto‑Numbered Column to PDF Table | `Document`, `Page`, `Table` | Shows how to create a PDF document with a table using Aspose.Pdf, add rows, and automatically fil... | +| [add-centered-paragraph-to-table-cell](./add-centered-paragraph-to-table-cell.cs) | Add Centered Paragraph to Table Cell in PDF | `Document`, `Page`, `Table` | Demonstrates opening an existing PDF, creating a table, adding a row and cell, and inserting a ce... | +| [add-footnote-references-in-table-cells](./add-footnote-references-in-table-cells.cs) | Add Footnote References in Table Cells | `Document`, `ITaggedContent`, `Page` | Shows how to insert a superscript footnote number inside a table cell and associate it with a foo... | +| [add-hyperlink-to-table-cell](./add-hyperlink-to-table-cell.cs) | Add Hyperlink to Table Cell in PDF | `Document`, `Page`, `Table` | Demonstrates creating a LinkAnnotation with a GoToURIAction and inserting it into a table cell's ... | +| [add-multiline-text-to-table-cell](./add-multiline-text-to-table-cell.cs) | Add Multiline Text to a Table Cell | `Document`, `Page`, `Table` | Shows how to create a PDF table cell containing multiline text by adding several TextFragment obj... | +| [add-radio-button-group-to-table-cell](./add-radio-button-group-to-table-cell.cs) | Add Radio Button Group Inside Table Cell | `Document`, `Page`, `Table` | Demonstrates creating a PDF table and placing a grouped set of radio buttons inside a cell using ... | +| [add-repeating-footer-row-to-pdf-table](./add-repeating-footer-row-to-pdf-table.cs) | Add Repeating Footer Row to PDF Table | `Document`, `Table`, `Row` | Shows how to add a visual footer row to a PDF table, make it repeat on every page, and define the... | +| [add-rotated-table-to-pdf-page](./add-rotated-table-to-pdf-page.cs) | Add Rotated Table to PDF Page | `Document`, `Page`, `Rotation` | Shows how to rotate a PDF page and then insert a table that automatically aligns with the rotated... | +| [add-styled-text-to-table-cell](./add-styled-text-to-table-cell.cs) | Add Styled Text to a Table Cell in PDF | `Document`, `Page`, `Table` | Shows how to place a TextFragment with a specific font and size into a table cell, using the cell... | +| [add-table-inside-paragraph-to-pdf](./add-table-inside-paragraph-to-pdf.cs) | Insert Table Within a Paragraph in a PDF | `Document`, `Page`, `TextFragment` | Demonstrates how to add a text fragment and then insert a table as a paragraph into an existing P... | +| [add-table-to-specific-pdf-page](./add-table-to-specific-pdf-page.cs) | Add Table to Specific PDF Page | `Document`, `Page`, `Table` | Shows how to load an existing PDF, create a simple 2×2 table, and insert it onto a specified page... | +| [add-table-to-textbox-form-field](./add-table-to-textbox-form-field.cs) | Add a Table Inside a TextBox Form Field | `Document`, `TextBoxField`, `Border` | Demonstrates creating a TextBox form field, building a tagged table structure, attaching the tabl... | +| [add-table-with-proportional-column-widths](./add-table-with-proportional-column-widths.cs) | Add Table with Proportional Column Widths to PDF | `Document`, `Table`, `Row` | Loads an existing PDF, calculates column width percentages, creates a table with those proportion... | +| [add-transparent-background-to-pdf-table](./add-transparent-background-to-pdf-table.cs) | Add Transparent Background Color to PDF Table | `Document`, `Page`, `Table` | Demonstrates setting a semi‑transparent background color for an Aspose.Pdf Table and saving the P... | +| [apply-different-autofit-behaviors-to-multiple-tabl...](./apply-different-autofit-behaviors-to-multiple-tables.cs) | Apply Different AutoFit Behaviors to Multiple Tables in a PD... | `Document`, `Page`, `Table` | Demonstrates how to add two tables to a PDF and set distinct ColumnAdjustment values (AutoFitToCo... | +| [apply-solid-border-to-pdf-table](./apply-solid-border-to-pdf-table.cs) | Apply Solid Border to PDF Table | `Document`, `Page`, `Table` | Demonstrates how to set a solid black border on an entire Aspose.Pdf Table by configuring a Borde... | +| [auto-fit-row-height-in-pdf-table](./auto-fit-row-height-in-pdf-table.cs) | Auto-fit Row Height in PDF Table | `Document`, `Page`, `Table` | Shows how to let a table row automatically adjust its height to fit the cell content by setting F... | +| [auto-fit-table-columns-to-content](./auto-fit-table-columns-to-content.cs) | AutoFit Table Columns to Content in PDF | `Document`, `Page`, `Table` | Demonstrates creating a PDF with a table whose column widths automatically adjust to the cell con... | +| [batch-add-table-with-logo-to-pdfs](./batch-add-table-with-logo-to-pdfs.cs) | Batch Add Table with Logo to PDFs | `Document`, `Page`, `Table` | Demonstrates iterating over a folder of PDF files, creating a table that contains a company logo ... | +| [batch-replace-tables-in-pdfs](./batch-replace-tables-in-pdfs.cs) | Batch Replace Tables in Multiple PDFs | `Document`, `Page`, `TableAbsorber` | Shows how to process all PDF files in a folder, locate tables on each page with TableAbsorber, an... | +| [calculate-remaining-page-space-add-table](./calculate-remaining-page-space-add-table.cs) | Calculate Remaining Page Space and Add Table to PDF | `Document`, `Page`, `Rectangle` | Loads a PDF, computes the usable vertical space by subtracting existing content height from the p... | +| [center-table-in-pdf](./center-table-in-pdf.cs) | Center Table in PDF using Aspose.Pdf | `Document`, `Table`, `Row` | Demonstrates how to create a table, set its HorizontalAlignment to Center, and add it to a PDF pa... | +| [check-table-isbroken-property](./check-table-isbroken-property.cs) | Check and Set Table Break Using IsBroken Property | `Document`, `Page`, `Table` | The example creates a PDF, adds a table, reads the Table.IsBroken property to see if the table wi... | +| [conditional-formatting-table-cells](./conditional-formatting-table-cells.cs) | Conditional Formatting of Table Cells in PDF | `Document`, `Page`, `Table` | Demonstrates how to apply background colors to PDF table cells based on numeric thresholds using ... | +| [count-tables-in-pdf](./count-tables-in-pdf.cs) | Count Tables in PDF using TableAbsorber | `Document`, `TableAbsorber`, `Visit` | Shows how to load a PDF with Aspose.Pdf, use TableAbsorber to extract tables, and obtain the numb... | +| [create-fixed-width-table](./create-fixed-width-table.cs) | Create Fixed-Width Table in PDF | `Document`, `Page`, `Table` | Shows how to create a table with a total width of 500 points, add a row and cell, position it on ... | +| [create-pdf-table-from-datatable](./create-pdf-table-from-datatable.cs) | Create PDF Table from a DataTable | `Document`, `Page`, `Table` | Demonstrates how to fill a DataTable, import it into an Aspose.Pdf Table, add the table to a PDF ... | +| [create-pdf-table-from-datatable__v2](./create-pdf-table-from-datatable__v2.cs) | Create PDF Table with Dynamic Row Count from DataTable | `Document`, `Page`, `Table` | Demonstrates how to count source records, import a DataTable into an Aspose.Pdf Table, and save t... | +| [create-repeating-table-header](./create-repeating-table-header.cs) | Create Repeating Table Header in PDF | `Document`, `ITaggedContent`, `StructureElement` | Shows how to add a table with a header row that repeats on each new page using Aspose.Pdf's tagge... | +| [create-table-stretched-to-page-width](./create-table-stretched-to-page-width.cs) | Create Table Stretched to Page Width in PDF | `Document`, `Page`, `Table` | Shows how to generate a PDF with a table whose columns are sized proportionally to fill the entir... | +| ... | | | *and 61 more files* | + +## Category Statistics +- Total examples: 91 + +## Category-Specific Tips + +### Key API Surface +- `Aspose.Pdf.BorderCornerStyle` +- `Aspose.Pdf.BorderInfo` +- `Aspose.Pdf.BorderSide` +- `Aspose.Pdf.Cell` +- `Aspose.Pdf.Color` +- `Aspose.Pdf.ColumnAdjustment` +- `Aspose.Pdf.Document` +- `Aspose.Pdf.GraphInfo` +- `Aspose.Pdf.HorizontalAlignment` +- `Aspose.Pdf.Image` +- `Aspose.Pdf.MarginInfo` +- `Aspose.Pdf.Page` +- `Aspose.Pdf.Row` +- `Aspose.Pdf.Table` +- `Aspose.Pdf.Table.GetWidth` + +### Rules +- Create an {image} object, assign its File property to a {string_literal} path, and embed it in a table cell by invoking cell.Paragraphs.Add({image}). +- Add a {table} to a {page} via page.Paragraphs.Add({table}), configure its DefaultCellBorder with new BorderInfo(BorderSide.All, {float}) and set ColumnWidths using a space‑separated {string_literal}; then populate rows with table.Rows.Add() and cells with row.Cells.Add(...), optionally adjusting cell properties such as VerticalAlignment. +- Instantiate a PDF document and add a page: {doc} = new Document(); {page} = {doc}.Pages.Add(); +- Create a Table, set column widths via a space‑separated string and enable auto‑fit to window: {table} = new Table(); {table}.ColumnWidths = "{string_literal}"; {table}.ColumnAdjustment = ColumnAdjustment.AutoFitToWindow; +- Define default cell border and overall table border using BorderInfo with BorderSide.All and a thickness: {table}.DefaultCellBorder = new BorderInfo(BorderSide.All, {float}); {table}.Border = new BorderInfo(BorderSide.All, {float}); + +### Warnings +- ColumnWidths expects a space‑separated string of numeric values; ensure the format matches the table layout requirements. +- ColumnAdjustment.AutoFitToWindow only takes effect when ColumnWidths are explicitly set; otherwise the table may not resize as expected. +- GetWidth may return a meaningful value only after the table has been laid out (e.g., added to a page or after layout processing). In this isolated example the table is not added to the page, which could lead to default or zero width in some scenarios. +- TableAbsorber and AbsorbedTable reside in the Aspose.Pdf.Text namespace; ensure the appropriate using directive is present. +- TableAbsorber.TableList may be empty; accessing index 0 without checking can cause an exception. + +## General Tips +- See parent [agents.md](../agents.md) for: + - **Boundaries** — Always / Ask First / Never rules for all examples + - **Common Mistakes** — verified anti-patterns that cause build failures + - **Domain Knowledge** — cross-cutting API-specific gotchas + - **Testing Guide** — build and run verification steps +- Review code examples in this folder for working-with-tables patterns + + +Updated: 2026-05-08 | Run: `20260508_145008_6ada82` + diff --git a/working-with-tables/apply-different-autofit-behaviors-to-multiple-tables.cs b/working-with-tables/apply-different-autofit-behaviors-to-multiple-tables.cs new file mode 100644 index 00000000..b19a608c --- /dev/null +++ b/working-with-tables/apply-different-autofit-behaviors-to-multiple-tables.cs @@ -0,0 +1,86 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // required for TextFragment + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing PDF inside a using block (ensures proper disposal) + using (Document doc = new Document(inputPath)) + { + // Ensure there is at least one page to add tables to + Page page = doc.Pages.Count > 0 ? doc.Pages[1] : doc.Pages.Add(); + + // ------------------------------------------------------------ + // Table 1 – AutoFit to content (columns shrink to fit cell content) + // ------------------------------------------------------------ + Table tableFitToContent = new Table + { + // Position the table on the page + Left = 50, + Top = 500, + // Apply the AutoFit behavior + ColumnAdjustment = ColumnAdjustment.AutoFitToContent + }; + + // Define a simple 2‑column layout (ColumnWidths is a string, not a collection) + tableFitToContent.ColumnWidths = "200 200"; + + // Add a header row + Row headerRow = tableFitToContent.Rows.Add(); + headerRow.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 1") } }); + headerRow.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 2") } }); + + // Add a data row with longer text to demonstrate fitting + Row dataRow = tableFitToContent.Rows.Add(); + dataRow.Cells.Add(new Cell { Paragraphs = { new TextFragment("This is a very long piece of text that should cause the column to shrink to fit its content.") } }); + dataRow.Cells.Add(new Cell { Paragraphs = { new TextFragment("Short") } }); + + // Add the table to the page + page.Paragraphs.Add(tableFitToContent); + + // ------------------------------------------------------------ + // Table 2 – AutoFit to window (columns expand to fill the table width) + // ------------------------------------------------------------ + Table tableFitToWindow = new Table + { + Left = 50, + Top = 300, + // Apply the other AutoFit behavior + ColumnAdjustment = ColumnAdjustment.AutoFitToWindow + }; + + // Same 2‑column layout + tableFitToWindow.ColumnWidths = "200 200"; + + // Header row + Row headerRow2 = tableFitToWindow.Rows.Add(); + headerRow2.Cells.Add(new Cell { Paragraphs = { new TextFragment("Column A") } }); + headerRow2.Cells.Add(new Cell { Paragraphs = { new TextFragment("Column B") } }); + + // Data row + Row dataRow2 = tableFitToWindow.Rows.Add(); + dataRow2.Cells.Add(new Cell { Paragraphs = { new TextFragment("Short") } }); + dataRow2.Cells.Add(new Cell { Paragraphs = { new TextFragment("Another short text") } }); + + // Add the second table to the page + page.Paragraphs.Add(tableFitToWindow); + + // Save the modified PDF (using the standard Save method) + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved with tables to '{outputPath}'."); + } +} diff --git a/working-with-tables/apply-solid-border-to-pdf-table.cs b/working-with-tables/apply-solid-border-to-pdf-table.cs new file mode 100644 index 00000000..f85d5998 --- /dev/null +++ b/working-with-tables/apply-solid-border-to-pdf-table.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; // BorderSide enum is in Aspose.Pdf namespace, but keeping for clarity + +class Program +{ + static void Main() + { + // Create a new PDF document and add a blank page + using (Document doc = new Document()) + { + Page page = doc.Pages.Add(); + + // Create a table + Table table = new Table(); + + // Configure a solid black border of width 2 points on all sides + BorderInfo border = new BorderInfo( + BorderSide.Left | BorderSide.Top | BorderSide.Right | BorderSide.Bottom, + 2f, // border width + Aspose.Pdf.Color.Black); // border color + + table.Border = border; + + // (Optional) Add a simple row and cell so the table is visible + Row row = table.Rows.Add(); + Cell cell = row.Cells.Add("Sample cell"); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + string outputPath = "TableWithBorder.pdf"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF could not be saved using Document.Save()."); + } + } + } + } + + // Helper method to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/auto-fit-row-height-in-pdf-table.cs b/working-with-tables/auto-fit-row-height-in-pdf-table.cs new file mode 100644 index 00000000..f7ae61b0 --- /dev/null +++ b/working-with-tables/auto-fit-row-height-in-pdf-table.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "autoheight_table.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and configure its appearance + Table table = new Table + { + // Two columns with equal width + ColumnWidths = "200 200", + // Table border + Border = new BorderInfo(BorderSide.All, 1f), + // Default cell border and padding + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5), + // Default text style for cells + DefaultCellTextState = new TextState + { + Font = FontRepository.FindFont("Helvetica"), + FontSize = 12, + ForegroundColor = Color.Black + } + }; + + // Add a row to the table + Row row = table.Rows.Add(); + + // Enable automatic height adjustment. + // Setting FixedRowHeight to 0 (or leaving it unset) lets the row grow + // to fit the content of its cells. + row.FixedRowHeight = 0; + + // Add cells with different amounts of text + row.Cells.Add("Short text"); + row.Cells.Add("This is a longer piece of text that should cause the row height to increase automatically to fit the content."); + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the document. + // On non‑Windows platforms the PDF save may require GDI+ (libgdiplus). + // Wrap the save in a try‑catch to handle missing native libraries gracefully. + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || + RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + try + { + doc.Save(outputPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Skipping save on this platform: GDI+ (libgdiplus) is not available."); + } + } + else + { + doc.Save(outputPath); + } + } + + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/auto-fit-table-columns-to-content.cs b/working-with-tables/auto-fit-table-columns-to-content.cs new file mode 100644 index 00000000..17e2c4d8 --- /dev/null +++ b/working-with-tables/auto-fit-table-columns-to-content.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "output.pdf"; + + using (Document doc = new Document()) + { + Page page = doc.Pages.Add(); + + Table table = new Table + { + Left = 50, + Top = 700, + // Adjust column widths based on content + ColumnAdjustment = ColumnAdjustment.AutoFitToContent + // No DefaultCellAutoFitBehavior property – ColumnAdjustment handles auto‑fit for cells + }; + + // First row + Row row1 = table.Rows.Add(); + Cell cell11 = row1.Cells.Add(); + cell11.Paragraphs.Add(new TextFragment("Short")); + Cell cell12 = row1.Cells.Add(); + cell12.Paragraphs.Add(new TextFragment("A much longer piece of text that should cause the column to expand automatically.")); + + // Second row + Row row2 = table.Rows.Add(); + Cell cell21 = row2.Cells.Add(); + cell21.Paragraphs.Add(new TextFragment("Another")); + Cell cell22 = row2.Cells.Add(); + cell22.Paragraphs.Add(new TextFragment("Text")); + + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/batch-add-table-with-logo-to-pdfs.cs b/working-with-tables/batch-add-table-with-logo-to-pdfs.cs new file mode 100644 index 00000000..2d309175 --- /dev/null +++ b/working-with-tables/batch-add-table-with-logo-to-pdfs.cs @@ -0,0 +1,86 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class BatchAddTableWithLogo +{ + static void Main() + { + // Resolve input and output folders relative to the executable location. + // This makes the code work on any OS (Windows, Linux, macOS). + string baseDir = AppDomain.CurrentDomain.BaseDirectory; + string inputFolder = Path.Combine(baseDir, "InputPdfs"); + string outputFolder = Path.Combine(baseDir, "OutputPdfs"); + // Path to the company logo image (PNG, JPG, etc.) – also resolved relative to the base directory. + string logoPath = Path.Combine(baseDir, "Resources", "logo.png"); + + // Validate that the required folders/files exist before proceeding. + if (!Directory.Exists(inputFolder)) + { + Console.Error.WriteLine($"Input folder does not exist: {inputFolder}"); + return; + } + if (!File.Exists(logoPath)) + { + Console.Error.WriteLine($"Logo image not found: {logoPath}"); + return; + } + + // Ensure the output directory exists. + Directory.CreateDirectory(outputFolder); + + // Process each PDF file in the input folder. + foreach (string pdfFile in Directory.GetFiles(inputFolder, "*.pdf")) + { + // Determine output file path (same name, different folder). + string outputPath = Path.Combine(outputFolder, Path.GetFileName(pdfFile)); + + // Load the PDF document inside a using block for deterministic disposal. + using (Document doc = new Document(pdfFile)) + { + // Get the first page (Aspose.Pdf uses 1‑based indexing). + Page page = doc.Pages[1]; + + // Create a table that will hold the logo and accompanying text. + Table table = new Table + { + // Define two columns: first for the logo, second for the text. + ColumnWidths = "100 400", + // Optional visual styling. + Border = new BorderInfo(BorderSide.All, 1f, Aspose.Pdf.Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Gray), + DefaultCellPadding = new MarginInfo(5f, 5f, 5f, 5f) + }; + + // Add a single row to the table. + var row = table.Rows.Add(); + + // ----- Logo cell ----- + var logoCell = row.Cells.Add(); + Image logoImage = new Image { File = logoPath }; + // Optionally set a fixed width/height to fit the cell (adjust as needed). + // logoImage.FixWidth = 80f; // example + logoCell.Paragraphs.Add(logoImage); + + // ----- Text cell ----- + var textCell = row.Cells.Add(); + TextFragment companyName = new TextFragment("Acme Corporation"); + companyName.TextState.FontSize = 14; + companyName.TextState.Font = FontRepository.FindFont("Helvetica"); + companyName.TextState.ForegroundColor = Aspose.Pdf.Color.DarkBlue; + textCell.Paragraphs.Add(companyName); + + // Insert the table at the beginning of the page's content. + page.Paragraphs.Insert(0, table); + + // Save the modified document to the output location. + doc.Save(outputPath); + } + + Console.WriteLine($"Processed: {Path.GetFileName(pdfFile)} → {outputPath}"); + } + + Console.WriteLine("Batch processing completed."); + } +} diff --git a/working-with-tables/batch-replace-tables-in-pdfs.cs b/working-with-tables/batch-replace-tables-in-pdfs.cs new file mode 100644 index 00000000..fce953b4 --- /dev/null +++ b/working-with-tables/batch-replace-tables-in-pdfs.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class BatchTableReplacer +{ + static void Main() + { + // Folder containing source PDFs + const string inputFolder = "InputPdfs"; + // Folder where updated PDFs will be saved + const string outputFolder = "OutputPdfs"; + + // Ensure output directory exists + Directory.CreateDirectory(outputFolder); + + // Verify that the input folder exists; if not, inform the user and exit gracefully + if (!Directory.Exists(inputFolder)) + { + Console.WriteLine($"Input folder '{inputFolder}' does not exist. No files to process."); + return; + } + + // Process each PDF file in the input folder + foreach (string inputPath in Directory.GetFiles(inputFolder, "*.pdf")) + { + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate through all pages (Aspose.Pdf uses 1‑based indexing) + for (int pageIndex = 1; pageIndex <= doc.Pages.Count; pageIndex++) + { + Page page = doc.Pages[pageIndex]; + + // Find all tables on the current page + TableAbsorber absorber = new TableAbsorber(); + absorber.Visit(page); + + // Work on a copy of the TableList to avoid collection modification issues + List tables = absorber.TableList.ToList(); + + // Replace each absorbed table with a newly created table + foreach (AbsorbedTable oldTable in tables) + { + // Create a new table with the same number of rows and columns as the old one + Table newTable = new Table(); + + // Replicate rows and cells (here we simply fill each cell with placeholder text) + foreach (var oldRow in oldTable.RowList) + { + var newRow = newTable.Rows.Add(); + foreach (var oldCell in oldRow.CellList) + { + var newCell = newRow.Cells.Add(); + // Insert placeholder text; customize as needed + newCell.Paragraphs.Add(new TextFragment("Updated")); + } + } + + // Replace the old table with the new table on the page + absorber.Replace(page, oldTable, newTable); + } + } + + // Save the modified document to the output folder (PDF format) + string outputPath = Path.Combine(outputFolder, Path.GetFileName(inputPath)); + doc.Save(outputPath); + } + + Console.WriteLine($"Processed and saved: {Path.GetFileName(inputPath)}"); + } + } +} diff --git a/working-with-tables/calculate-remaining-page-space-add-table.cs b/working-with-tables/calculate-remaining-page-space-add-table.cs new file mode 100644 index 00000000..7283df0a --- /dev/null +++ b/working-with-tables/calculate-remaining-page-space-add-table.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // needed for TextFragment + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the source PDF + using (Document doc = new Document(inputPath)) + { + // Aspose.Pdf uses 1‑based page indexing + Page page = doc.Pages[1]; + + // Calculate the bounding box of existing content (without visible margins) + Aspose.Pdf.Rectangle contentBox = page.CalculateContentBBox(); + + // Height of the existing content + double contentHeight = contentBox.URY - contentBox.LLY; + + // Total usable page height (excluding page margins) + double pageHeight = page.PageInfo.PureHeight; + + // Remaining vertical space on the page + double remainingSpace = pageHeight - contentHeight; + + // Create a simple table + Table table = new Table + { + ColumnWidths = "100 100" + }; + + // First row + Row row1 = new Row(); + row1.Cells.Add(new Cell { Paragraphs = { new TextFragment("Cell 1") } }); + row1.Cells.Add(new Cell { Paragraphs = { new TextFragment("Cell 2") } }); + table.Rows.Add(row1); + + // Second row + Row row2 = new Row(); + row2.Cells.Add(new Cell { Paragraphs = { new TextFragment("Cell 3") } }); + row2.Cells.Add(new Cell { Paragraphs = { new TextFragment("Cell 4") } }); + table.Rows.Add(row2); + + // Get the height the table would occupy on this page + double tableHeight = table.GetHeight(page); + + // Ensure the table fits into the remaining space + if (tableHeight > remainingSpace) + { + Console.WriteLine("Not enough space on the page for the table. Adjusting position to start at the top margin."); + // Position the table at the top of the page (below the top margin) + table.Top = (float)page.PageInfo.Margin.Top; + } + else + { + // Position the table just below the existing content + table.Top = (float)(contentBox.LLY - tableHeight); + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/center-table-in-pdf.cs b/working-with-tables/center-table-in-pdf.cs new file mode 100644 index 00000000..19d4da1d --- /dev/null +++ b/working-with-tables/center-table-in-pdf.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; // Existing PDF (optional) + const string outputPath = "centered_table.pdf"; + + // Load existing PDF if it exists; otherwise create a new empty document. + using (Document doc = File.Exists(inputPath) ? new Document(inputPath) : new Document()) + { + // Ensure there is at least one page to host the table. + if (doc.Pages.Count == 0) + doc.Pages.Add(); + + // Create a table instance and center it on the page. + Table table = new Table + { + HorizontalAlignment = HorizontalAlignment.Center, // Center the whole table + ColumnAdjustment = ColumnAdjustment.AutoFitToContent // Optional auto‑fit + }; + + // Add a simple row with two cells (demo content). + Row row = table.Rows.Add(); + row.Cells.Add("Cell 1"); + row.Cells.Add("Cell 2"); + + // Insert the table into the first page's paragraph collection. + doc.Pages[1].Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ on non‑Windows platforms. + SaveDocument(doc, outputPath); + } + + Console.WriteLine($"PDF processing completed. Output: '{outputPath}'."); + } + + private static void SaveDocument(Document doc, string path) + { + // On Windows the native GDI+ library is always present. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(path); + return; + } + + // On macOS / Linux the Aspose.Pdf engine may try to load libgdiplus. + // Wrap the call in a try‑catch that looks for a nested DllNotFoundException. + try + { + doc.Save(path); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF was saved without GDI‑dependent features."); + } + } + + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/check-table-isbroken-property.cs b/working-with-tables/check-table-isbroken-property.cs new file mode 100644 index 00000000..2873bed0 --- /dev/null +++ b/working-with-tables/check-table-isbroken-property.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Paths for input and output PDFs + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + // If the input file does not exist, create a simple PDF with one blank page + if (!File.Exists(inputPath)) + { + using (Document newDoc = new Document()) + { + newDoc.Pages.Add(); // add a blank page + newDoc.Save(inputPath); + } + } + + // Load the PDF using the recommended load pattern + using (Document doc = new Document(inputPath)) + { + // Retrieve the first page (Aspose.Pdf uses 1‑based indexing) + Page page = doc.Pages[1]; + + // Create a table and configure basic layout properties + Table table = new Table + { + ColumnWidths = "100 100 100", // three equal columns + Border = new BorderInfo(BorderSide.All, 1f, Aspose.Pdf.Color.Black), + IsBroken = false // default: do not break across pages + }; + + // Add a single row with three cells + Row row = table.Rows.Add(); + row.Cells.Add("Cell 1"); + row.Cells.Add("Cell 2"); + row.Cells.Add("Cell 3"); + + // Insert the table into the page's paragraph collection + page.Paragraphs.Add(table); + + // Check whether the table is set to break onto the next page + bool willBreak = table.IsBroken; + Console.WriteLine($"Table.IsBroken (initial) = {willBreak}"); + + // For demonstration, force the table to break and verify the change + table.IsBroken = true; + Console.WriteLine($"Table.IsBroken (after setting) = {table.IsBroken}"); + + // Save the modified document with a guard for platforms lacking GDI+ (e.g., macOS/Linux) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + } + else + { + try + { + doc.Save(outputPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF saved without GDI+ dependent features."); + } + } + } + + Console.WriteLine($"Document saved to '{outputPath}'."); + } + + // Helper to detect a nested DllNotFoundException (libgdiplus) inside a TypeInitializationException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/conditional-formatting-table-cells.cs b/working-with-tables/conditional-formatting-table-cells.cs new file mode 100644 index 00000000..d2e581ea --- /dev/null +++ b/working-with-tables/conditional-formatting-table-cells.cs @@ -0,0 +1,79 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Drawing; + +class ConditionalFormattingExample +{ + static void Main() + { + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and add it to the page + Table table = new Table + { + // Define three equal-width columns + ColumnWidths = "100 100 100" + }; + page.Paragraphs.Add(table); + + // Sample numeric data to populate the table + double[,] data = new double[,] { + { 30, 75, 120 }, + { 55, 45, 200 } + }; + + // Iterate over the data array, create rows/cells, and apply conditional formatting + for (int i = 0; i < data.GetLength(0); i++) + { + // Add a new row to the table + Row row = table.Rows.Add(); + + for (int j = 0; j < data.GetLength(1); j++) + { + double value = data[i, j]; + + // Add a new cell to the current row + Cell cell = row.Cells.Add(); + + // Insert the numeric value as text into the cell + TextFragment tf = new TextFragment(value.ToString()); + cell.Paragraphs.Add(tf); + + // Conditional background color based on the numeric value + if (value > 100) + { + // Values greater than 100 get a LightGoldenrodYellow background + cell.BackgroundColor = Color.LightGoldenrodYellow; + } + else if (value > 50) + { + // Values between 51 and 100 get a LemonChiffon background + cell.BackgroundColor = Color.LemonChiffon; + } + // Values 50 or below keep the default background (no color set) + } + } + + // Save the PDF with the formatted table – guard against missing GDI+ on non‑Windows platforms + string outputPath = "conditional_table.pdf"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + Console.WriteLine("libgdiplus (GDI+) is required for PDF creation on this platform. " + + "Skipping doc.Save() to avoid TypeInitializationException."); + } + } + + Console.WriteLine("Execution completed."); + } +} \ No newline at end of file diff --git a/working-with-tables/count-tables-in-pdf.cs b/working-with-tables/count-tables-in-pdf.cs new file mode 100644 index 00000000..beaf1893 --- /dev/null +++ b/working-with-tables/count-tables-in-pdf.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document; using ensures proper disposal + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to search for tables + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from the entire document + absorber.Visit(doc); + + // The TableList collection holds all found tables + int tableCount = absorber.TableList.Count; + + Console.WriteLine($"Number of tables found: {tableCount}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-fixed-width-table.cs b/working-with-tables/create-fixed-width-table.cs new file mode 100644 index 00000000..d9d14edc --- /dev/null +++ b/working-with-tables/create-fixed-width-table.cs @@ -0,0 +1,67 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a blank page + Page page = doc.Pages.Add(); + + // Create a table with a fixed total width of 500 points + Table table = new Table(); + table.ColumnWidths = "500"; // defines the total table width + table.DefaultColumnWidth = "500"; // default width for columns without explicit width + + // Add a row with a single cell + Row row = table.Rows.Add(); + Cell cell = row.Cells.Add(); + cell.Paragraphs.Add(new TextFragment("Fixed width table cell")); + + // Position the table on the page (optional) + table.Left = 50; // 50 points from the left edge + table.Top = 750; // 750 points from the bottom edge + + // Add the table to the page + page.Paragraphs.Add(table); + + string outputPath = "FixedWidthTable.pdf"; + + // Guard Document.Save against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/create-pdf-table-from-datatable.cs b/working-with-tables/create-pdf-table-from-datatable.cs new file mode 100644 index 00000000..8e303216 --- /dev/null +++ b/working-with-tables/create-pdf-table-from-datatable.cs @@ -0,0 +1,72 @@ +using System; +using System.Data; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // ------------------------------------------------------------------- + // Create an in‑memory DataTable with sample data. + // ------------------------------------------------------------------- + DataTable dataTable = new DataTable(); + dataTable.Columns.Add("Id", typeof(int)); + dataTable.Columns.Add("Name", typeof(string)); + dataTable.Columns.Add("Quantity", typeof(int)); + + dataTable.Rows.Add(1, "Apple", 10); + dataTable.Rows.Add(2, "Banana", 20); + dataTable.Rows.Add(3, "Cherry", 15); + + // Create a new PDF document and add a page + using (Document pdfDocument = new Document()) + { + Page page = pdfDocument.Pages.Add(); + + // Create a table and import the DataTable into it + Table table = new Table(); + table.ColumnWidths = "100 200 100"; // widths are in points + table.ImportDataTable(dataTable, true, 0, 0); + page.Paragraphs.Add(table); + + string outputPath = "output.pdf"; + + // ------------------------------------------------------------------- + // Save the PDF – guard the call on non‑Windows platforms where libgdiplus + // (required by Aspose.Pdf for GDI+) may be missing. + // ------------------------------------------------------------------- + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + pdfDocument.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + pdfDocument.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + + Console.WriteLine("Program finished."); + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException. + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/create-pdf-table-from-datatable__v2.cs b/working-with-tables/create-pdf-table-from-datatable__v2.cs new file mode 100644 index 00000000..8cc6e505 --- /dev/null +++ b/working-with-tables/create-pdf-table-from-datatable__v2.cs @@ -0,0 +1,90 @@ +using System; +using System.Data; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; // for TextState if needed + +class Program +{ + static void Main() + { + // Paths + const string outputPath = "table_output.pdf"; + + // Prepare source data (DataTable) – in real scenarios this could come from a database + DataTable sourceTable = new DataTable("SampleData"); + sourceTable.Columns.Add("ID", typeof(int)); + sourceTable.Columns.Add("Name", typeof(string)); + sourceTable.Columns.Add("Quantity", typeof(int)); + + // Populate the DataTable with sample rows (dynamic row count) + for (int i = 1; i <= 15; i++) + { + sourceTable.Rows.Add(i, $"Item {i}", i * 10); + } + + // Determine number of source records (rows) before import + int recordCount = sourceTable.Rows.Count; + Console.WriteLine($"Source records to import: {recordCount}"); + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page + Page page = doc.Pages.Add(); + + // Create a Table instance + Table table = new Table + { + Border = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5), + // Three equal columns (adjust widths as needed) + ColumnWidths = "100 200 100" + }; + + // Import the DataTable into the Aspose.Pdf.Table + // sourceTable – the DataTable to import + // true – import column names as the first row + // 0 – start importing at the first row of the PDF table (zero‑based) + // 0 – start importing at the first column of the PDF table (zero‑based) + table.ImportDataTable(sourceTable, true, 0, 0); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF with table saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF with table saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF was generated in memory but could not be saved to disk."); + } + } + } + } + + // Helper that walks the exception chain looking for a DllNotFoundException (e.g., libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/create-repeating-table-header.cs b/working-with-tables/create-repeating-table-header.cs new file mode 100644 index 00000000..23bc63bb --- /dev/null +++ b/working-with-tables/create-repeating-table-header.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Tagged; +using Aspose.Pdf.LogicalStructure; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_with_header.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF inside a using block for proper disposal + using (Document doc = new Document(inputPath)) + { + // Access tagged content API + ITaggedContent tagged = doc.TaggedContent; + tagged.SetLanguage("en-US"); + tagged.SetTitle("Document with repeating table header"); + + // Root element of the logical structure tree + StructureElement root = tagged.RootElement; + + // Create a table element and attach it to the root + TableElement table = tagged.CreateTableElement(); + table.AlternativeText = "Sample data table with repeating header"; + root.AppendChild(table); + + // Create the table header (THead) group + TableTHeadElement thead = tagged.CreateTableTHeadElement(); + table.AppendChild(thead); + + // Create a header row inside the THead + TableTRElement headerRow = tagged.CreateTableTRElement(); + thead.AppendChild(headerRow); + + // Mark the row as a header that should repeat on new pages + headerRow.IsInNewPage = true; // makes the row repeat + table.RepeatingRowsCount = 1; // first row (header) repeats + + // Add header cells + TableTHElement th1 = tagged.CreateTableTHElement(); + th1.SetText("Column A"); + headerRow.AppendChild(th1); + + TableTHElement th2 = tagged.CreateTableTHElement(); + th2.SetText("Column B"); + headerRow.AppendChild(th2); + + // Create the table body (TBody) group + TableTBodyElement tbody = tagged.CreateTableTBodyElement(); + table.AppendChild(tbody); + + // Add a sample data row + TableTRElement dataRow = tagged.CreateTableTRElement(); + tbody.AppendChild(dataRow); + + TableTDElement td1 = tagged.CreateTableTDElement(); + td1.SetText("Value 1"); + dataRow.AppendChild(td1); + + TableTDElement td2 = tagged.CreateTableTDElement(); + td2.SetText("Value 2"); + dataRow.AppendChild(td2); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Saved PDF with repeating table header to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/create-table-stretched-to-page-width.cs b/working-with-tables/create-table-stretched-to-page-width.cs new file mode 100644 index 00000000..1f481109 --- /dev/null +++ b/working-with-tables/create-table-stretched-to-page-width.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "TableAutoFitToPageWidth.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and stretch it to the page width by setting column widths proportionally + Table table = new Table(); + + // Calculate equal column widths that fill the entire page width + double pageWidth = page.PageInfo.Width; // total page width (points) + double colWidth = pageWidth / 3.0; // three equal columns + table.ColumnWidths = $"{colWidth} {colWidth} {colWidth}"; + + // Add a header row + Row header = table.Rows.Add(); + header.Cells.Add("Header 1"); + header.Cells.Add("Header 2"); + header.Cells.Add("Header 3"); + + // Add a few data rows + for (int i = 1; i <= 5; i++) + { + Row row = table.Rows.Add(); + row.Cells.Add($"Row {i} - Col 1"); + row.Cells.Add($"Row {i} - Col 2"); + row.Cells.Add($"Row {i} - Col 3"); + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/create-table-with-2-point-border.cs b/working-with-tables/create-table-with-2-point-border.cs new file mode 100644 index 00000000..427340c1 --- /dev/null +++ b/working-with-tables/create-table-with-2-point-border.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Drawing; +using Aspose.Pdf.Annotations; + +class Program +{ + static void Main() + { + // Output PDF path + const string outputPath = "table_with_border.pdf"; + + // Create a new PDF document inside a using block for proper disposal + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and set its position and size + Table table = new Table + { + // Position the table on the page (left, top) + Left = 50, + Top = 700, + // Define column widths (example: two columns) + ColumnWidths = "200 200" + }; + + // Set the table border thickness to 2 points using the BorderInfo constructor + table.Border = new BorderInfo(BorderSide.All, 2f); + + // Add a simple row with two cells for demonstration + Row row = table.Rows.Add(); + row.Cells.Add("Header 1"); + row.Cells.Add("Header 2"); + + // Add a second row + Row row2 = table.Rows.Add(); + row2.Cells.Add("Data 1"); + row2.Cells.Add("Data 2"); + + // Demonstrate correct usage of RichMediaAnnotation without setting an invalid property. + // Use the fully‑qualified Aspose.Pdf.Rectangle to avoid ambiguity. + RichMediaAnnotation richMedia = new RichMediaAnnotation(page, new Aspose.Pdf.Rectangle(100, 500, 300, 600)); + // Note: Activation property is not available in the current API version; omit it. + page.Annotations.Add(richMedia); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF document – guard against missing libgdiplus on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + Console.WriteLine("libgdiplus is required for PDF creation on this platform. Skipping doc.Save()."); + } + } + } +} diff --git a/working-with-tables/create-table-with-colspan.cs b/working-with-tables/create-table-with-colspan.cs new file mode 100644 index 00000000..547b733a --- /dev/null +++ b/working-with-tables/create-table-with-colspan.cs @@ -0,0 +1,83 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; // required for TextState, if needed + +class Program +{ + static void Main() + { + // Create a new PDF document inside a using block for deterministic disposal + using (Document doc = new Document()) + { + // Add a blank page (first page, 1‑based indexing) + Page page = doc.Pages.Add(); + + // Create a table with three columns + Table table = new Table + { + // Define equal column widths (you can adjust as needed) + ColumnWidths = "150 150 150" + }; + + // ---------- First row: a merged cell spanning three columns ---------- + Row mergedRow = table.Rows.Add(); // Add a new row + Cell mergedCell = mergedRow.Cells.Add("Merged Cell"); // Add a cell with text + mergedCell.ColSpan = 3; // Merge three adjacent columns + + // Optional: set some visual styling for the merged cell + mergedCell.BackgroundColor = Color.LightGray; + mergedCell.DefaultCellTextState = new TextState + { + FontSize = 14, + Font = FontRepository.FindFont("Helvetica"), + ForegroundColor = Color.Black, + FontStyle = FontStyles.Bold + }; + + // ---------- Second row: regular three separate cells ---------- + Row normalRow = table.Rows.Add(); + normalRow.Cells.Add("Cell 1"); + normalRow.Cells.Add("Cell 2"); + normalRow.Cells.Add("Cell 3"); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + string outputPath = "TableWithColSpan.pdf"; + + // Guard Document.Save against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + } + else + { + try + { + doc.Save(outputPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF was not saved using Aspose.Pdf's rendering engine."); + } + } + } + + Console.WriteLine("PDF creation routine finished."); + } + + // Helper method to walk the inner‑exception chain and detect a missing native library + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/create-table-with-rows-in-pdf.cs b/working-with-tables/create-table-with-rows-in-pdf.cs new file mode 100644 index 00000000..e6b44568 --- /dev/null +++ b/working-with-tables/create-table-with-rows-in-pdf.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Output PDF path + const string outputPath = "table_output.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a Table object + Table table = new Table + { + // Optional: set table position and width + Left = 50, + Top = 700, + ColumnWidths = "100 150 200" // three columns with specified widths + }; + + // ----- Add first (header) row ----- + Row row1 = table.Rows.Add(); // creates a new Row and adds it to the table + // Populate cells in the first row + row1.Cells.Add("Header 1"); + row1.Cells.Add("Header 2"); + row1.Cells.Add("Header 3"); + + // Apply a simple style to the header row + row1.DefaultCellTextState = new TextState + { + FontSize = 12, + FontStyle = FontStyles.Bold, + ForegroundColor = Color.White + }; + // Set background colour for each cell (Row does not expose DefaultCellBackgroundColor) + foreach (Cell cell in row1.Cells) + { + cell.BackgroundColor = Color.Gray; + } + + // ----- Add second row ----- + Row row2 = table.Rows.Add(); + row2.Cells.Add("Row 1, Col 1"); + row2.Cells.Add("Row 1, Col 2"); + row2.Cells.Add("Row 1, Col 3"); + + // ----- Add third row ----- + Row row3 = table.Rows.Add(); + row3.Cells.Add("Row 2, Col 1"); + row3.Cells.Add("Row 2, Col 2"); + row3.Cells.Add("Row 2, Col 3"); + + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // Save the PDF document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/detect-merged-cells-in-pdf-tables.cs b/working-with-tables/detect-merged-cells-in-pdf-tables.cs new file mode 100644 index 00000000..2d904914 --- /dev/null +++ b/working-with-tables/detect-merged-cells-in-pdf-tables.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber and enable the FlowEngine to get ColSpan values + TableAbsorber absorber = new TableAbsorber + { + UseFlowEngine = true + }; + + // Extract tables from the whole document + absorber.Visit(doc); + + // Iterate over each detected table + for (int t = 0; t < absorber.TableList.Count; t++) + { + var table = absorber.TableList[t]; + Console.WriteLine($"Table {t + 1} found on page {table.PageNum}"); + + // Iterate over rows + for (int r = 0; r < table.RowList.Count; r++) + { + var row = table.RowList[r]; + + // Iterate over cells in the row + for (int c = 0; c < row.CellList.Count; c++) + { + AbsorbedCell cell = row.CellList[c]; + + // ColSpan > 1 indicates a merged (horizontally spanned) cell + if (cell.ColSpan > 1) + { + Console.WriteLine( + $" Merged cell detected at Table {t + 1}, Row {r + 1}, Column {c + 1} " + + $"(ColSpan = {cell.ColSpan})"); + } + + // If RowSpan were available on AbsorbedCell, you would check similarly: + // if (cell.RowSpan > 1) { ... } + } + } + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/embed-html-fragment-in-table-cell.cs b/working-with-tables/embed-html-fragment-in-table-cell.cs new file mode 100644 index 00000000..6f186ae2 --- /dev/null +++ b/working-with-tables/embed-html-fragment-in-table-cell.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "table_with_html.pdf"; + + // Create a new PDF document inside a using block for deterministic disposal + using (Document doc = new Document()) + { + // Add a blank page to the document + Page page = doc.Pages.Add(); + + // Create a table with a single column (width 200 points) + Table table = new Table { ColumnWidths = "200" }; + + // Add a row to the table + Row row = table.Rows.Add(); + + // Add a cell to the row + Cell cell = row.Cells.Add(); + + // HTML markup to embed inside the cell + string html = "Hello World
Red Text"; + + // Create an HtmlFragment from the markup + HtmlFragment htmlFragment = new HtmlFragment(html); + + // Add the HtmlFragment to the cell's paragraph collection + cell.Paragraphs.Add(htmlFragment); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/enable-table-splitting-across-pdf-pages.cs b/working-with-tables/enable-table-splitting-across-pdf-pages.cs new file mode 100644 index 00000000..11a0f023 --- /dev/null +++ b/working-with-tables/enable-table-splitting-across-pdf-pages.cs @@ -0,0 +1,76 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "table_split.pdf"; + + // Create a new PDF document and ensure deterministic disposal + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and enable breaking across pages + Table table = new Table + { + IsBroken = true, // Allow the table to split across pages + ColumnWidths = "100 200 100" // Define column widths (optional) + }; + + // Add a header row + Row header = table.Rows.Add(); + header.Cells.Add("ID"); + header.Cells.Add("Description"); + header.Cells.Add("Value"); + + // Populate the table with enough rows to require pagination + for (int i = 1; i <= 100; i++) + { + Row row = table.Rows.Add(); + row.Cells.Add(i.ToString()); + row.Cells.Add($"Item number {i}"); + row.Cells.Add((i * 10).ToString()); + } + + // Add the table to the page's content + page.Paragraphs.Add(table); + + // Save the PDF document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF could not be saved."); + } + } + } + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/export-pdf-table-to-csv.cs b/working-with-tables/export-pdf-table-to-csv.cs new file mode 100644 index 00000000..9a61f5d2 --- /dev/null +++ b/working-with-tables/export-pdf-table-to-csv.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputCsv = "output.csv"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"File not found: {inputPdf}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document doc = new Document(inputPdf)) + { + // Configure ExcelSaveOptions to export as CSV (non‑PDF format requires explicit options) + ExcelSaveOptions csvOptions = new ExcelSaveOptions + { + Format = ExcelSaveOptions.ExcelFormat.CSV + }; + + // Save the document as CSV; each table cell is written as a comma‑separated value + doc.Save(outputCsv, csvOptions); + } + + Console.WriteLine($"CSV file created at '{outputCsv}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/export-tagged-table-structure-to-json.cs b/working-with-tables/export-tagged-table-structure-to-json.cs new file mode 100644 index 00000000..4c811a81 --- /dev/null +++ b/working-with-tables/export-tagged-table-structure-to-json.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Aspose.Pdf; +using Aspose.Pdf.Tagged; +using Aspose.Pdf.LogicalStructure; + +class ExportTableStructureToJson +{ + // DTO for a table cell + private class CellDto + { + public string? ActualText { get; set; } + public string? AlternativeText { get; set; } + public string? Title { get; set; } + public string? Alignment { get; set; } + public string? BackgroundColor { get; set; } + public string? Border { get; set; } + public int? RowSpan { get; set; } + public int? ColSpan { get; set; } + } + + // DTO for a table row + private class RowDto + { + public string? AlternativeText { get; set; } + public string? Title { get; set; } + public string? BackgroundColor { get; set; } + public string? Border { get; set; } + public List Cells { get; set; } = new List(); + } + + // DTO for a table + private class TableDto + { + public string? AlternativeText { get; set; } + public string? Title { get; set; } + public string? Alignment { get; set; } + public string? BackgroundColor { get; set; } + public string? Border { get; set; } + public List Rows { get; set; } = new List(); + } + + static void Main() + { + const string inputPdfPath = "input.pdf"; // source PDF containing a tagged table + const string outputJsonPath = "table_structure.json"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"File not found: {inputPdfPath}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document doc = new Document(inputPdfPath)) + { + // Access tagged content (must use ITaggedContent, not cast Document) + ITaggedContent taggedContent = doc.TaggedContent; + + // Find all TableElement objects in the structure tree (recursive search) + var tableElements = taggedContent.RootElement.FindElements(true); + + var tables = new List(); + + foreach (TableElement table in tableElements) + { + TableDto tableDto = new TableDto { + AlternativeText = table.AlternativeText, + Title = table.Title, + // HorizontalAlignment is a non‑nullable enum; use direct ToString() + Alignment = table.Alignment.ToString(), + BackgroundColor = table.BackgroundColor?.ToString(), + Border = table.Border?.ToString() + }; + + // Iterate over child elements of the table (rows) + foreach (Element rowElem in table.ChildElements) + { + if (rowElem is TableTRElement row) + { + RowDto rowDto = new RowDto { + AlternativeText = row.AlternativeText, + Title = row.Title, + BackgroundColor = row.BackgroundColor?.ToString(), + Border = row.Border?.ToString() + }; + + // Iterate over cells within the row + foreach (Element cellElem in row.ChildElements) + { + if (cellElem is TableTDElement cell) + { + CellDto cellDto = new CellDto { + ActualText = cell.ActualText, + AlternativeText = cell.AlternativeText, + Title = cell.Title, + // HorizontalAlignment is a non‑nullable enum; use direct ToString() + Alignment = cell.Alignment.ToString(), + BackgroundColor = cell.BackgroundColor?.ToString(), + Border = cell.Border?.ToString(), + RowSpan = cell.RowSpan, + ColSpan = cell.ColSpan + }; + rowDto.Cells.Add(cellDto); + } + } + + tableDto.Rows.Add(rowDto); + } + } + + tables.Add(tableDto); + } + + // Serialize the collected table structures to JSON + JsonSerializerOptions jsonOptions = new JsonSerializerOptions { WriteIndented = true }; + string json = JsonSerializer.Serialize(tables, jsonOptions); + + // Write JSON to file + File.WriteAllText(outputJsonPath, json); + Console.WriteLine($"Table structure exported to '{outputJsonPath}'."); + } + } +} diff --git a/working-with-tables/extract-modify-tables-rotated-pages.cs b/working-with-tables/extract-modify-tables-rotated-pages.cs new file mode 100644 index 00000000..e7b5cd17 --- /dev/null +++ b/working-with-tables/extract-modify-tables-rotated-pages.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Open the PDF document with deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Pages are 1‑based in Aspose.Pdf + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // Check if the page has any rotation applied + if (page.Rotate != Rotation.None) + { + Console.WriteLine($"Page {i} is rotated: {page.Rotate}"); + + // Create a TableAbsorber for the current page + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables on this rotated page + absorber.Visit(page); + + // Iterate over all tables found on the page + foreach (AbsorbedTable table in absorber.TableList) + { + Console.WriteLine($" Table found on page {i} at rectangle {table.Rectangle}"); + Console.WriteLine($" Rows: {table.RowList.Count}"); + + // Example modification: change text of the first fragment in the first cell + if (table.RowList.Count > 0 && table.RowList[0].CellList.Count > 0) + { + var cell = table.RowList[0].CellList[0]; + if (cell.TextFragments.Count > 0) + { + TextFragment fragment = cell.TextFragments[0]; + fragment.Text = "Modified"; + } + } + } + } + } + + // Save the (potentially modified) document + doc.Save(outputPath); + } + + Console.WriteLine($"Processing completed. Output saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/extract-pdf-tables-to-csv.cs b/working-with-tables/extract-pdf-tables-to-csv.cs new file mode 100644 index 00000000..3eff7e3d --- /dev/null +++ b/working-with-tables/extract-pdf-tables-to-csv.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputDir = "TablesCsv"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Ensure the output directory exists + Directory.CreateDirectory(outputDir); + + // Load the PDF document (lifecycle rule: use Document constructor and using block) + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + Page page = doc.Pages[pageNum]; + + // Create a new TableAbsorber for the current page + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables on this page + absorber.Visit(page); + + // Process each extracted table + for (int tblIdx = 0; tblIdx < absorber.TableList.Count; tblIdx++) + { + var absorbedTable = absorber.TableList[tblIdx]; + + // Build a CSV file name that reflects page and table numbers + string csvPath = Path.Combine(outputDir, + $"page{pageNum}_table{tblIdx + 1}.csv"); + + // Write the table content to CSV + using (StreamWriter writer = new StreamWriter(csvPath)) + { + foreach (var row in absorbedTable.RowList) + { + List cellTexts = new List(); + + foreach (var cell in row.CellList) + { + // Concatenate all text fragments inside the cell + string cellText = string.Empty; + foreach (var fragment in cell.TextFragments) + { + cellText += fragment.Text; + } + + // Escape commas and double quotes according to CSV rules + if (cellText.Contains("\"") || cellText.Contains(",")) + { + cellText = $"\"{cellText.Replace("\"", "\"\"")}\""; + } + + cellTexts.Add(cellText); + } + + // Join the cell texts with commas and write the line + writer.WriteLine(string.Join(",", cellTexts)); + } + } + + Console.WriteLine($"Extracted table to: {csvPath}"); + } + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/extract-pdf-tables-to-datatable.cs b/working-with-tables/extract-pdf-tables-to-datatable.cs new file mode 100644 index 00000000..82921f1b --- /dev/null +++ b/working-with-tables/extract-pdf-tables-to-datatable.cs @@ -0,0 +1,89 @@ +using System; +using System.Data; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Path to the source PDF file + const string inputPath = "input.pdf"; + + // Ensure the file exists before proceeding + if (!System.IO.File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Open the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to locate tables in the document + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from the entire document + absorber.Visit(doc); + + // Iterate over each discovered table + int tableIndex = 0; + foreach (AbsorbedTable absorbedTable in absorber.TableList) + { + // Create a DataTable to hold the extracted data + DataTable dataTable = new DataTable($"Table{tableIndex}"); + + // Determine the maximum number of cells in any row (column count) + int maxColumns = 0; + foreach (AbsorbedRow row in absorbedTable.RowList) + { + if (row.CellList.Count > maxColumns) + maxColumns = row.CellList.Count; + } + + // Add columns to the DataTable + for (int col = 0; col < maxColumns; col++) + { + dataTable.Columns.Add($"Column{col + 1}", typeof(string)); + } + + // Populate rows + foreach (AbsorbedRow row in absorbedTable.RowList) + { + DataRow dataRow = dataTable.NewRow(); + int colIndex = 0; + + foreach (AbsorbedCell cell in row.CellList) + { + // Concatenate all text fragments within the cell + string cellText = string.Empty; + foreach (TextFragment fragment in cell.TextFragments) + { + cellText += fragment.Text; + } + + // Assign the concatenated text to the appropriate column + dataRow[colIndex] = cellText; + colIndex++; + } + + // If the row has fewer cells than maxColumns, remaining columns stay null + dataTable.Rows.Add(dataRow); + } + + // Example output: display the extracted table contents + Console.WriteLine($"--- {dataTable.TableName} (Rows: {dataTable.Rows.Count}, Columns: {dataTable.Columns.Count}) ---"); + foreach (DataRow dr in dataTable.Rows) + { + for (int i = 0; i < dataTable.Columns.Count; i++) + { + Console.Write($"{dr[i]}\t"); + } + Console.WriteLine(); + } + + tableIndex++; + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/extract-table-coordinates-from-pdf.cs b/working-with-tables/extract-table-coordinates-from-pdf.cs new file mode 100644 index 00000000..d2bbdeb0 --- /dev/null +++ b/working-with-tables/extract-table-coordinates-from-pdf.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // TableAbsorber and AbsorbedTable live here + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + for (int pageIndex = 1; pageIndex <= doc.Pages.Count; pageIndex++) + { + Page page = doc.Pages[pageIndex]; + + // Create a fresh TableAbsorber for the current page + TableAbsorber absorber = new TableAbsorber(); + absorber.Visit(page); + + // Loop through each detected table and output its rectangle coordinates + for (int i = 0; i < absorber.TableList.Count; i++) + { + AbsorbedTable table = absorber.TableList[i]; + Aspose.Pdf.Rectangle rect = table.Rectangle; + + // Output the page number and rectangle bounds (llx, lly, urx, ury) + Console.WriteLine($"Page {page.Number}: Table {i + 1} – " + + $"LLX={rect.LLX}, LLY={rect.LLY}, URX={rect.URX}, URY={rect.URY}"); + } + } + } + } +} diff --git a/working-with-tables/extract-tables-from-pdf.cs b/working-with-tables/extract-tables-from-pdf.cs new file mode 100644 index 00000000..02414b5e --- /dev/null +++ b/working-with-tables/extract-tables-from-pdf.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document with deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to locate tables + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from the entire document + absorber.Visit(doc); + + // Iterate over all found tables + foreach (AbsorbedTable table in absorber.TableList) + { + // Output basic table information + Console.WriteLine($"Table on page {table.PageNum}: " + + $"LLX={table.Rectangle.LLX}, LLY={table.Rectangle.LLY}, " + + $"URX={table.Rectangle.URX}, URY={table.Rectangle.URY}"); + + // Optionally iterate rows and cells to read cell text + foreach (AbsorbedRow row in table.RowList) + { + foreach (AbsorbedCell cell in row.CellList) + { + string cellText = string.Empty; + foreach (TextFragment fragment in cell.TextFragments) + { + cellText += fragment.Text; + } + Console.WriteLine($" Cell text: {cellText}"); + } + } + } + + // Save the (potentially modified) document + doc.Save(outputPath); + } + + Console.WriteLine($"Processing completed. Output saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/extract-text-from-pdf-tables.cs b/working-with-tables/extract-text-from-pdf-tables.cs new file mode 100644 index 00000000..9c890bec --- /dev/null +++ b/working-with-tables/extract-text-from-pdf-tables.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (wrapped in using for deterministic disposal) + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to find tables in the document + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from the entire document + absorber.Visit(doc); + + // Iterate over each absorbed table + for (int t = 0; t < absorber.TableList.Count; t++) + { + var table = absorber.TableList[t]; + Console.WriteLine($"Table {t + 1} found on page {table.PageNum}"); + + // Iterate over rows in the current table + for (int r = 0; r < table.RowList.Count; r++) + { + var row = table.RowList[r]; + + // Iterate over cells in the current row + for (int c = 0; c < row.CellList.Count; c++) + { + var cell = row.CellList[c]; + + // Concatenate all text fragments inside the cell + string cellText = string.Empty; + foreach (TextFragment fragment in cell.TextFragments) + { + cellText += fragment.Text; + } + + Console.WriteLine($" Row {r + 1}, Cell {c + 1}: \"{cellText}\""); + } + } + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/import-datatable-auto-fit-columns.cs b/working-with-tables/import-datatable-auto-fit-columns.cs new file mode 100644 index 00000000..f7f01b68 --- /dev/null +++ b/working-with-tables/import-datatable-auto-fit-columns.cs @@ -0,0 +1,68 @@ +using System; +using System.Data; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // for MarginInfo and BorderInfo if needed + +class Program +{ + static void Main() + { + const string inputPdf = "template.pdf"; + const string outputPdf = "output.pdf"; + + // Verify the source PDF exists + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"File not found: {inputPdf}"); + return; + } + + // ------------------------------------------------- + // Create a sample DataTable to be imported into PDF + // ------------------------------------------------- + DataTable dataTable = new DataTable(); + dataTable.Columns.Add("ID", typeof(int)); + dataTable.Columns.Add("Name", typeof(string)); + dataTable.Columns.Add("Price",typeof(double)); + + dataTable.Rows.Add(1, "Apple", 0.50); + dataTable.Rows.Add(2, "Banana", 0.30); + dataTable.Rows.Add(3, "Cherry", 1.20); + + // ------------------------------------------------- + // Load the PDF, add a table, import data, auto‑fit + // ------------------------------------------------- + using (Document doc = new Document(inputPdf)) + { + // Create a new table instance + Table table = new Table + { + // Optional visual settings + Border = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Import the DataTable; include column names as the first row + table.ImportDataTable(dataTable, true, 0, 0); + + // Adjust column widths automatically based on the imported content + // Aspose.Pdf.Table does not have AutoFitColumns(); use ColumnAdjustment instead. + table.ColumnAdjustment = ColumnAdjustment.AutoFitToContent; + + // Position the table on the first page + Page page = doc.Pages[1]; + table.Left = 50; // distance from the left edge + table.Top = 700; // distance from the bottom edge + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"PDF with auto‑fitted table saved to '{outputPdf}'."); + } +} diff --git a/working-with-tables/import-datatable-into-pdf-table.cs b/working-with-tables/import-datatable-into-pdf-table.cs new file mode 100644 index 00000000..fcc9f7f3 --- /dev/null +++ b/working-with-tables/import-datatable-into-pdf-table.cs @@ -0,0 +1,81 @@ +using System; +using System.Data; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; // Core Aspose.Pdf namespace +using Aspose.Pdf.Text; // For text related classes if needed + +class Program +{ + static void Main() + { + // Prepare sample data in a DataTable + DataTable dt = new DataTable("Sample"); + dt.Columns.Add("ID", typeof(int)); + dt.Columns.Add("Name", typeof(string)); + dt.Columns.Add("Quantity", typeof(int)); + + dt.Rows.Add(1, "Apples", 10); + dt.Rows.Add(2, "Bananas", 20); + dt.Rows.Add(3, "Cherries", 15); + + const string outputPath = "DataTableExport.pdf"; + + // Create a PDF document and add a page + using (Document doc = new Document()) + { + Page page = doc.Pages.Add(); + + // Create a Table and configure basic appearance + Table table = new Table + { + // Define column widths (space‑separated values) + ColumnWidths = "100 200 100", + // Optional: set a border for the whole table + Border = new BorderInfo(BorderSide.All, 0.5f) + }; + + // Import the DataTable into the Aspose.Pdf.Table + // Parameters: + // dt – source DataTable + // true – import column names as the first row + // 0 – start importing at the first row of the target table (zero‑based) + // 0 – start importing at the first column of the target table (zero‑based) + table.ImportDataTable(dt, true, 0, 0); + + // Add the populated table to the page + page.Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/import-filtered-dataview-into-pdf-table.cs b/working-with-tables/import-filtered-dataview-into-pdf-table.cs new file mode 100644 index 00000000..40db7edc --- /dev/null +++ b/working-with-tables/import-filtered-dataview-into-pdf-table.cs @@ -0,0 +1,87 @@ +using System; +using System.Data; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // Prepare sample data in a DataTable + DataTable dataTable = new DataTable("Sample"); + dataTable.Columns.Add("ID", typeof(int)); + dataTable.Columns.Add("Name", typeof(string)); + dataTable.Columns.Add("Score", typeof(int)); + + dataTable.Rows.Add(1, "Alice", 85); + dataTable.Rows.Add(2, "Bob", 92); + dataTable.Rows.Add(3, "Charlie", 78); + dataTable.Rows.Add(4, "Diana", 90); + + // Create a DataView with a filter (e.g., Score >= 80) + DataView dataView = new DataView(dataTable) + { + RowFilter = "Score >= 80" + }; + + // Create a new PDF document and add a page + using (Document doc = new Document()) + { + Page page = doc.Pages.Add(); + + // Create a table and import the filtered DataView + Table table = new Table(); + + // Optionally set column widths (example: three equal columns) + table.ColumnWidths = "100 150 100"; + + // Import the DataView: + // - include column names as the first row + // - start at row 0, column 0 of the target table + // - import all rows and columns from the DataView + table.ImportDataView( + sourceDataView: dataView, + isColumnNamesImported: true, + firstFilledRow: 0, + firstFilledColumn: 0, + maxRows: dataView.Count, + maxColumns: dataView.Table?.Columns.Count ?? 0); + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + string outputPath = "DataViewTable.pdf"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + + Console.WriteLine("Program finished."); + } + + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/import-filtered-dataview-into-pdf-table__v2.cs b/working-with-tables/import-filtered-dataview-into-pdf-table__v2.cs new file mode 100644 index 00000000..569f7296 --- /dev/null +++ b/working-with-tables/import-filtered-dataview-into-pdf-table__v2.cs @@ -0,0 +1,100 @@ +using System; +using System.Data; +using System.IO; +using System.Runtime.InteropServices; // for OS check +using Aspose.Pdf; +using Aspose.Pdf.Text; // for TextState if needed + +class Program +{ + static void Main() + { + // Paths (adjust as needed) + const string outputPdfPath = "output.pdf"; + + // Sample data creation + DataTable dt = new DataTable(); + dt.Columns.Add("Id", typeof(int)); + dt.Columns.Add("Name", typeof(string)); + dt.Columns.Add("Score", typeof(double)); + + dt.Rows.Add(1, "Alice", 85.5); + dt.Rows.Add(2, "Bob", 92.0); + dt.Rows.Add(3, "Charlie", 78.0); + dt.Rows.Add(4, "David", 88.5); + dt.Rows.Add(5, "Eve", 91.0); + + // Create a DataView and apply a filter (e.g., only scores >= 90) + DataView view = new DataView(dt); + view.RowFilter = "Score >= 90"; + + // Create a new PDF document (wrapped in using for proper disposal) + using (Document doc = new Document()) + { + // Add a page to host the table + Page page = doc.Pages.Add(); + + // Create a table instance + Table table = new Table(); + + // Define column widths (optional – here we create as many columns as the source) + // Ensure the table has at least one row with the required number of cells + // This satisfies the requirement that the target column must exist before import. + Row headerRow = table.Rows.Add(); + + // Guard against a possible null DataView.Table (the warning CS8602) + int columnCount = view.Table?.Columns?.Count ?? 0; + for (int i = 0; i < columnCount; i++) + { + // Add empty cells to establish column count + headerRow.Cells.Add(string.Empty); + } + + // Import the filtered DataView into the table + // Parameters: + // sourceDataView : view (filtered) + // isColumnNamesImported : true (import column names as first row) + // firstFilledRow : 0 (start at first row of the table) + // firstFilledColumn : 0 (start at first column) + // maxRows : view.Count (import all filtered rows) + // maxColumns : view.Table?.Columns?.Count ?? 0 (import all columns) + table.ImportDataView(view, true, 0, 0, view.Count, columnCount); + + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // Save the resulting PDF – guard against missing libgdiplus on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPdfPath); + Console.WriteLine($"PDF with filtered table saved to '{outputPdfPath}'."); + } + else + { + // Attempt to save and handle the GDI+ (libgdiplus) issue gracefully + try + { + doc.Save(outputPdfPath); + Console.WriteLine($"PDF saved (non‑Windows platform) to '{outputPdfPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF could not be saved, but the rest of the program executed correctly."); + } + } + } + } + + // Helper to walk the exception chain and detect a missing native GDI+ library + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/index.json b/working-with-tables/index.json new file mode 100644 index 00000000..9bff5634 --- /dev/null +++ b/working-with-tables/index.json @@ -0,0 +1,2152 @@ +{ + "category": "working-with-tables", + "nuget_version": "26.4.0", + "last_updated": "2026-05-08T09:58:17Z", + "examples": { + "create-table-with-rows-in-pdf": { + "title": "Create a Table with Header and Rows in a PDF", + "filename": "create-table-with-rows-in-pdf.cs", + "description": "Demonstrates how to programmatically create a PDF, add a Table, populate header and data rows, apply basic styling, and save the document using Aspose.Pdf for .NET.", + "tags": [ + "table", + "pdf", + "aspose-pdf", + "csharp", + "header" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextState" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-table-into-pdf-page": { + "title": "Insert Table into Existing PDF Page", + "filename": "insert-table-into-pdf-page.cs", + "description": "Shows how to load an existing PDF, create and style a Table, position it on a specific page, add rows and cells, and save the updated document.", + "tags": [ + "table", + "pdf", + "aspose-pdf", + "insert", + "page" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Text.TextState", + "Aspose.Pdf.Text.FontRepository" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "auto-fit-table-columns-to-content": { + "title": "AutoFit Table Columns to Content in PDF", + "filename": "auto-fit-table-columns-to-content.cs", + "description": "Demonstrates creating a PDF with a table whose column widths automatically adjust to the cell contents using ColumnAdjustment.AutoFitToContent, and saves the document with platform‑specific handling for GDI+.", + "tags": [ + "table", + "autofit", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.ColumnAdjustment" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-table-stretched-to-page-width": { + "title": "Create Table Stretched to Page Width in PDF", + "filename": "create-table-stretched-to-page-width.cs", + "description": "Shows how to generate a PDF with a table whose columns are sized proportionally to fill the entire page width using Aspose.Pdf.", + "tags": [ + "table", + "autofit", + "pdf", + "column-width", + "aspnet" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Table.ColumnWidths" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-svg-into-table-cell": { + "title": "Insert SVG Image into a Table Cell", + "filename": "insert-svg-into-table-cell.cs", + "description": "Demonstrates how to embed an SVG file as an Image inside a Table cell of a PDF using Aspose.Pdf, including PDF creation/loading and cross‑platform save handling.", + "tags": [ + "svg", + "table", + "image", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Image" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "embed-html-fragment-in-table-cell": { + "title": "Embed HTML Fragment in PDF Table Cell", + "filename": "embed-html-fragment-in-table-cell.cs", + "description": "Demonstrates creating a PDF with a table and inserting HTML markup into a cell using Aspose.Pdf's HtmlFragment, including platform‑specific handling for saving the document.", + "tags": [ + "html", + "table", + "cell", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.HtmlFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-page-break-after-table-row": { + "title": "Insert Page Break After a Table Row in PDF", + "filename": "insert-page-break-after-table-row.cs", + "description": "Demonstrates how to load a PDF, locate a table, and set the IsInNewPage flag on a specific row to force a page break after that row.", + "tags": [ + "pdf", + "table", + "page-break", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Page", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "render-table-on-new-page": { + "title": "Render Table on a New PDF Page", + "filename": "render-table-on-new-page.cs", + "description": "Shows how to create a PDF document, add a blank page, build a table with header and data rows, and place the table on the page using Aspose.Pdf.", + "tags": [ + "table", + "pdf", + "aspose.pdf", + "page", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-table-with-colspan": { + "title": "Create Table with Merged Cell Using ColSpan", + "filename": "create-table-with-colspan.cs", + "description": "Demonstrates how to build a PDF table with three columns and merge a cell across all columns using the ColSpan property, including basic cell styling and platform‑aware document saving.", + "tags": [ + "table", + "colspan", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextState", + "Aspose.Pdf.FontRepository.FindFont", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "merge-table-cells-vertically-rowspan": { + "title": "Merge Table Cells Vertically Using RowSpan", + "filename": "merge-table-cells-vertically-rowspan.cs", + "description": "Demonstrates how to set the RowSpan property of a table cell to merge it with the cell directly below, creating a vertically spanning cell in a PDF table.", + "tags": [ + "table", + "rowspan", + "cell-merge", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-custom-cell-margins-in-pdf-table": { + "title": "Set Custom Cell Margins in a PDF Table", + "filename": "set-custom-cell-margins-in-pdf-table.cs", + "description": "Demonstrates how to configure individual cell margins in an Aspose.Pdf table using a MarginInfo object and save the document, handling platform‑specific GDI+ requirements.", + "tags": [ + "table", + "margin", + "cell", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-default-cell-padding-for-pdf-table": { + "title": "Set Default Cell Padding for a PDF Table", + "filename": "set-default-cell-padding-for-pdf-table.cs", + "description": "Creates a PDF document, adds a 3‑column by 4‑row table, and applies uniform cell padding by setting Table.DefaultCellPadding with a MarginInfo instance.", + "tags": [ + "table", + "padding", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.BorderSide" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "read-rendered-table-width": { + "title": "Read Rendered Table Width After Layout", + "filename": "read-rendered-table-width.cs", + "description": "Creates a PDF with a table using Aspose.Pdf, lets the layout engine calculate column widths, and retrieves the rendered table width via the Table.ColumnWidths property.", + "tags": [ + "table", + "width", + "layout", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Text.BorderInfo", + "Aspose.Pdf.Table.ColumnWidths", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "import-datatable-into-pdf-table": { + "title": "Import DataTable into PDF Table", + "filename": "import-datatable-into-pdf-table.cs", + "description": "Demonstrates how to import an in‑memory DataTable into an Aspose.Pdf Table using Table.ImportDataTable and save the result as a PDF document.", + "tags": [ + "datatable", + "pdf", + "table", + "import", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Table.ImportDataTable" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "import-filtered-dataview-into-pdf-table": { + "title": "Import Filtered DataView into PDF Table", + "filename": "import-filtered-dataview-into-pdf-table.cs", + "description": "Demonstrates creating a filtered DataView, importing it into an Aspose.Pdf Table with ImportDataView, and saving the PDF while handling platform‑specific GDI+ availability.", + "tags": [ + "dataview", + "table", + "pdf", + "aspose-pdf", + "filter" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Table.ImportDataView", + "Aspose.Pdf.Page.Paragraphs.Add" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-pdf-table-from-datatable": { + "title": "Create PDF Table from a DataTable", + "filename": "create-pdf-table-from-datatable.cs", + "description": "Demonstrates how to fill a DataTable, import it into an Aspose.Pdf Table, add the table to a PDF page, and save the document while handling platform‑specific GDI+ availability.", + "tags": [ + "aspose.pdf", + "datatable", + "pdf-table", + "csharp", + "cross-platform" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Table.ImportDataTable", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "check-table-isbroken-property": { + "title": "Check and Set Table Break Using IsBroken Property", + "filename": "check-table-isbroken-property.cs", + "description": "The example creates a PDF, adds a table, reads the Table.IsBroken property to see if the table will break across pages, changes the property, and saves the document.", + "tags": [ + "table", + "isbroken", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Color" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "repeat-header-column-row-in-pdf-table": { + "title": "Repeat Header Column and Row in PDF Table", + "filename": "repeat-header-column-row-in-pdf-table.cs", + "description": "Demonstrates how to create a PDF table with a header column and header row that repeat on each new page using Aspose.Pdf, including handling of missing input files and platform‑specific saving.", + "tags": [ + "table", + "header", + "repeat", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Drawing.BorderInfo", + "Aspose.Pdf.Text.TextState" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "extract-tables-from-pdf": { + "title": "Extract Tables from PDF Using TableAbsorber", + "filename": "extract-tables-from-pdf.cs", + "description": "Demonstrates how to load a PDF, locate tables with TableAbsorber, iterate through rows and cells, and read cell text using Aspose.Pdf.", + "tags": [ + "pdf", + "tables", + "extraction", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.AbsorbedTable", + "Aspose.Pdf.AbsorbedRow", + "Aspose.Pdf.AbsorbedCell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "replace-table-in-pdf": { + "title": "Replace an Existing Table in a PDF with a New Table", + "filename": "replace-table-in-pdf.cs", + "description": "Demonstrates how to locate a table on a PDF page using TableAbsorber, remove it, and insert a newly created Table at the same position.", + "tags": [ + "table", + "replace", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.Table", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.TableAbsorber.Replace" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "remove-first-table-from-pdf": { + "title": "Remove First Table from PDF Using TableAbsorber", + "filename": "remove-first-table-from-pdf.cs", + "description": "Demonstrates how to locate tables on a PDF page with TableAbsorber, remove a specific table using the Remove method, and save the modified document.", + "tags": [ + "table", + "pdf", + "remove", + "aspose-pdf", + "tableabsorber" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.AbsorbedTable", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.TableAbsorber.Remove", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "remove-all-tables-from-pdf": { + "title": "Remove All Tables from a PDF Document", + "filename": "remove-all-tables-from-pdf.cs", + "description": "Shows how to locate tables in a PDF using TableAbsorber and delete each absorbed table, then save the updated document.", + "tags": [ + "table", + "remove", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Text.TableAbsorber", + "Aspose.Pdf.Text.AbsorbedTable", + "Aspose.Pdf.Text.TableAbsorber.Visit", + "Aspose.Pdf.Text.TableAbsorber.Remove", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "batch-add-table-with-logo-to-pdfs": { + "title": "Batch Add Table with Logo to PDFs", + "filename": "batch-add-table-with-logo-to-pdfs.cs", + "description": "Demonstrates iterating over a folder of PDF files, creating a table that contains a company logo image and text, inserting the table at the top of each document's first page, and saving the modified files to an output directory.", + "tags": [ + "pdf", + "table", + "image", + "batch", + "logo" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Image", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.FontRepository", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Color" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "batch-replace-tables-in-pdfs": { + "title": "Batch Replace Tables in Multiple PDFs", + "filename": "batch-replace-tables-in-pdfs.cs", + "description": "Shows how to process all PDF files in a folder, locate tables on each page with TableAbsorber, and replace each found table with a newly created table.", + "tags": [ + "table", + "batch", + "pdf", + "replace", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.AbsorbedTable", + "Aspose.Pdf.Table", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.TableAbsorber.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "apply-different-autofit-behaviors-to-multiple-tables": { + "title": "Apply Different AutoFit Behaviors to Multiple Tables in a PDF", + "filename": "apply-different-autofit-behaviors-to-multiple-tables.cs", + "description": "Demonstrates how to add two tables to a PDF and set distinct ColumnAdjustment values (AutoFitToContent and AutoFitToWindow) so each table sizes its columns differently.", + "tags": [ + "autofit", + "tables", + "pdf", + "aspose", + "columnadjustment" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.ColumnAdjustment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-cell-background-color-in-pdf-table": { + "title": "Set Cell Background Color in PDF Table", + "filename": "set-cell-background-color-in-pdf-table.cs", + "description": "Creates a PDF document with a table and demonstrates how to set the background color of a specific cell using Aspose.Pdf.", + "tags": [ + "pdf", + "table", + "cell", + "background-color", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Color", + "Aspose.Pdf.BorderInfo" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "apply-solid-border-to-pdf-table": { + "title": "Apply Solid Border to PDF Table", + "filename": "apply-solid-border-to-pdf-table.cs", + "description": "Demonstrates how to set a solid black border on an entire Aspose.Pdf Table by configuring a BorderInfo object and assigning it to Table.Border.", + "tags": [ + "table", + "border", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.BorderSide", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-image-into-table-cell": { + "title": "Insert Image into Table Cell in PDF", + "filename": "insert-image-into-table-cell.cs", + "description": "Shows how to create a PDF, add a two‑column table, place text in the first cell and embed an external PNG image in the second cell using Aspose.Pdf.", + "tags": [ + "pdf", + "table", + "image", + "aspose.pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Image" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-image-from-memory-stream-into-pdf-table-cell": { + "title": "Insert Image from Memory Stream into PDF Table Cell", + "filename": "insert-image-from-memory-stream-into-pdf-table-cell.cs", + "description": "Shows how to load an image into a memory stream and embed it in a table cell of a PDF document using Aspose.Pdf.", + "tags": [ + "pdf", + "image", + "table", + "memory-stream", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Image", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-styled-text-to-table-cell": { + "title": "Add Styled Text to a Table Cell in PDF", + "filename": "add-styled-text-to-table-cell.cs", + "description": "Shows how to place a TextFragment with a specific font and size into a table cell, using the cell's IsOverrideByFragment property to apply the fragment's TextState.", + "tags": [ + "table", + "textfragment", + "font", + "pdf", + "aspnet" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Text.FontRepository" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-centered-paragraph-to-table-cell": { + "title": "Add Centered Paragraph to Table Cell in PDF", + "filename": "add-centered-paragraph-to-table-cell.cs", + "description": "Demonstrates opening an existing PDF, creating a table, adding a row and cell, and inserting a centered paragraph into the cell using Aspose.Pdf.", + "tags": [ + "table", + "centered-text", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-cell-vertical-alignment-middle": { + "title": "Center Cell Content Vertically in PDF Table", + "filename": "set-cell-vertical-alignment-middle.cs", + "description": "Demonstrates creating a PDF with Aspose.Pdf, adding a table, and setting the vertical alignment of a cell's text to the middle using the Cell.VerticalAlignment property.", + "tags": [ + "pdf", + "table", + "vertical-alignment", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.VerticalAlignment" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "center-table-in-pdf": { + "title": "Center Table in PDF using Aspose.Pdf", + "filename": "center-table-in-pdf.cs", + "description": "Demonstrates how to create a table, set its HorizontalAlignment to Center, and add it to a PDF page using Aspose.Pdf. Includes platform‑aware saving to handle GDI+ availability.", + "tags": [ + "table", + "center", + "pdf", + "aspose", + "horizontal-alignment" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Page", + "Aspose.Pdf.HorizontalAlignment", + "Aspose.Pdf.ColumnAdjustment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "offset-table-left-margin": { + "title": "Offset Table from Left Margin in PDF", + "filename": "offset-table-left-margin.cs", + "description": "Demonstrates how to shift a table away from the left edge of a PDF page by setting the Table.Margin.Left property using Aspose.Pdf.", + "tags": [ + "table", + "margin", + "offset", + "pdf", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Page" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "enable-table-splitting-across-pdf-pages": { + "title": "Enable Table Splitting Across PDF Pages", + "filename": "enable-table-splitting-across-pdf-pages.cs", + "description": "Demonstrates how to allow an Aspose.Pdf Table to break across multiple pages by setting Table.IsBroken to true, and saves the resulting PDF.", + "tags": [ + "table", + "pagination", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "prevent-table-splitting": { + "title": "Prevent Table Splitting in PDF", + "filename": "prevent-table-splitting.cs", + "description": "Shows how to keep an Aspose.Pdf table on a single page by disabling automatic splitting with Table.IsBroken and Row.IsRowBroken.", + "tags": [ + "table", + "pdf", + "aspose", + "csharp", + "nosplit" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.BorderInfo" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "calculate-remaining-page-space-add-table": { + "title": "Calculate Remaining Page Space and Add Table to PDF", + "filename": "calculate-remaining-page-space-add-table.cs", + "description": "Loads a PDF, computes the usable vertical space by subtracting existing content height from the page height, checks if a table fits, and positions the table either below the content or at the top margin.", + "tags": [ + "pdf", + "table", + "layout", + "margin", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Table.GetHeight" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-fixed-width-table": { + "title": "Create Fixed-Width Table in PDF", + "filename": "create-fixed-width-table.cs", + "description": "Shows how to create a table with a total width of 500 points, add a row and cell, position it on a page, and save the PDF using Aspose.Pdf.", + "tags": [ + "table", + "fixed-width", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-table-width-80-percent": { + "title": "Set Table Width to 80% of Page Width", + "filename": "set-table-width-80-percent.cs", + "description": "Demonstrates creating a PDF with Aspose.Pdf, adding a table, and defining its width as 80% of the page using the ColumnWidths property.", + "tags": [ + "table", + "width", + "percentage", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.HorizontalAlignment" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "map-datatable-columns-to-pdf-table": { + "title": "Map DataTable Columns to Specific PDF Table Columns", + "filename": "map-datatable-columns-to-pdf-table.cs", + "description": "Demonstrates how to map selected DataTable columns to arbitrary positions in an Aspose.Pdf Table using a column‑mapping dictionary and Table.ImportDataTable.", + "tags": [ + "datatable", + "table-mapping", + "pdf", + "aspose", + "import" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Table.ImportDataTable", + "Aspose.Pdf.Drawing.BorderInfo", + "Aspose.Pdf.Drawing.Color" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "import-filtered-dataview-into-pdf-table__v2": { + "title": "Import Filtered DataView into PDF Table", + "filename": "import-filtered-dataview-into-pdf-table__v2.cs", + "description": "Shows how to filter rows in a DataView and import the filtered data into an Aspose.Pdf Table, then save the result as a PDF document.", + "tags": [ + "dataview", + "filter", + "pdf", + "table", + "aspose.pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Table.ImportDataView" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "populate-pdf-table-from-linq": { + "title": "Populate PDF Table from LINQ Query using Aspose.Pdf", + "filename": "populate-pdf-table-from-linq.cs", + "description": "Demonstrates converting a LINQ query result into a DataTable and importing it into an Aspose.Pdf Table, then saving the table in a PDF document.", + "tags": [ + "linq", + "datatable", + "pdf", + "aspose", + "table" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.ColumnAdjustment", + "Aspose.Pdf.Table.ImportDataTable" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-table-to-specific-pdf-page": { + "title": "Add Table to Specific PDF Page", + "filename": "add-table-to-specific-pdf-page.cs", + "description": "Shows how to load an existing PDF, create a simple 2×2 table, and insert it onto a specified page using Aspose.Pdf.", + "tags": [ + "table", + "pdf", + "aspose", + "page", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-table-after-paragraph": { + "title": "Insert Table After a Specific Paragraph in PDF", + "filename": "insert-table-after-paragraph.cs", + "description": "Demonstrates how to locate a paragraph containing given text in a PDF, create a table with header and data rows, and insert the table immediately after that paragraph.", + "tags": [ + "table", + "pdf", + "paragraph", + "insert", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Text.TextState", + "Aspose.Pdf.FontRepository" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-table-before-image": { + "title": "Insert Table Before Image in PDF", + "filename": "insert-table-before-image.cs", + "description": "Shows how to locate image objects on PDF pages and insert a formatted table right before each image using Aspose.Pdf.", + "tags": [ + "pdf", + "table", + "image", + "insert", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Image", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Text.TextState" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-repeating-table-header": { + "title": "Create Repeating Table Header in PDF", + "filename": "create-repeating-table-header.cs", + "description": "Shows how to add a table with a header row that repeats on each new page using Aspose.Pdf's tagged content API.", + "tags": [ + "table", + "header", + "repeat", + "tagged-content", + "pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Tagged.ITaggedContent", + "Aspose.Pdf.LogicalStructure.StructureElement", + "Aspose.Pdf.Tagged.TableElement", + "Aspose.Pdf.Tagged.TableTHeadElement", + "Aspose.Pdf.Tagged.TableTRElement", + "Aspose.Pdf.Tagged.TableTHElement", + "Aspose.Pdf.Tagged.TableTDElement" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "style-table-header-row-pdf": { + "title": "Style Table Header Row in PDF with Aspose.Pdf", + "filename": "style-table-header-row-pdf.cs", + "description": "Demonstrates how to create a PDF table and apply distinct styling to the header row by setting a background color and bold font for its cells using Aspose.Pdf.", + "tags": [ + "table", + "header-style", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Text.TextState", + "Aspose.Pdf.FontRepository.FindFont", + "Aspose.Pdf.Color" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-repeating-footer-row-to-pdf-table": { + "title": "Add Repeating Footer Row to PDF Table", + "filename": "add-repeating-footer-row-to-pdf-table.cs", + "description": "Shows how to add a visual footer row to a PDF table, make it repeat on every page, and define the logical TFoot element in the tagged PDF structure using Aspose.Pdf.", + "tags": [ + "table", + "footer", + "repeating", + "tagged-pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Tagged.ITaggedContent", + "Aspose.Pdf.Tagged.TableElement", + "Aspose.Pdf.Tagged.TableTFootElement", + "Aspose.Pdf.Tagged.TableTDElement" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "pdf-table-alternating-row-colors": { + "title": "Create PDF Table with Alternating Row Colors", + "filename": "pdf-table-alternating-row-colors.cs", + "description": "Shows how to build a table in a PDF using Aspose.Pdf, add header and data rows, and apply alternating background colors to each row based on its index parity.", + "tags": [ + "pdf", + "table", + "alternating-rows", + "background-color", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Color", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Text.TextState" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-hyperlink-to-table-cell": { + "title": "Add Hyperlink to Table Cell in PDF", + "filename": "add-hyperlink-to-table-cell.cs", + "description": "Demonstrates creating a LinkAnnotation with a GoToURIAction and inserting it into a table cell's paragraph to embed a clickable hyperlink in a PDF document.", + "tags": [ + "hyperlink", + "table", + "annotation", + "pdf", + "linkannotation" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Annotations.LinkAnnotation", + "Aspose.Pdf.Annotations.GoToURIAction", + "Aspose.Pdf.Rectangle" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-radio-button-group-to-table-cell": { + "title": "Add Radio Button Group Inside Table Cell", + "filename": "add-radio-button-group-to-table-cell.cs", + "description": "Demonstrates creating a PDF table and placing a grouped set of radio buttons inside a cell using Aspose.Pdf form fields.", + "tags": [ + "tables", + "radio-buttons", + "form-fields", + "aspdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Forms.RadioButtonField", + "Aspose.Pdf.Forms.RadioButtonOptionField", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "export-tagged-table-structure-to-json": { + "title": "Export Tagged Table Structure to JSON", + "filename": "export-tagged-table-structure-to-json.cs", + "description": "Loads a PDF, accesses its tagged content, extracts tables, rows, and cells with their properties, and writes the structure to a formatted JSON file.", + "tags": [ + "pdf", + "table", + "tagged-content", + "json", + "export" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Tagged.ITaggedContent", + "Aspose.Pdf.LogicalStructure.TableElement", + "Aspose.Pdf.LogicalStructure.TableTRElement", + "Aspose.Pdf.LogicalStructure.TableTDElement" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "export-pdf-table-to-csv": { + "title": "Export PDF Table Data to CSV", + "filename": "export-pdf-table-to-csv.cs", + "description": "Shows how to load a PDF document with Aspose.Pdf and save its table contents as a CSV file using ExcelSaveOptions.", + "tags": [ + "pdf", + "csv", + "export", + "tables", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.ExcelSaveOptions", + "Aspose.Pdf.Document.Save", + "Aspose.Pdf.ExcelSaveOptions.ExcelFormat" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "serialize-table-to-xml": { + "title": "Serialize Table to XML", + "filename": "serialize-table-to-xml.cs", + "description": "Shows how to create a PDF table with Aspose.Pdf, add it to a document, and then export the document's structure to an XML file using XmlSaveOptions.", + "tags": [ + "table", + "xml", + "aspdf", + "pdf", + "serialization" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Drawing.BorderInfo", + "Aspose.Pdf.Drawing.Color", + "Aspose.Pdf.XmlSaveOptions" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "render-table-from-xml-to-pdf": { + "title": "Render Table from XML to PDF", + "filename": "render-table-from-xml-to-pdf.cs", + "description": "Demonstrates loading a PDF document defined in XML (PDFXML) that contains a table, reconstructing it with Aspose.Pdf, and saving the result as a PDF file.", + "tags": [ + "table", + "xml", + "pdf", + "aspose-pdf", + "render" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.XmlLoadOptions", + "Aspose.Pdf.Document..ctor(string, XmlLoadOptions)", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "count-tables-in-pdf": { + "title": "Count Tables in PDF using TableAbsorber", + "filename": "count-tables-in-pdf.cs", + "description": "Shows how to load a PDF with Aspose.Pdf, use TableAbsorber to extract tables, and obtain the number of tables via the TableList collection.", + "tags": [ + "table", + "pdf", + "count", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Text.TableAbsorber", + "Aspose.Pdf.Text.TableAbsorber.Visit", + "Aspose.Pdf.Text.TableAbsorber.TableList" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "extract-table-coordinates-from-pdf": { + "title": "Extract Table Coordinates from PDF", + "filename": "extract-table-coordinates-from-pdf.cs", + "description": "Demonstrates loading a PDF, iterating through its pages, using TableAbsorber to detect tables, and retrieving each table's Rectangle bounds (LLX, LLY, URX, URY).", + "tags": [ + "table", + "coordinates", + "pdf", + "aspose", + "tableabsorber" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.AbsorbedTable", + "Aspose.Pdf.Rectangle" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "extract-text-from-pdf-tables": { + "title": "Extract Text from PDF Tables Using TableAbsorber", + "filename": "extract-text-from-pdf-tables.cs", + "description": "Shows how to load a PDF, locate tables with TableAbsorber, and read the concatenated text of each cell by iterating through tables, rows, and cells.", + "tags": [ + "pdf", + "table", + "text-extraction", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.TableAbsorber.TableList", + "Aspose.Pdf.TableAbsorbed.RowList", + "Aspose.Pdf.CellAbsorbed.TextFragments" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "replace-keyword-in-pdf-table-cells": { + "title": "Replace Keyword in PDF Table Cells", + "filename": "replace-keyword-in-pdf-table-cells.cs", + "description": "Shows how to locate tables in a PDF, iterate through rows and cells, and replace a specific keyword inside cell text fragments using Aspose.Pdf.", + "tags": [ + "pdf", + "table", + "text-replacement", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Table", + "Aspose.Pdf.TableAbsorber.Row", + "Aspose.Pdf.TableAbsorber.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "remove-table-column-from-pdf": { + "title": "Remove a Column from a PDF Table", + "filename": "remove-table-column-from-pdf.cs", + "description": "Demonstrates how to delete a specific column from tables in a PDF by removing the corresponding Cell objects from each Row using Aspose.Pdf.", + "tags": [ + "pdf", + "table", + "column", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-column-into-pdf-table": { + "title": "Insert Column into PDF Table", + "filename": "insert-column-into-pdf-table.cs", + "description": "Demonstrates loading a PDF, creating a table, and inserting a new column at a specified index by adding a cell to each row, then adjusting column widths and saving the document.", + "tags": [ + "pdf", + "table", + "column", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.BorderInfo" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "reorder-pdf-table-columns": { + "title": "Reorder Columns of a PDF Table", + "filename": "reorder-pdf-table-columns.cs", + "description": "Demonstrates how to extract a table from a PDF, rearrange its columns by reordering Cell objects in each Row, and replace the original table with the new layout using Aspose.Pdf.", + "tags": [ + "pdf", + "table", + "column-reorder", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.AbsorbedTable", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-table-with-proportional-column-widths": { + "title": "Add Table with Proportional Column Widths to PDF", + "filename": "add-table-with-proportional-column-widths.cs", + "description": "Loads an existing PDF, calculates column width percentages, creates a table with those proportional widths, adds a row of cells, and saves the modified document.", + "tags": [ + "pdf", + "table", + "column-width", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.ColumnAdjustment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-minimum-column-width-for-pdf-table": { + "title": "Set Minimum Column Width for PDF Table", + "filename": "set-minimum-column-width-for-pdf-table.cs", + "description": "Shows how to create a table in a PDF with Aspose.Pdf, enforce a minimum column width using DefaultColumnWidth, and add the table to a page before saving.", + "tags": [ + "table", + "column-width", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Page" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-maximum-column-width-for-pdf-table": { + "title": "Set Maximum Column Width for PDF Table", + "filename": "set-maximum-column-width-for-pdf-table.cs", + "description": "Shows how to create a table in a PDF with fixed column widths (150 points) using Aspose.Pdf, preventing columns from expanding beyond the specified size.", + "tags": [ + "pdf", + "table", + "column-width", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Color", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.ColumnAdjustment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "import-datatable-auto-fit-columns": { + "title": "Import DataTable into PDF and Auto‑Fit Table Columns", + "filename": "import-datatable-auto-fit-columns.cs", + "description": "Loads a PDF template, creates an Aspose.Pdf.Table, imports a System.Data.DataTable, automatically adjusts column widths to the content, and saves the result.", + "tags": [ + "pdf", + "table", + "autofit", + "import", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Table", + "Aspose.Pdf.Page", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.ColumnAdjustment", + "Aspose.Pdf.Table.ImportDataTable", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-auto-numbered-column-to-pdf-table": { + "title": "Add Auto‑Numbered Column to PDF Table", + "filename": "add-auto-numbered-column-to-pdf-table.cs", + "description": "Shows how to create a PDF document with a table using Aspose.Pdf, add rows, and automatically fill the first column with sequential numbers.", + "tags": [ + "pdf", + "table", + "autonumber", + "aspose.pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-transparent-background-to-pdf-table": { + "title": "Add Transparent Background Color to PDF Table", + "filename": "add-transparent-background-to-pdf-table.cs", + "description": "Demonstrates setting a semi‑transparent background color for an Aspose.Pdf Table and saving the PDF, with platform‑specific handling for GDI+ availability.", + "tags": [ + "table", + "background-color", + "opacity", + "pdf", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Color.FromArgb", + "Aspose.Pdf.Color.LightGray", + "Aspose.Pdf.Document.Save", + "Aspose.Pdf.Page.Paragraphs.Add" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-table-zindex-in-pdf": { + "title": "Set Table Z-Index in PDF", + "filename": "set-table-zindex-in-pdf.cs", + "description": "Demonstrates how to assign a Z‑index to a Table in an Aspose.Pdf document to control its overlapping order with other page elements.", + "tags": [ + "table", + "z-index", + "pdf", + "aspose-pdf", + "overlap" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-table-to-textbox-form-field": { + "title": "Add a Table Inside a TextBox Form Field", + "filename": "add-table-to-textbox-form-field.cs", + "description": "Demonstrates creating a TextBox form field, building a tagged table structure, attaching the table to the PDF's logical structure, and setting the field's appearance to display the table.", + "tags": [ + "form-field", + "table", + "tagged-pdf", + "appearance", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Forms.TextBoxField", + "Aspose.Pdf.Annotations.Border", + "Aspose.Pdf.Tagged.TaggedContent", + "Aspose.Pdf.Tagged.TableElement", + "Aspose.Pdf.Tagged.TableTHeadElement", + "Aspose.Pdf.Tagged.TableTRElement", + "Aspose.Pdf.Forms.Form.AddFieldAppearance" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-table-inside-paragraph-to-pdf": { + "title": "Insert Table Within a Paragraph in a PDF", + "filename": "add-table-inside-paragraph-to-pdf.cs", + "description": "Demonstrates how to add a text fragment and then insert a table as a paragraph into an existing PDF document using Aspose.Pdf, with positioning and basic styling.", + "tags": [ + "table", + "pdf", + "aspose", + "paragraph", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.Position" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "render-table-high-dpi-images": { + "title": "Render Table with High‑DPI Images", + "filename": "render-table-high-dpi-images.cs", + "description": "Demonstrates creating a PDF, adding a two‑column table, and inserting high‑resolution images using Image.IsApplyResolution and ImageScale to preserve DPI while mixing text cells.", + "tags": [ + "table", + "high-dpi", + "image", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Image", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-pdf-table-from-datatable__v2": { + "title": "Create PDF Table with Dynamic Row Count from DataTable", + "filename": "create-pdf-table-from-datatable__v2.cs", + "description": "Demonstrates how to count source records, import a DataTable into an Aspose.Pdf Table, and save the resulting PDF, including platform‑specific handling for GDI+.", + "tags": [ + "pdf", + "table", + "datatable", + "aspose.pdf", + "dynamic-rows" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.Table.ImportDataTable", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "conditional-formatting-table-cells": { + "title": "Conditional Formatting of Table Cells in PDF", + "filename": "conditional-formatting-table-cells.cs", + "description": "Demonstrates how to apply background colors to PDF table cells based on numeric thresholds using Aspose.Pdf.", + "tags": [ + "conditional-formatting", + "pdf-table", + "background-color", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Drawing.Color" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "rotate-table-90-degrees": { + "title": "Rotate a Table 90 Degrees Using a Transformation Matrix", + "filename": "rotate-table-90-degrees.cs", + "description": "Shows how to rotate an entire table by 90° in a PDF by saving the graphics state, applying a ConcatenateMatrix, adding the table, and then restoring the state.", + "tags": [ + "table", + "rotation", + "matrix", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Operators.GSave", + "Aspose.Pdf.Operators.GRestore", + "Aspose.Pdf.Operators.ConcatenateMatrix" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "detect-merged-cells-in-pdf-tables": { + "title": "Detect Merged Cells in PDF Tables Using TableAbsorber", + "filename": "detect-merged-cells-in-pdf-tables.cs", + "description": "Loads a PDF, extracts tables with TableAbsorber (FlowEngine enabled), and reports cells whose ColSpan > 1, indicating horizontally merged cells.", + "tags": [ + "pdf", + "table", + "merged-cells", + "aspose", + "tableabsorber" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.TableAbsorber.UseFlowEngine", + "Aspose.Pdf.AbsorbedCell.ColSpan" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "replace-merged-table-cells": { + "title": "Replace Merged Table Cells with Separate Cells in PDF", + "filename": "replace-merged-table-cells.cs", + "description": "Shows how to locate a table in a PDF, split cells that span multiple columns into individual cells, and replace the original merged table using Aspose.Pdf.", + "tags": [ + "table", + "merged-cells", + "pdf", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.AbsorbedTable", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.TableAbsorber.Replace" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-footnote-references-in-table-cells": { + "title": "Add Footnote References in Table Cells", + "filename": "add-footnote-references-in-table-cells.cs", + "description": "Shows how to insert a superscript footnote number inside a table cell and associate it with a footnote paragraph at the end of the PDF using Aspose.Pdf.", + "tags": [ + "footnote", + "table", + "tagged-content", + "textfragment", + "pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Tagged.ITaggedContent", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.LogicalStructure.Note" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "insert-table-at-specific-position": { + "title": "Insert Table at Specific Position in PDF", + "filename": "insert-table-at-specific-position.cs", + "description": "Shows how to place a table at exact X and Y coordinates on a PDF page by configuring the table's MarginInfo and adding it to the page's paragraphs collection.", + "tags": [ + "table", + "position", + "pdf", + "aspose-pdf", + "margininfo" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextState", + "Aspose.Pdf.Text.FontRepository" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "right-align-table-in-pdf": { + "title": "Right Align Table in PDF", + "filename": "right-align-table-in-pdf.cs", + "description": "Demonstrates creating a table, setting its horizontal alignment to the right margin, adjusting the left offset, and adding it to a PDF document using Aspose.Pdf.", + "tags": [ + "table", + "alignment", + "pdf", + "aspose-pdf", + "right-align" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.HorizontalAlignment" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "create-table-with-2-point-border": { + "title": "Create Table with 2‑Point Border in PDF", + "filename": "create-table-with-2-point-border.cs", + "description": "Demonstrates how to generate a PDF, add a table, and set the table border thickness to 2 points using BorderInfo before rendering the document.", + "tags": [ + "table", + "border", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.Annotations.RichMediaAnnotation", + "Aspose.Pdf.Rectangle" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-multiline-text-to-table-cell": { + "title": "Add Multiline Text to a Table Cell", + "filename": "add-multiline-text-to-table-cell.cs", + "description": "Shows how to create a PDF table cell containing multiline text by adding several TextFragment objects separated with line‑break fragments using Aspose.Pdf.", + "tags": [ + "table", + "multiline", + "textfragment", + "pdf", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.FontRepository" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "extract-pdf-tables-to-csv": { + "title": "Extract PDF Tables to CSV using TableAbsorber", + "filename": "extract-pdf-tables-to-csv.cs", + "description": "Shows how to use Aspose.Pdf's TableAbsorber to locate tables on each PDF page and export each table's rows and cells into separate CSV files.", + "tags": [ + "table extraction", + "csv export", + "aspose pdf", + "tableabsorber", + "pdf tables" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.TableAbsorber.TableList", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "extract-pdf-tables-to-datatable": { + "title": "Extract PDF Tables to DataTable Using TableAbsorber", + "filename": "extract-pdf-tables-to-datatable.cs", + "description": "Demonstrates how to locate tables in a PDF with Aspose.Pdf's TableAbsorber, convert each table into a System.Data.DataTable, and output the extracted cell text.", + "tags": [ + "pdf", + "table-extraction", + "datatable", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.AbsorbedTable", + "Aspose.Pdf.AbsorbedRow", + "Aspose.Pdf.AbsorbedCell", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-custom-row-height-in-pdf-table": { + "title": "Set Custom Row Height in PDF Table", + "filename": "set-custom-row-height-in-pdf-table.cs", + "description": "Demonstrates how to assign a fixed height to a specific table row in a PDF using Aspose.Pdf. The example creates a table, sets a custom height for the second row, and saves the document.", + "tags": [ + "table", + "row-height", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Drawing.BorderInfo", + "Aspose.Pdf.Drawing.MarginInfo" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "auto-fit-row-height-in-pdf-table": { + "title": "Auto-fit Row Height in PDF Table", + "filename": "auto-fit-row-height-in-pdf-table.cs", + "description": "Shows how to let a table row automatically adjust its height to fit the cell content by setting FixedRowHeight to 0 (auto‑fit) using Aspose.Pdf.", + "tags": [ + "table", + "auto-fit", + "row-height", + "pdf", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo", + "Aspose.Pdf.TextState", + "Aspose.Pdf.FontRepository.FindFont" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "set-fixed-row-height-table-rows": { + "title": "Set Fixed Row Height for Table Rows in PDF", + "filename": "set-fixed-row-height-table-rows.cs", + "description": "Demonstrates how to assign a fixed height to each row of an Aspose.Pdf Table by setting the FixedRowHeight property before adding cells, and then saving the PDF document.", + "tags": [ + "table", + "fixed-row-height", + "pdf", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Text.TextFragment", + "Aspose.Pdf.Color" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "landscape-pdf-with-wide-table": { + "title": "Create Landscape PDF with Wide Table", + "filename": "landscape-pdf-with-wide-table.cs", + "description": "Shows how to set a page to landscape orientation and add a wide table that fits within the page using Aspose.Pdf.", + "tags": [ + "landscape", + "table", + "pdf", + "aspose.pdf", + "orientation" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.PageInfo.IsLandscape", + "Aspose.Pdf.Page.SetPageSize", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.Cell", + "Aspose.Pdf.Text.TextState", + "Aspose.Pdf.Text.FontRepository.FindFont" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "add-rotated-table-to-pdf-page": { + "title": "Add Rotated Table to PDF Page", + "filename": "add-rotated-table-to-pdf-page.cs", + "description": "Shows how to rotate a PDF page and then insert a table that automatically aligns with the rotated orientation.", + "tags": [ + "rotation", + "table", + "pdf", + "aspose-pdf", + "page" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Rotation", + "Aspose.Pdf.Table", + "Aspose.Pdf.Row", + "Aspose.Pdf.BorderInfo", + "Aspose.Pdf.MarginInfo" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "extract-modify-tables-rotated-pages": { + "title": "Extract and Modify Tables on Rotated PDF Pages", + "filename": "extract-modify-tables-rotated-pages.cs", + "description": "The example opens a PDF, checks each page for rotation, uses TableAbsorber to locate tables on rotated pages, and demonstrates modifying a cell's text before saving the document.", + "tags": [ + "table-absorption", + "rotation", + "pdf-modification", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Rotation", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.Text.TextFragment" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + }, + "remove-tables-containing-keyword": { + "title": "Remove Tables Containing a Keyword from PDF", + "filename": "remove-tables-containing-keyword.cs", + "description": "Demonstrates how to locate tables in a PDF using Aspose.Pdf's TableAbsorber, scan each cell for a specific keyword, and delete the matching tables before saving the document.", + "tags": [ + "pdf", + "tables", + "keyword", + "remove", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.TableAbsorber", + "Aspose.Pdf.TableAbsorber.Visit", + "Aspose.Pdf.TableAbsorber.Remove", + "Aspose.Pdf.TableAbsorber.TableList" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:58:17Z", + "status": "verified" + } + } +} \ No newline at end of file diff --git a/working-with-tables/insert-column-into-pdf-table.cs b/working-with-tables/insert-column-into-pdf-table.cs new file mode 100644 index 00000000..f5d4c6d0 --- /dev/null +++ b/working-with-tables/insert-column-into-pdf-table.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const int insertColumnIndex = 1; // zero‑based index where the new column will be inserted + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (lifecycle rule: use Document constructor) + using (Document doc = new Document(inputPath)) + { + // Ensure there is at least one page (page indexing is 1‑based) + Page page = doc.Pages[1]; + + // Create a simple table with 3 columns and 3 rows (for demonstration) + Table table = new Table + { + // Initial column widths (three columns) + ColumnWidths = "100 100 100", + // Simple border for visibility + Border = new BorderInfo(BorderSide.All, 0.5f) + }; + + // Populate the table with sample data + for (int r = 0; r < 3; r++) + { + Row row = table.Rows.Add(); // Add a new row + for (int c = 0; c < 3; c++) + { + // Add a cell with text "R{row}C{col}" + Cell cell = row.Cells.Add($"R{r + 1}C{c + 1}"); + // Optional: set cell border (use the correct property name) + cell.Border = new BorderInfo(BorderSide.All, 0.5f); + } + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Insert a new column at the specified index by adding a Cell to each Row + foreach (Row row in table.Rows) + { + // Create a new empty cell + Cell newCell = new Cell(); + + // Optionally add placeholder text to the new cell + newCell.Paragraphs.Add(new TextFragment("New")); + + // Insert the cell at the desired column index + row.Cells.Insert(insertColumnIndex, newCell); + } + + // Adjust column widths to accommodate the new column (equal widths for simplicity) + int columnCount = table.Rows[0].Cells.Count; // assume at least one row exists + string[] widths = new string[columnCount]; + for (int i = 0; i < columnCount; i++) widths[i] = "100"; + table.ColumnWidths = string.Join(" ", widths); + + // Save the modified PDF (lifecycle rule: use Document.Save) + doc.Save(outputPath); + } + + Console.WriteLine($"Column inserted and saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/insert-image-from-memory-stream-into-pdf-table-cell.cs b/working-with-tables/insert-image-from-memory-stream-into-pdf-table-cell.cs new file mode 100644 index 00000000..46d8e916 --- /dev/null +++ b/working-with-tables/insert-image-from-memory-stream-into-pdf-table-cell.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Paths for the source PDF, the image file (used as a memory stream), and the output PDF. + const string inputPdfPath = "input.pdf"; + const string imagePath = "sample.jpg"; + const string outputPdfPath = "output.pdf"; + + // Verify that the required files exist. + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // Open the source PDF inside a using block to ensure proper disposal. + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Load the image into a memory stream. + using (FileStream imgStream = File.OpenRead(imagePath)) + { + // Create an Image object and assign the stream. + Aspose.Pdf.Image pdfImage = new Aspose.Pdf.Image + { + // The ImageStream property accepts a Stream containing the image data. + ImageStream = imgStream + }; + + // Create a table with a single cell. + Aspose.Pdf.Table table = new Aspose.Pdf.Table(); + + // Optionally set column widths (here we use a single column that spans the page width). + table.ColumnWidths = "100%"; + + // Add a row to the table. + Aspose.Pdf.Row row = table.Rows.Add(); + + // Add a cell to the row. + Aspose.Pdf.Cell cell = row.Cells.Add(); + + // Insert the image into the cell's paragraph collection. + cell.Paragraphs.Add(pdfImage); + + // Add the table to the first page of the document. + // Ensure the page exists; Aspose.Pdf uses 1‑based indexing. + if (pdfDoc.Pages.Count == 0) + { + pdfDoc.Pages.Add(); + } + pdfDoc.Pages[1].Paragraphs.Add(table); + } + + // Save the modified PDF. The using block ensures the document is disposed after saving. + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Image inserted into table cell and saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-image-into-table-cell.cs b/working-with-tables/insert-image-into-table-cell.cs new file mode 100644 index 00000000..7725c467 --- /dev/null +++ b/working-with-tables/insert-image-into-table-cell.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Paths – adjust as needed + string dataDir = "Data"; // folder containing the image + string imagePath = Path.Combine(dataDir, "sample.png"); + string outputPdf = Path.Combine(dataDir, "TableWithImage.pdf"); + + // Ensure the image file exists + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image not found: {imagePath}"); + return; + } + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + doc.Pages.Add(); + Page page = doc.Pages[1]; + + // Create a table with two columns + Table table = new Table + { + // Define column widths (in points). Adjust as required. + ColumnWidths = "250 250" + }; + + // Add a row to the table + Row row = table.Rows.Add(); + + // ----- First cell: simple text ----- + Cell textCell = row.Cells.Add(); + TextFragment tf = new TextFragment("This cell contains text."); + textCell.Paragraphs.Add(tf); + + // ----- Second cell: image ----- + Cell imageCell = row.Cells.Add(); + + // Create an Image object, set its source file, and add it to the cell + Image img = new Image + { + File = imagePath + // Optional: set explicit dimensions + // FixWidth = 200, + // FixHeight = 150 + }; + imageCell.Paragraphs.Add(img); + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"PDF created: {outputPdf}"); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-page-break-after-table-row.cs b/working-with-tables/insert-page-break-after-table-row.cs new file mode 100644 index 00000000..bba95ec9 --- /dev/null +++ b/working-with-tables/insert-page-break-after-table-row.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Assume the first page contains a table. + // Locate the first Table element in the page's paragraphs. + Table table = null; + foreach (var paragraph in doc.Pages[1].Paragraphs) + { + if (paragraph is Table tbl) + { + table = tbl; + break; + } + } + + if (table == null) + { + Console.Error.WriteLine("No table found on the first page."); + return; + } + + // Choose the row after which we want a page break. + // Row indices are zero‑based in the Rows collection. + int targetRowIndex = 2; // break after the third row (index 2) + + if (targetRowIndex < 0 || targetRowIndex >= table.Rows.Count) + { + Console.Error.WriteLine("Target row index is out of range."); + return; + } + + // Set IsInNewPage on the row that should start on a new page. + // This forces the row (and all following rows) to be printed on the next page. + table.Rows[targetRowIndex].IsInNewPage = true; + + // Save the modified document + doc.Save(outputPath); + } + + Console.WriteLine($"Document saved with page break after row {2} to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-svg-into-table-cell.cs b/working-with-tables/insert-svg-into-table-cell.cs new file mode 100644 index 00000000..8aae6085 --- /dev/null +++ b/working-with-tables/insert-svg-into-table-cell.cs @@ -0,0 +1,84 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // existing PDF (can be empty) + const string outputPdf = "output_with_svg.pdf"; + const string svgPath = "image.svg"; // path to the SVG file to embed + + if (!File.Exists(svgPath)) + { + Console.Error.WriteLine($"SVG file not found: {svgPath}"); + return; + } + + // Load (or create) the PDF document + using (Document doc = File.Exists(inputPdf) ? new Document(inputPdf) : new Document()) + { + // Ensure there is at least one page + if (doc.Pages.Count == 0) + doc.Pages.Add(); + + // Create a table with a single column + Table table = new Table + { + ColumnWidths = "500" // width of the single column (points) + }; + + // Add a row + Row row = table.Rows.Add(); + + // Add a cell to the row + Cell cell = row.Cells.Add(); + + // Create an Image object that points to the SVG file + Image svgImage = new Image + { + File = svgPath + }; + + // Add the image to the cell's paragraph collection + cell.Paragraphs.Add(svgImage); + + // Add the table to the first page + doc.Pages[1].Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPdf); + } + else + { + try + { + doc.Save(outputPdf); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) is not available on this platform. PDF saved without rendering the SVG."); + } + } + } + + Console.WriteLine($"PDF saved to '{outputPdf}'."); + } + + // Helper to detect a nested DllNotFoundException (libgdiplus) inside TypeInitializationException + private static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/insert-table-after-paragraph.cs b/working-with-tables/insert-table-after-paragraph.cs new file mode 100644 index 00000000..f69012ab --- /dev/null +++ b/working-with-tables/insert-table-after-paragraph.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class InsertTableAfterParagraph +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string searchText = "Insert table after this paragraph"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Open the PDF document + using (Document doc = new Document(inputPath)) + { + // Assume the paragraph is on the first page; adjust as needed + Page page = doc.Pages[1]; + + // Locate the paragraph (TextFragment) that contains the target text + int paragraphIndex = -1; + for (int i = 0; i < page.Paragraphs.Count; i++) + { + if (page.Paragraphs[i] is TextFragment tf && tf.Text.Contains(searchText)) + { + paragraphIndex = i; + break; + } + } + + if (paragraphIndex == -1) + { + Console.Error.WriteLine("Target paragraph not found."); + doc.Save(outputPath); // Save unchanged document + return; + } + + // Create a new table + Table table = new Table + { + // Optional visual settings + Border = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Define column widths (optional) + table.ColumnWidths = "100 150"; + + // Add a header row + Row header = table.Rows.Add(); + header.Cells.Add("Header 1"); + header.Cells.Add("Header 2"); + header.DefaultCellTextState = new TextState + { + FontSize = 12, + FontStyle = FontStyles.Bold, + Font = FontRepository.FindFont("Helvetica") + }; + + // Add a data row + Row data = table.Rows.Add(); + data.Cells.Add("Cell A1"); + data.Cells.Add("Cell B1"); + + // Insert the table immediately after the located paragraph + // Paragraphs.Insert expects the index where the new element will be placed + page.Paragraphs.Insert(paragraphIndex + 1, table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Table inserted and saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-table-at-specific-position.cs b/working-with-tables/insert-table-at-specific-position.cs new file mode 100644 index 00000000..92a7e28d --- /dev/null +++ b/working-with-tables/insert-table-at-specific-position.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class InsertTableAtPosition +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Choose the page where the table will be placed (1‑based index) + Page page = doc.Pages[1]; + + // Create a new table + Table table = new Table(); + + // Set the absolute position of the table on the page using MarginInfo. + // X = 100 points from the left, Y = 500 points from the bottom. + // Aspose.Pdf uses a top‑down coordinate system for margins, so we set the left margin + // and calculate the top margin as (page height - desired Y coordinate). + double desiredX = 100; // points from left + double desiredYFromBottom = 500; // points from bottom + double topMargin = page.PageInfo.Height - desiredYFromBottom; // convert to top‑based coordinate + table.Margin = new MarginInfo { Left = desiredX, Top = topMargin }; + + // Define column widths (two columns, 200 points each) + table.ColumnWidths = "200 200"; + + // Add a header row + Row header = table.Rows.Add(); + Cell headerCell1 = header.Cells.Add("Header 1"); + Cell headerCell2 = header.Cells.Add("Header 2"); + headerCell1.DefaultCellTextState = new TextState + { + FontSize = 12, + Font = FontRepository.FindFont("Helvetica"), + ForegroundColor = Aspose.Pdf.Color.Black // Aspose.Pdf.Color, not System.Drawing.Color + }; + headerCell2.DefaultCellTextState = new TextState + { + FontSize = 12, + Font = FontRepository.FindFont("Helvetica"), + ForegroundColor = Aspose.Pdf.Color.Black + }; + + // Add a data row + Row dataRow = table.Rows.Add(); + dataRow.Cells.Add("Value A"); + dataRow.Cells.Add("Value B"); + + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Table inserted at (100, 500) and saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/insert-table-before-image.cs b/working-with-tables/insert-table-before-image.cs new file mode 100644 index 00000000..55ccc3dd --- /dev/null +++ b/working-with-tables/insert-table-before-image.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Iterate through all pages + for (int p = 1; p <= doc.Pages.Count; p++) + { + Page page = doc.Pages[p]; + + // ParagraphCollection is 1‑based. Scan for Image objects. + for (int i = 1; i <= page.Paragraphs.Count; i++) + { + // The concrete type for an image placed on a page is Aspose.Pdf.Image + if (page.Paragraphs[i] is Image) + { + // Build a simple table to insert before the image + Table table = new Table + { + // Optional visual settings + Border = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Define two columns (adjust widths as needed) + table.ColumnWidths = "200 200"; + + // Header row + Row header = table.Rows.Add(); + header.Cells.Add("Column 1"); + header.Cells.Add("Column 2"); + // Apply a simple background to header cells + foreach (Cell cell in header.Cells) + { + cell.BackgroundColor = Aspose.Pdf.Color.LightGray; + cell.DefaultCellTextState = new TextState + { + FontSize = 12, + FontStyle = FontStyles.Bold, + Font = FontRepository.FindFont("Helvetica") + }; + } + + // Data row + Row data = table.Rows.Add(); + data.Cells.Add("Value A"); + data.Cells.Add("Value B"); + + // Insert the table before the image (at the same index) + page.Paragraphs.Insert(i, table); + + // If there may be multiple images and you only want the first, + // break out of the inner loop after insertion. + // break; + } + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Table inserted before images and saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-table-into-pdf-page.cs b/working-with-tables/insert-table-into-pdf-page.cs new file mode 100644 index 00000000..7294dd1e --- /dev/null +++ b/working-with-tables/insert-table-into-pdf-page.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // Added for TextState and FontRepository + +class InsertTableExample +{ + static void Main() + { + // Input PDF path, output PDF path, and target page number (1‑based) + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const int targetPage = 2; // Insert table on page 2 + + // Table position (coordinates in points) and size + const double tableLeft = 100; // X coordinate of left side + const double tableTop = 500; // Y coordinate of top side + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the existing PDF document + using (Document doc = new Document(inputPath)) + { + // Ensure the requested page exists + if (targetPage < 1 || targetPage > doc.Pages.Count) + { + Console.Error.WriteLine($"Page {targetPage} is out of range. Document has {doc.Pages.Count} pages."); + return; + } + + // Create a new Table instance + Table table = new Table(); + + // Position the table on the page (cast double to float as required by the API) + table.Left = (float)tableLeft; + table.Top = (float)tableTop; + + // Optional: set table appearance + table.Border = new BorderInfo(BorderSide.All, 1, Aspose.Pdf.Color.Black); + table.DefaultCellPadding = new MarginInfo(5, 5, 5, 5); + table.DefaultCellTextState = new TextState { FontSize = 12, Font = FontRepository.FindFont("Helvetica") }; + + // Add some rows and cells + // Row 1 (header) + Row headerRow = table.Rows.Add(); + Cell headerCell1 = headerRow.Cells.Add("Product"); + Cell headerCell2 = headerRow.Cells.Add("Price"); + // Apply bold style to header cells + headerCell1.DefaultCellTextState = new TextState { FontSize = 12, Font = FontRepository.FindFont("Helvetica-Bold") }; + headerCell2.DefaultCellTextState = new TextState { FontSize = 12, Font = FontRepository.FindFont("Helvetica-Bold") }; + + // Row 2 (data) + Row dataRow = table.Rows.Add(); + dataRow.Cells.Add("Widget A"); + dataRow.Cells.Add("$25.00"); + + // Row 3 (data) + Row dataRow2 = table.Rows.Add(); + dataRow2.Cells.Add("Widget B"); + dataRow2.Cells.Add("$30.00"); + + // Retrieve the target page and add the table to its paragraphs collection + Page page = doc.Pages[targetPage]; + page.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Table inserted on page {targetPage} and saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/landscape-pdf-with-wide-table.cs b/working-with-tables/landscape-pdf-with-wide-table.cs new file mode 100644 index 00000000..190e1548 --- /dev/null +++ b/working-with-tables/landscape-pdf-with-wide-table.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Paths for the output PDF + const string outputPath = "landscape_table.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a blank page (pages are 1‑based) + Page page = doc.Pages.Add(); + + // Set the page orientation to landscape. + page.PageInfo.IsLandscape = true; + // Adjust the page size to A4 landscape dimensions (width > height). + page.SetPageSize(842, 595); + + // Create a wide table with many columns to demonstrate landscape fitting + Table table = new Table + { + Top = 50, + Left = 20, + BackgroundColor = Color.LightGray, + ColumnWidths = "100 100 100 100 100 100 100 100" + }; + + // Add a header row + Row header = table.Rows.Add(); + for (int i = 1; i <= 8; i++) + { + Cell cell = header.Cells.Add($"Header {i}"); + cell.DefaultCellTextState = new TextState + { + Font = FontRepository.FindFont("Helvetica-Bold"), + FontSize = 12, + ForegroundColor = Color.Black, + HorizontalAlignment = HorizontalAlignment.Center + }; + } + + // Add a few data rows + for (int r = 1; r <= 5; r++) + { + Row dataRow = table.Rows.Add(); + for (int c = 1; c <= 8; c++) + { + Cell cell = dataRow.Cells.Add($"R{r}C{c}"); + cell.DefaultCellTextState = new TextState + { + Font = FontRepository.FindFont("Helvetica"), + FontSize = 10, + ForegroundColor = Color.Black + }; + } + } + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF was generated in memory but could not be saved to disk."); + } + } + } + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/map-datatable-columns-to-pdf-table.cs b/working-with-tables/map-datatable-columns-to-pdf-table.cs new file mode 100644 index 00000000..5198fdc0 --- /dev/null +++ b/working-with-tables/map-datatable-columns-to-pdf-table.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Drawing; // for Color, BorderInfo, etc. + +class Program +{ + static void Main() + { + // Input PDF (existing or new) and output PDF paths + const string inputPdf = "template.pdf"; // can be an empty PDF or a template page + const string outputPdf = "mapped_table.pdf"; + + // Sample DataTable with some data + DataTable dt = new DataTable(); + dt.Columns.Add("ID", typeof(int)); + dt.Columns.Add("Name", typeof(string)); + dt.Columns.Add("Age", typeof(int)); + dt.Columns.Add("City", typeof(string)); + + dt.Rows.Add(1, "Alice", 30, "London"); + dt.Rows.Add(2, "Bob", 25, "Paris"); + dt.Rows.Add(3, "Carol", 28, "Berlin"); + + // Mapping: DataTable column name -> target Table column index (zero‑based) + // Example: map "Name" to column 0, "Age" to column 2, "City" to column 4 + var columnMap = new Dictionary + { + { "Name", 0 }, + { "Age", 2 }, + { "City", 4 } + }; + + // Ensure the target table has enough columns. + // Here we create 5 columns (indices 0‑4) with equal widths. + int totalTargetColumns = columnMap.Values.Max() + 1; + var columnWidths = Enumerable.Repeat(100f, totalTargetColumns).ToArray(); + // Aspose.Pdf.Table.ColumnWidths expects a space‑separated string, not a float array. + string columnWidthsString = string.Join(" ", columnWidths.Select(w => w.ToString(CultureInfo.InvariantCulture))); + + // Load the template PDF if it exists; otherwise create a new empty document. + Document doc; + if (File.Exists(inputPdf)) + { + doc = new Document(inputPdf); + } + else + { + doc = new Document(); + // Ensure at least one page exists. + doc.Pages.Add(); + } + + // Create a table and set its column widths + Table table = new Table + { + ColumnWidths = columnWidthsString, + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Color.Black) // Aspose.Pdf.Drawing.Color + }; + + // Prepare a list of all source row indices (zero‑based) + int[] sourceRows = Enumerable.Range(0, dt.Rows.Count).ToArray(); + + // Import each mapped column individually + foreach (var kvp in columnMap) + { + string sourceColumnName = kvp.Key; + int targetColumnIndex = kvp.Value; + + // Guard against missing columns in the DataTable + if (!dt.Columns.Contains(sourceColumnName)) + continue; // or throw, depending on requirements + + // Get the zero‑based index of the source column in the DataTable + int sourceColumnIndex = dt.Columns[sourceColumnName].Ordinal; + + // Import only this column (sourceColumnList contains a single index) + int[] sourceColumns = new int[] { sourceColumnIndex }; + + // Import the column data into the table. + table.ImportDataTable( + dt, + sourceRows, + sourceColumns, + firstFilledRow: 0, + firstFilledColumn: targetColumnIndex, + showColumnNamesAsFirstRow: false, + isHtmlSupported: false); + } + + // Ensure the document has at least one page; if not, add a blank page. + if (doc.Pages.Count == 0) + doc.Pages.Add(); + + // Add the table to the first page (index 1 in Aspose – pages are 1‑based). + // Use the null‑forgiving operator because Aspose guarantees a Page object when Count > 0. + doc.Pages[1]!.Paragraphs.Add(table); + + // Save the resulting PDF – guard against missing libgdiplus on non‑Windows platforms. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPdf); + } + else + { + try + { + doc.Save(outputPdf); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: libgdiplus (GDI+) is not available on this platform. PDF was not saved."); + } + } + + Console.WriteLine($"PDF with mapped table processing completed. Output path: '{outputPdf}'."); + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus). + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/merge-table-cells-vertically-rowspan.cs b/working-with-tables/merge-table-cells-vertically-rowspan.cs new file mode 100644 index 00000000..8d78fb8a --- /dev/null +++ b/working-with-tables/merge-table-cells-vertically-rowspan.cs @@ -0,0 +1,78 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string outputPath = "table_rowspan.pdf"; + + // Create a new PDF document and ensure deterministic disposal + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table with three equal-width columns + Table table = new Table + { + ColumnWidths = "100 100 100" + }; + + // ----- First row ----- + Row row1 = table.Rows.Add(); + + // Cell that will span two rows (merge with the cell directly below) + Cell mergedCell = row1.Cells.Add("Merged Cell"); + mergedCell.RowSpan = 2; // Set RowSpan to 2 + + // Add the remaining cells for the first row + row1.Cells.Add("Cell 1-2"); + row1.Cells.Add("Cell 1-3"); + + // ----- Second row ----- + Row row2 = table.Rows.Add(); + + // Since the first cell of the previous row spans two rows, + // we only need to add two cells in this row. + row2.Cells.Add("Cell 2-2"); + row2.Cells.Add("Cell 2-3"); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'. (non‑Windows platform, GDI+ may be missing but save succeeded)"); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF could not be saved."); + } + } + } + } + + // Helper method to walk the inner‑exception chain and detect a missing native library + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/offset-table-left-margin.cs b/working-with-tables/offset-table-left-margin.cs new file mode 100644 index 00000000..49f6ddaf --- /dev/null +++ b/working-with-tables/offset-table-left-margin.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // Needed for TextFragment + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing PDF inside a using block (ensures proper disposal) + using (Document doc = new Document(inputPath)) + { + // Create a new table + Table table = new Table(); + + // Set the left offset by configuring the MarginInfo.Left property (value in points) + table.Margin = new MarginInfo(); + table.Margin.Left = 50; // offset 50 points from the left margin + + // Optional: add a simple row and cell for demonstration + Row row = table.Rows.Add(); + Cell cell = row.Cells.Add(); + cell.Paragraphs.Add(new TextFragment("Sample cell")); + + // Add the table to the first page + Page page = doc.Pages[1]; + page.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Table offset applied and saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/pdf-table-alternating-row-colors.cs b/working-with-tables/pdf-table-alternating-row-colors.cs new file mode 100644 index 00000000..ba92d5c9 --- /dev/null +++ b/working-with-tables/pdf-table-alternating-row-colors.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "alternating_rows.pdf"; + + // Create a new PDF document and ensure proper disposal + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table with 5 columns + Table table = new Table + { + ColumnWidths = "100 100 100 100 100", + Border = new BorderInfo(BorderSide.All, 0.5f) + }; + + // Add a header row + Row header = table.Rows.Add(); + for (int c = 0; c < 5; c++) + { + Cell cell = header.Cells.Add(); + cell.Paragraphs.Add(new TextFragment($"Header {c + 1}")); + cell.BackgroundColor = Aspose.Pdf.Color.LightBlue; + cell.DefaultCellTextState = new TextState { FontSize = 12, FontStyle = FontStyles.Bold }; + } + + // Add data rows + for (int r = 0; r < 10; r++) + { + Row row = table.Rows.Add(); + for (int c = 0; c < 5; c++) + { + Cell cell = row.Cells.Add(); + cell.Paragraphs.Add(new TextFragment($"R{r + 1}C{c + 1}")); + } + } + + // Apply alternating background colors to each row's cells + for (int i = 0; i < table.Rows.Count; i++) + { + Row row = table.Rows[i]; + // Choose background based on row index parity + Aspose.Pdf.Color bg = (i % 2 == 0) ? Aspose.Pdf.Color.LightGray : Aspose.Pdf.Color.White; + foreach (Cell cell in row.Cells) + { + cell.BackgroundColor = bg; + } + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + } + else + { + try + { + doc.Save(outputPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + + Console.WriteLine($"PDF saved to {Path.GetFullPath(outputPath)}"); + } + + // Helper that walks the inner‑exception chain looking for a DllNotFoundException (e.g., libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/populate-pdf-table-from-linq.cs b/working-with-tables/populate-pdf-table-from-linq.cs new file mode 100644 index 00000000..6c2aca9b --- /dev/null +++ b/working-with-tables/populate-pdf-table-from-linq.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + try + { + // Sample data source – a list of anonymous objects + var people = new List<(int Id, string Name, int Age)> + { + (1, "Alice", 30), + (2, "Bob", 25), + (3, "Carol", 28) + }; + + // LINQ query – select the data we want in the table + var query = from p in people + select new { p.Id, p.Name, p.Age }; + + // Convert the query result to a DataTable + DataTable dataTable = new DataTable(); + + // Add columns based on the query's property names + foreach (var prop in query.First().GetType().GetProperties()) + { + dataTable.Columns.Add(prop.Name, prop.PropertyType); + } + + // Add rows + foreach (var item in query) + { + var row = dataTable.NewRow(); + foreach (var prop in item.GetType().GetProperties()) + { + row[prop.Name] = prop.GetValue(item, null) ?? DBNull.Value; + } + dataTable.Rows.Add(row); + } + + // Create a new PDF document (or load an existing one) + using (Document doc = new Document()) + { + // Add a page to host the table + Page page = doc.Pages.Add(); + + // Create the Aspose.Pdf.Table + Table table = new Table + { + // Optional visual settings + Border = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5), + // Use the correct enum value for auto‑fit behavior + ColumnAdjustment = ColumnAdjustment.AutoFitToContent + }; + + // Import the DataTable into the Aspose.Pdf.Table + // Parameters: (DataTable, import column names as first row, start row, start column) + table.ImportDataTable(dataTable, true, 0, 0); + + // Position the table on the page + table.Margin = new MarginInfo { Top = 50, Left = 50 }; + page.Paragraphs.Add(table); + + // Save the PDF + doc.Save("output.pdf"); + } + + Console.WriteLine("PDF with populated table saved as 'output.pdf'."); + } + catch (FileNotFoundException ex) when (ex.FileName != null && ex.FileName.Contains("AsposePdfApi")) + { + Console.Error.WriteLine("Required Aspose.Pdf native library not found: " + ex.FileName); + Console.Error.WriteLine("Make sure the corresponding AsposePdfApi_*.dll is copied to the output directory."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"An unexpected error occurred: {ex.Message}"); + } + } +} diff --git a/working-with-tables/prevent-table-splitting.cs b/working-with-tables/prevent-table-splitting.cs new file mode 100644 index 00000000..e0bf96c8 --- /dev/null +++ b/working-with-tables/prevent-table-splitting.cs @@ -0,0 +1,86 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "table_no_split.pdf"; + + // Create a new PDF document inside a using block for deterministic disposal + using (Aspose.Pdf.Document doc = new Aspose.Pdf.Document()) + { + // Add a single page (pages are 1‑based) + Aspose.Pdf.Page page = doc.Pages.Add(); + + // Create a table and disable automatic splitting across pages + Aspose.Pdf.Table table = new Aspose.Pdf.Table + { + IsBroken = false, // forces the whole table to stay on one page + Border = new BorderInfo(BorderSide.All, 1f, Aspose.Pdf.Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Define three equal column widths (adjust as needed) + table.ColumnWidths = "100 100 100"; + + // Add a header row + Row header = table.Rows.Add(); + header.BackgroundColor = Aspose.Pdf.Color.LightGray; + header.IsRowBroken = false; // keep header row intact + header.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 1") } }); + header.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 2") } }); + header.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 3") } }); + + // Add many data rows – enough to normally cause a split + for (int i = 0; i < 30; i++) + { + Row row = table.Rows.Add(); + row.IsRowBroken = false; // ensure each row stays together + row.Cells.Add(new Cell { Paragraphs = { new TextFragment($"Row {i + 1} Col 1") } }); + row.Cells.Add(new Cell { Paragraphs = { new TextFragment($"Row {i + 1} Col 2") } }); + row.Cells.Add(new Cell { Paragraphs = { new TextFragment($"Row {i + 1} Col 3") } }); + } + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the document. + // On non‑Windows platforms Aspose.Pdf may require libgdiplus for rendering. + // Guard the Save call to avoid a TypeInitializationException. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + } + else + { + try + { + doc.Save(outputPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) not available; PDF saved without graphics rendering."); + } + } + } + + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + + // Helper method to walk inner exceptions and detect a missing native library + static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/read-rendered-table-width.cs b/working-with-tables/read-rendered-table-width.cs new file mode 100644 index 00000000..faec7e80 --- /dev/null +++ b/working-with-tables/read-rendered-table-width.cs @@ -0,0 +1,98 @@ +using System; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; // for BorderInfo + +class Program +{ + static void Main() + { + const string outputPath = "table_output.pdf"; + + // Create a new PDF document and ensure deterministic disposal + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table with three columns; column widths will be auto‑calculated after layout + Table table = new Table + { + // Optional: set a default border for visual clarity + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f) + }; + + // First row + Row row1 = table.Rows.Add(); + row1.Cells.Add("Cell 1"); + row1.Cells.Add("Cell 2"); + row1.Cells.Add("Cell 3"); + + // Second row + Row row2 = table.Rows.Add(); + row2.Cells.Add("Another 1"); + row2.Cells.Add("Another 2"); + row2.Cells.Add("Another 3"); + + // Add the table to the page at the desired position + page.Paragraphs.Add(table); + + // After the table is added to the page the layout engine calculates its size. + // The rendered width can be obtained by parsing the calculated column widths string. + double renderedWidth = ParseColumnWidths(table.ColumnWidths).Sum(); + Console.WriteLine($"Rendered table width: {renderedWidth}"); + + // Save the PDF – guard against missing libgdiplus on non‑Windows platforms. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus). + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } + + // Parses the Table.ColumnWidths string (e.g., "50 100 150") into a sequence of doubles. + private static IEnumerable ParseColumnWidths(string columnWidths) + { + if (string.IsNullOrWhiteSpace(columnWidths)) + return Enumerable.Empty(); + + // Split by spaces or commas, remove empty entries, and parse each token. + return columnWidths + .Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(token => + { + // Use InvariantCulture to ensure '.' as decimal separator. + if (double.TryParse(token, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double value)) + return value; + // If parsing fails, treat the width as 0 to avoid exceptions. + return 0.0; + }); + } +} diff --git a/working-with-tables/remove-all-tables-from-pdf.cs b/working-with-tables/remove-all-tables-from-pdf.cs new file mode 100644 index 00000000..a6d71e2b --- /dev/null +++ b/working-with-tables/remove-all-tables-from-pdf.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; +using System.Linq; // For ToList() +using Aspose.Pdf; // Document, Page +using Aspose.Pdf.Text; // TableAbsorber, AbsorbedTable + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to find tables in the document + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from the whole document + absorber.Visit(doc); + + // Copy the TableList because Remove modifies the collection + var tables = absorber.TableList.ToList(); + + // Remove each absorbed table from its page + foreach (AbsorbedTable table in tables) + { + absorber.Remove(table); + } + + // Save the modified PDF (lifecycle rule: save after modifications) + doc.Save(outputPath); + } + + Console.WriteLine($"Tables removed and document saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/remove-first-table-from-pdf.cs b/working-with-tables/remove-first-table-from-pdf.cs new file mode 100644 index 00000000..dc0a1a58 --- /dev/null +++ b/working-with-tables/remove-first-table-from-pdf.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // TableAbsorber, AbsorbedTable + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to locate tables + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from the first page (pages are 1‑based) + absorber.Visit(doc.Pages[1]); + + // If at least one table was found, remove the first one + if (absorber.TableList.Count > 0) + { + AbsorbedTable tableToRemove = absorber.TableList[0]; + absorber.Remove(tableToRemove); + Console.WriteLine("Removed one table from the document."); + } + else + { + Console.WriteLine("No tables found on the first page."); + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Document saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/remove-table-column-from-pdf.cs b/working-with-tables/remove-table-column-from-pdf.cs new file mode 100644 index 00000000..48945e14 --- /dev/null +++ b/working-with-tables/remove-table-column-from-pdf.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using System.Linq; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const int columnIndexToRemove = 1; // zero‑based index of the column to delete + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Process each page + foreach (Page page in doc.Pages) + { + // Find all tables on the page + var tables = page.Paragraphs.OfType().ToList(); + + foreach (Table table in tables) + { + // Remove the cell at the specified column index from every row + foreach (Row row in table.Rows) + { + if (columnIndexToRemove >= 0 && columnIndexToRemove < row.Cells.Count) + { + Cell cell = row.Cells[columnIndexToRemove]; + row.Cells.Remove(cell); // Cells.Remove method + } + } + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Column removed and saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/remove-tables-containing-keyword.cs b/working-with-tables/remove-tables-containing-keyword.cs new file mode 100644 index 00000000..8ce8667d --- /dev/null +++ b/working-with-tables/remove-tables-containing-keyword.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using System.Linq; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string keyword = "CONFIDENTIAL"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to locate tables in the document + TableAbsorber absorber = new TableAbsorber(); + + // Extract tables from all pages + absorber.Visit(doc); + + // Work on a copy of the TableList because Remove() changes the collection + var tables = absorber.TableList.ToArray(); + + foreach (var table in tables) + { + bool containsKeyword = false; + + // Examine each cell's text fragments for the keyword + foreach (var row in table.RowList) + { + foreach (var cell in row.CellList) + { + foreach (var fragment in cell.TextFragments) + { + if (fragment.Text != null && + fragment.Text.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0) + { + containsKeyword = true; + break; + } + } + if (containsKeyword) break; + } + if (containsKeyword) break; + } + + // Remove the table if the keyword was found in any cell + if (containsKeyword) + { + absorber.Remove(table); + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/render-table-from-xml-to-pdf.cs b/working-with-tables/render-table-from-xml-to-pdf.cs new file mode 100644 index 00000000..af023086 --- /dev/null +++ b/working-with-tables/render-table-from-xml-to-pdf.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core Aspose.Pdf namespace provides Document, XmlLoadOptions, etc. + +class Program +{ + static void Main() + { + // Paths to the source XML definition and the target PDF file + const string xmlPath = "table-definition.xml"; + const string pdfPath = "rendered-table.pdf"; + + // Verify that the XML file exists + if (!File.Exists(xmlPath)) + { + Console.Error.WriteLine($"Error: XML file not found at '{xmlPath}'."); + return; + } + + // Load the XML definition (PDFXML format) using XmlLoadOptions. + // XmlLoadOptions resides directly in the Aspose.Pdf namespace, so no extra using directive is required. + XmlLoadOptions loadOptions = new XmlLoadOptions(); + + // The Document constructor with XmlLoadOptions reconstructs the Table object defined in the XML. + using (Document pdfDocument = new Document(xmlPath, loadOptions)) + { + // Save the reconstructed document as a PDF. + pdfDocument.Save(pdfPath); + } + + Console.WriteLine($"Table rendered successfully to '{pdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/render-table-high-dpi-images.cs b/working-with-tables/render-table-high-dpi-images.cs new file mode 100644 index 00000000..afa80e61 --- /dev/null +++ b/working-with-tables/render-table-high-dpi-images.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + // Paths – adjust as needed + const string outputPdf = "TableWithHighDpiImages.pdf"; + const string imagePath1 = "highres1.jpg"; + const string imagePath2 = "highres2.png"; + + // Ensure the image files exist before proceeding + if (!File.Exists(imagePath1) || !File.Exists(imagePath2)) + { + Console.Error.WriteLine("One or more image files not found."); + return; + } + + // Create a new PDF document inside a using block for deterministic disposal + using (Document doc = new Document()) + { + // Add a single page to the document + Page page = doc.Pages.Add(); + + // Create a table with two columns + Table table = new Table + { + // Define column widths (in points). Adjust as required. + ColumnWidths = "200 200", + // Optional visual styling + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // ---------- First Row ---------- + Row row1 = table.Rows.Add(); + + // First cell – text + Cell textCell = row1.Cells.Add(); + TextFragment tf = new TextFragment("Sample Text"); + tf.TextState.FontSize = 12; + tf.TextState.ForegroundColor = Aspose.Pdf.Color.Black; + textCell.Paragraphs.Add(tf); + + // Second cell – high‑DPI image + Cell imgCell1 = row1.Cells.Add(); + Image img1 = new Image + { + File = imagePath1, + // Instruct Aspose.Pdf to respect the image's native resolution + IsApplyResolution = true, + // Scale factor >1 can be used to increase the effective DPI in the PDF + ImageScale = 2.0 + }; + imgCell1.Paragraphs.Add(img1); + + // ---------- Second Row ---------- + Row row2 = table.Rows.Add(); + + // First cell – another high‑DPI image + Cell imgCell2 = row2.Cells.Add(); + Image img2 = new Image + { + File = imagePath2, + IsApplyResolution = true, + ImageScale = 2.0 + }; + imgCell2.Paragraphs.Add(img2); + + // Second cell – text + Cell textCell2 = row2.Cells.Add(); + TextFragment tf2 = new TextFragment("More Text"); + tf2.TextState.FontSize = 12; + tf2.TextState.ForegroundColor = Aspose.Pdf.Color.DarkBlue; + textCell2.Paragraphs.Add(tf2); + + // Add the completed table to the page + page.Paragraphs.Add(table); + + // Save the PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"PDF saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/render-table-on-new-page.cs b/working-with-tables/render-table-on-new-page.cs new file mode 100644 index 00000000..82d5df0c --- /dev/null +++ b/working-with-tables/render-table-on-new-page.cs @@ -0,0 +1,52 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class RenderTableOnNewPage +{ + static void Main() + { + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a new blank page (1‑based indexing) + Page page = doc.Pages.Add(); + + // Create a table instance + Table table = new Table(); + + // Define three equal column widths (in points) + table.ColumnWidths = "150 150 150"; + + // ----- First row (header) ----- + Row headerRow = table.Rows.Add(); + headerRow.Cells.Add("Header 1"); + headerRow.Cells.Add("Header 2"); + headerRow.Cells.Add("Header 3"); + + // ----- Second row (data) ----- + Row dataRow = table.Rows.Add(); + dataRow.Cells.Add("Cell A1"); + dataRow.Cells.Add("Cell A2"); + dataRow.Cells.Add("Cell A3"); + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + string outputPath = "RenderedTable.pdf"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + // On macOS/Linux Aspose.Pdf may require libgdiplus for saving. + // Either install libgdiplus or skip saving to avoid a crash. + Console.WriteLine("Skipping doc.Save(): libgdiplus is required on this platform to save PDFs."); + } + } + } +} diff --git a/working-with-tables/reorder-pdf-table-columns.cs b/working-with-tables/reorder-pdf-table-columns.cs new file mode 100644 index 00000000..7d0bf7d9 --- /dev/null +++ b/working-with-tables/reorder-pdf-table-columns.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + // Define the desired column order (zero‑based indices). + // Example: move column 3 to first, then column 1, then column 2, etc. + static readonly int[] DesiredColumnOrder = new int[] { 2, 0, 1 }; + + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "reordered.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document. + using (Document doc = new Document(inputPath)) + { + // Locate tables on the first page (adjust page index as needed). + TableAbsorber absorber = new TableAbsorber(); + absorber.Visit(doc.Pages[1]); + + if (absorber.TableList.Count == 0) + { + Console.WriteLine("No tables found on the page."); + doc.Save(outputPath); // Save unchanged document. + return; + } + + // Work with the first detected table. + AbsorbedTable oldTable = absorber.TableList[0]; + Page page = doc.Pages[oldTable.PageNum]; + + // Create a new table that will hold the reordered columns. + Table newTable = new Table(); + + // Optional: preserve original column widths if known. + // newTable.ColumnWidths = "100 100 100"; // adjust as required. + + // Reorder cells for each row. + foreach (AbsorbedRow oldRow in oldTable.RowList) + { + // Add a new row to the new table. + Row newRow = newTable.Rows.Add(); + + // Add cells in the desired order. + foreach (int colIndex in DesiredColumnOrder) + { + // Guard against out‑of‑range indices. + if (colIndex < 0 || colIndex >= oldRow.CellList.Count) + continue; + + var oldCell = oldRow.CellList[colIndex]; + + // Concatenate all text fragments inside the cell. + string cellText = string.Empty; + foreach (TextFragment tf in oldCell.TextFragments) + cellText += tf.Text; + + // Add the cell content to the new row. + newRow.Cells.Add(cellText); + } + } + + // Replace the original table with the reordered one. + absorber.Replace(page, oldTable, newTable); + + // Save the modified document. + doc.Save(outputPath); + } + + Console.WriteLine($"Reordered table saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/repeat-header-column-row-in-pdf-table.cs b/working-with-tables/repeat-header-column-row-in-pdf-table.cs new file mode 100644 index 00000000..9b79af75 --- /dev/null +++ b/working-with-tables/repeat-header-column-row-in-pdf-table.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Drawing; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; // existing PDF (can be empty) + const string outputPath = "output_with_table.pdf"; + + // Ensure the input file exists; if not, create a blank PDF to host the table + if (!File.Exists(inputPath)) + { + using (Document blank = new Document()) + { + blank.Pages.Add(); + blank.Save(inputPath); + } + } + + // Open the document, add a table with a header column that repeats on each page + using (Document doc = new Document(inputPath)) + { + // Create a new page if the document has none + Page page = doc.Pages.Count > 0 ? doc.Pages[1] : doc.Pages.Add(); + + // Create a table + Table table = new Table + { + // Define column widths (example: two columns) + ColumnWidths = "100 300", + // Mark the first column as a repeating header column + RepeatingColumnsCount = 1, + // Optionally repeat the first row (header row) on each new page + RepeatingRowsCount = 1, + // Add some styling (optional) + // The BorderInfo constructor overload without a Color argument is used to avoid the missing Aspose.Pdf.Drawing.Color type. + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Header row (will be repeated because RepeatingRowsCount = 1) + Row headerRow = table.Rows.Add(); + // First cell – column header (will repeat because RepeatingColumnsCount = 1) + Cell headerCell1 = headerRow.Cells.Add("Header Column"); + headerCell1.DefaultCellTextState = new TextState { FontSize = 12, FontStyle = FontStyles.Bold }; + // Second cell – regular header for the row + Cell headerCell2 = headerRow.Cells.Add("Header Row"); + headerCell2.DefaultCellTextState = new TextState { FontSize = 12, FontStyle = FontStyles.Bold }; + + // Add multiple data rows to force pagination + for (int i = 1; i <= 100; i++) + { + Row dataRow = table.Rows.Add(); + // First column – will repeat on each new page + dataRow.Cells.Add($"Item {i}"); + // Second column – regular data + dataRow.Cells.Add($"Value {i}"); + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the modified PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}' (non‑Windows platform)."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF could not be saved using Aspose.Pdf's default renderer."); + } + } + } + } + + // Helper to detect a missing native GDI+ library deep in the exception chain + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/replace-keyword-in-pdf-table-cells.cs b/working-with-tables/replace-keyword-in-pdf-table-cells.cs new file mode 100644 index 00000000..0aa9b177 --- /dev/null +++ b/working-with-tables/replace-keyword-in-pdf-table-cells.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string keyword = "PLACEHOLDER"; // text to search for inside cells + const string replacement = "New Value"; // text to replace the keyword with + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Create a TableAbsorber to locate tables in the document + TableAbsorber tableAbsorber = new TableAbsorber(); + + // Visit each page to collect tables + for (int i = 1; i <= doc.Pages.Count; i++) + { + tableAbsorber.Visit(doc.Pages[i]); + } + + // Iterate over all found tables + foreach (var absorbedTable in tableAbsorber.TableList) + { + // Iterate over rows in the table + foreach (var row in absorbedTable.RowList) + { + // Iterate over cells in the row + foreach (var cell in row.CellList) + { + // Iterate over text fragments inside the cell + foreach (var fragment in cell.TextFragments) + { + if (!string.IsNullOrEmpty(fragment.Text) && fragment.Text.Contains(keyword)) + { + // Replace the keyword with the new text + fragment.Text = fragment.Text.Replace(keyword, replacement); + } + } + } + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/replace-merged-table-cells.cs b/working-with-tables/replace-merged-table-cells.cs new file mode 100644 index 00000000..a4c7f25b --- /dev/null +++ b/working-with-tables/replace-merged-table-cells.cs @@ -0,0 +1,103 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (lifecycle rule) + using (Document doc = new Document(inputPath)) + { + // Assume the table to modify is on the first page + Aspose.Pdf.Page page = doc.Pages[1]; + + // Find tables on the page + TableAbsorber absorber = new TableAbsorber(); + absorber.Visit(page); + + if (absorber.TableList.Count == 0) + { + Console.WriteLine("No tables found on the page."); + doc.Save(outputPath); // still save unchanged document + return; + } + + // Work with the first detected table + AbsorbedTable oldTable = absorber.TableList[0]; + + // Determine total number of logical columns (sum of ColSpan in the first row) + int totalColumns = 0; + foreach (AbsorbedCell cell in oldTable.RowList[0].CellList) + totalColumns += cell.ColSpan; + + // Create a new table that will replace the old one + Table newTable = new Table(); + + // Simple column width distribution (equal widths) + string columnWidths = string.Empty; + for (int i = 0; i < totalColumns; i++) + columnWidths += "100 "; // 100 points per column (adjust as needed) + newTable.ColumnWidths = columnWidths.Trim(); + + // Iterate through each absorbed row and rebuild it + foreach (var absorbedRow in oldTable.RowList) + { + // Add a new row to the replacement table + Row newRow = newTable.Rows.Add(); + + // Process each cell in the absorbed row + foreach (AbsorbedCell absorbedCell in absorbedRow.CellList) + { + // If the cell spans multiple columns, split it into separate cells + if (absorbedCell.ColSpan > 1) + { + // Extract text from the original merged cell (if any) + string mergedText = string.Empty; + if (absorbedCell.TextFragments.Count > 0) + mergedText = absorbedCell.TextFragments[0].Text; + + // Create individual cells for each spanned column + for (int i = 0; i < absorbedCell.ColSpan; i++) + { + Cell splitCell = newRow.Cells.Add(); + + // Preserve the original text only in the first split cell + if (i == 0 && !string.IsNullOrEmpty(mergedText)) + splitCell.Paragraphs.Add(new TextFragment(mergedText)); + } + } + else + { + // Normal (non‑merged) cell – copy its text + Cell normalCell = newRow.Cells.Add(); + + if (absorbedCell.TextFragments.Count > 0) + { + string cellText = absorbedCell.TextFragments[0].Text; + normalCell.Paragraphs.Add(new TextFragment(cellText)); + } + } + } + } + + // Replace the old table with the newly built one (replace‑table rule) + absorber.Replace(page, oldTable, newTable); + + // Save the modified document (lifecycle rule) + doc.Save(outputPath); + } + + Console.WriteLine($"Document saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/replace-table-in-pdf.cs b/working-with-tables/replace-table-in-pdf.cs new file mode 100644 index 00000000..da3de4e2 --- /dev/null +++ b/working-with-tables/replace-table-in-pdf.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // TableAbsorber resides here +using Aspose.Pdf.Drawing; // For Rectangle if needed + +class ReplaceTableExample +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Assume we work with the first page (1‑based indexing) + Page page = doc.Pages[1]; + + // Find all tables on the page + TableAbsorber absorber = new TableAbsorber(); + absorber.Visit(page); + + // If no tables were found, nothing to replace + if (absorber.TableList.Count == 0) + { + Console.WriteLine("No tables found on the page."); + doc.Save(outputPath); + return; + } + + // Take the first absorbed table as the one to replace + AbsorbedTable oldTable = absorber.TableList[0]; + + // Create a new Table that will occupy the same rectangle + Table newTable = new Table(); + + // Preserve the original position + // AbsorbedTable.Rectangle provides LLX, LLY, URX, URY (double) + Aspose.Pdf.Rectangle rect = oldTable.Rectangle; + newTable.Left = (float)rect.LLX; // cast double -> float + newTable.Top = (float)rect.URY; // cast double -> float + + // Example: define a simple 2×2 table with some content + newTable.ColumnWidths = "100 100"; // two columns, 100 points each + + // Row 1 + newTable.Rows.Add(new Row()); + newTable.Rows[0].Cells.Add(new Cell { Paragraphs = { new TextFragment("New Cell 1") } }); + newTable.Rows[0].Cells.Add(new Cell { Paragraphs = { new TextFragment("New Cell 2") } }); + + // Row 2 + newTable.Rows.Add(new Row()); + newTable.Rows[1].Cells.Add(new Cell { Paragraphs = { new TextFragment("New Cell 3") } }); + newTable.Rows[1].Cells.Add(new Cell { Paragraphs = { new TextFragment("New Cell 4") } }); + + // Replace the absorbed table with the new Table. + // This method updates the internal TableList collection automatically. + absorber.Replace(page, oldTable, newTable); + + // Save the modified document + doc.Save(outputPath); + } + + Console.WriteLine($"Table replaced and saved to '{outputPath}'."); + } +} diff --git a/working-with-tables/right-align-table-in-pdf.cs b/working-with-tables/right-align-table-in-pdf.cs new file mode 100644 index 00000000..48259b1a --- /dev/null +++ b/working-with-tables/right-align-table-in-pdf.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "right_aligned_table.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (using rule: document-disposal-with-using) + using (Document doc = new Document(inputPath)) + { + // Get the first page where the table will be placed + Page page = doc.Pages[1]; + + // Create a new table (default constructor) + Table table = new Table(); + + // Define two columns with equal widths – ColumnWidths is a string, not a collection + table.ColumnWidths = "200 200"; + + // Add a header row + Row header = table.Rows.Add(); + AddCell(header, "Header 1"); + AddCell(header, "Header 2"); + + // Add a data row + Row data = table.Rows.Add(); + AddCell(data, "Value 1"); + AddCell(data, "Value 2"); + + // Align the table to the right margin + table.HorizontalAlignment = HorizontalAlignment.Right; + + // Adjust the left margin (distance from the left page edge) + // Since the table is right‑aligned, setting Left shifts it leftwards. + // Here we set a 30‑point left margin as an example. + table.Left = 30; + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the modified PDF (using rule: document-disposal-with-using) + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + + // Helper method to add a text cell to a row + private static void AddCell(Row row, string text) + { + Cell cell = new Cell(); + cell.Paragraphs.Add(new TextFragment(text)); + row.Cells.Add(cell); + } +} diff --git a/working-with-tables/rotate-table-90-degrees.cs b/working-with-tables/rotate-table-90-degrees.cs new file mode 100644 index 00000000..c9e8b00a --- /dev/null +++ b/working-with-tables/rotate-table-90-degrees.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Operators; // GSave, GRestore, ConcatenateMatrix +using Aspose.Pdf.Text; // for TextState if needed + +class Program +{ + static void Main() + { + const string outputPath = "rotated_table.pdf"; + + // Create a new PDF document and add a page + using (Document doc = new Document()) + { + Page page = doc.Pages.Add(); + + // Build a simple table + Table table = new Table + { + ColumnWidths = "100 100 100", // three columns, each 100 points wide + // Use Aspose.Pdf.Color to avoid System.Drawing dependency on non‑Windows platforms + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Aspose.Pdf.Color.Black), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Add header row + Row header = table.Rows.Add(); + header.Cells.Add("Header 1"); + header.Cells.Add("Header 2"); + header.Cells.Add("Header 3"); + + // Add a few data rows + for (int i = 1; i <= 5; i++) + { + Row row = table.Rows.Add(); + row.Cells.Add($"R{i}C1"); + row.Cells.Add($"R{i}C2"); + row.Cells.Add($"R{i}C3"); + } + + // Create a rotation matrix for 90 degrees (π/2 radians) + // For a 90° rotation about the origin the matrix is: + // [ 0 1 -1 0 0 0 ] + // (a, b, c, d, e, f) = (0, 1, -1, 0, 0, 0) + var rotationMatrix = new ConcatenateMatrix(0, 1, -1, 0, 0, 0); + + // Apply the transformation only to the table: + // Save graphics state, apply rotation, add the table, then restore state. + page.Contents.Add(new GSave()); // Save current graphics state + page.Contents.Add(rotationMatrix); // Apply 90° rotation + page.Paragraphs.Add(table); // Table will be rendered with the rotation applied + page.Contents.Add(new GRestore()); // Restore graphics state + + // Save the document – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF with rotated table saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF with rotated table saved to '{outputPath}'. (non‑Windows platform, libgdiplus must be present)"); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. The PDF could not be saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/serialize-table-to-xml.cs b/working-with-tables/serialize-table-to-xml.cs new file mode 100644 index 00000000..444dffd8 --- /dev/null +++ b/working-with-tables/serialize-table-to-xml.cs @@ -0,0 +1,102 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Drawing; // for BorderInfo and Color + +class SerializeTableToXml +{ + static void Main() + { + // Paths for the output PDF (optional) and XML files + const string pdfPath = "table.pdf"; + const string xmlPath = "table.xml"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and set basic properties + Table table = new Table + { + // Example: set table border and alignment + Border = new BorderInfo(BorderSide.All, 1f, Color.Black), // Aspose.Pdf.Drawing.Color, no System.Drawing dependency + Alignment = HorizontalAlignment.Center + }; + + // Define column widths (optional) + table.ColumnWidths = "100 150 200"; + + // Add header row + Row header = table.Rows.Add(); + header.Cells.Add(new TextFragment("ID")); + header.Cells.Add(new TextFragment("Name")); + header.Cells.Add(new TextFragment("Quantity")); + + // Add a few data rows + for (int i = 1; i <= 3; i++) + { + Row row = table.Rows.Add(); + row.Cells.Add(new TextFragment(i.ToString())); + row.Cells.Add(new TextFragment($"Item {i}")); + row.Cells.Add(new TextFragment((i * 10).ToString())); + } + + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // OPTIONAL: Save the PDF for visual verification (guarded for non‑Windows platforms) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(pdfPath); + } + else + { + try + { + doc.Save(pdfPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF save skipped."); + } + } + + // Save the document structure as XML using XmlSaveOptions (also guarded) + XmlSaveOptions xmlOptions = new XmlSaveOptions(); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(xmlPath, xmlOptions); + } + else + { + try + { + doc.Save(xmlPath, xmlOptions); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. XML save skipped."); + } + } + } + + Console.WriteLine($"Table saved as PDF: {pdfPath}"); + Console.WriteLine($"Document XML representation saved as: {xmlPath}"); + } + + // Helper method to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/set-cell-background-color-in-pdf-table.cs b/working-with-tables/set-cell-background-color-in-pdf-table.cs new file mode 100644 index 00000000..6ac8ef11 --- /dev/null +++ b/working-with-tables/set-cell-background-color-in-pdf-table.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string outputPath = "table_with_colored_cell.pdf"; + + // Create a new PDF document and ensure proper disposal + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table, define column widths and optional border + Table table = new Table + { + ColumnWidths = "100 100 100", + Border = new BorderInfo(BorderSide.All, 0.5f) + }; + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // Add a row to the table + Row row = table.Rows.Add(); + + // Add a cell to the row with some text + Cell cell = row.Cells.Add("Cell with background"); + + // Set the background color of the cell using Aspose.Pdf.Color + cell.BackgroundColor = Aspose.Pdf.Color.LightGray; + + // Save the PDF document – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. " + + "The PDF was generated in memory but could not be saved to disk."); + } + } + } + } + + // Helper method that walks the inner‑exception chain looking for a DllNotFoundException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/set-cell-vertical-alignment-middle.cs b/working-with-tables/set-cell-vertical-alignment-middle.cs new file mode 100644 index 00000000..284a8d54 --- /dev/null +++ b/working-with-tables/set-cell-vertical-alignment-middle.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "CellVerticalAlignment.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a blank page (page indexing is 1‑based) + Page page = doc.Pages.Add(); + + // Create a table with a single column + Table table = new Table { ColumnWidths = "200" }; // width of the column in points + + // Add a row to the table + Row row = table.Rows.Add(); + + // Create a cell, add some text, and set vertical alignment to middle (center) + Cell cell = new Cell(); + cell.Paragraphs.Add(new TextFragment("Centered Text")); + cell.VerticalAlignment = VerticalAlignment.Center; // Middle alignment + + // Add the cell to the row + row.Cells.Add(cell); + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + SaveDocument(doc, outputPath); + } + } + + private static void SaveDocument(Document doc, string path) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(path); + Console.WriteLine($"PDF saved to '{path}'."); + } + else + { + try + { + doc.Save(path); + Console.WriteLine($"PDF saved to '{path}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF not saved."); + } + } + } + + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/set-custom-cell-margins-in-pdf-table.cs b/working-with-tables/set-custom-cell-margins-in-pdf-table.cs new file mode 100644 index 00000000..73205079 --- /dev/null +++ b/working-with-tables/set-custom-cell-margins-in-pdf-table.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "table_with_margins.pdf"; + + // Create a new PDF document and ensure proper disposal + using (Document doc = new Document()) + { + // Add a blank page to the document + Page page = doc.Pages.Add(); + + // Create a table; optionally set default cell padding + Table table = new Table + { + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) // left, bottom, right, top + }; + + // Add a row to the table + Row row = table.Rows.Add(); + + // Add a cell with some text + Cell cell = row.Cells.Add("Cell with custom margins"); + + // Configure custom margins for this cell using MarginInfo + MarginInfo cellMargin = new MarginInfo + { + Left = 10, // points from the left edge of the cell + Right = 10, // points from the right edge + Top = 5, // points from the top edge + Bottom = 5 // points from the bottom edge + }; + cell.Margin = cellMargin; + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF. Guard against missing GDI+ on non‑Windows platforms. + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || + RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + try + { + doc.Save(outputPath); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("libgdiplus is required for PDF creation on this platform. Save skipped."); + } + } + else + { + doc.Save(outputPath); + } + } + + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/set-custom-row-height-in-pdf-table.cs b/working-with-tables/set-custom-row-height-in-pdf-table.cs new file mode 100644 index 00000000..ece1b6a4 --- /dev/null +++ b/working-with-tables/set-custom-row-height-in-pdf-table.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Drawing; + +class Program +{ + static void Main() + { + const string outputPath = "table_row_height.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table with three columns + Table table = new Table + { + ColumnWidths = "100 100 100", // widths in points + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // First row – default height + Row row0 = table.Rows.Add(); + row0.Cells.Add("Cell 1"); + row0.Cells.Add("Cell 2"); + row0.Cells.Add("Cell 3"); + + // Second row – custom fixed height (e.g., 50 points) + Row row1 = table.Rows.Add(); + row1.FixedRowHeight = 50; // set custom row height + row1.Cells.Add("Tall Cell 1"); + row1.Cells.Add("Tall Cell 2"); + row1.Cells.Add("Tall Cell 3"); + + // Third row – default height + Row row2 = table.Rows.Add(); + row2.Cells.Add("Cell 4"); + row2.Cells.Add("Cell 5"); + row2.Cells.Add("Cell 6"); + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the document (guarded for non‑Windows platforms where GDI+ may be missing) + if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + Console.WriteLine("Skipping save on non‑Windows platform (GDI+ not available)."); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-default-cell-padding-for-pdf-table.cs b/working-with-tables/set-default-cell-padding-for-pdf-table.cs new file mode 100644 index 00000000..67958ba9 --- /dev/null +++ b/working-with-tables/set-default-cell-padding-for-pdf-table.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; // optional, kept for completeness + +class Program +{ + static void Main() + { + const string outputPath = "table_with_padding.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a blank page + Page page = doc.Pages.Add(); + + // Create a table with 3 columns and 4 rows and set default cell padding + Table table = new Table + { + ColumnWidths = "100 100 100", + DefaultCellPadding = new MarginInfo + { + Left = 5, + Right = 5, + Top = 5, + Bottom = 5 + } + }; + + // Populate the table with sample data + for (int r = 0; r < 4; r++) + { + Row row = table.Rows.Add(); + for (int c = 0; c < 3; c++) + { + Cell cell = row.Cells.Add($"R{r + 1}C{c + 1}"); + // Optional: set a border to visualize the padding + cell.Border = new BorderInfo(BorderSide.All, 0.5f); + } + } + + // Add the table to the page + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (libgdiplus) inside TypeInitializationException + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/set-fixed-row-height-table-rows.cs b/working-with-tables/set-fixed-row-height-table-rows.cs new file mode 100644 index 00000000..ac2eb75a --- /dev/null +++ b/working-with-tables/set-fixed-row-height-table-rows.cs @@ -0,0 +1,91 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "table_fixed_row_height.pdf"; + + // Create a new PDF document inside a using block for deterministic disposal + using (Document doc = new Document()) + { + // Add a page (pages are 1‑based) + Page page = doc.Pages.Add(); + + // Create a table and set its position on the page + Table table = new Table + { + // Example: set left and top coordinates + Left = 50, + Top = 700, + // Define column widths (space‑separated values) + ColumnWidths = "100 150 100" + }; + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Define a fixed row height (in points) + const double fixedHeight = 30.0; + + // Add rows and set the FixedRowHeight before populating cells + for (int i = 0; i < 5; i++) + { + // Create a new row + Row row = table.Rows.Add(); + + // Apply the fixed height to this row + row.FixedRowHeight = fixedHeight; + + // Add three cells to the row and fill them with text + for (int col = 0; col < 3; col++) + { + // Create a text fragment for the cell content + TextFragment tf = new TextFragment($"R{i + 1}C{col + 1}") + { + // Optional styling + TextState = { FontSize = 12, ForegroundColor = Aspose.Pdf.Color.Black } + }; + + // Add the cell with the text fragment + row.Cells.Add(tf); + } + } + + // Save the document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) is not available on this platform; PDF saved without rendering the table."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-tables/set-maximum-column-width-for-pdf-table.cs b/working-with-tables/set-maximum-column-width-for-pdf-table.cs new file mode 100644 index 00000000..d6ac44d0 --- /dev/null +++ b/working-with-tables/set-maximum-column-width-for-pdf-table.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_with_table.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing PDF document + using (Document doc = new Document(inputPath)) + { + // Ensure there is at least one page to add the table to + Page page = doc.Pages.Count > 0 ? doc.Pages[1] : doc.Pages.Add(); + + // Create a table and configure column width limits (150 points per column) + Table table = new Table + { + // Set a fixed width for each column; values are space‑separated + ColumnWidths = "150 150 150", + // Prevent automatic adjustment that could expand columns beyond the specified widths + ColumnAdjustment = ColumnAdjustment.Customized, + // Optional: set a default column width for any additional columns + DefaultColumnWidth = "150", + // Add a simple border for visual clarity (order: side, width, color) + Border = new BorderInfo(BorderSide.All, 1.0f, Aspose.Pdf.Color.Black) + }; + + // Add a header row + Row header = table.Rows.Add(); + header.BackgroundColor = Aspose.Pdf.Color.LightGray; + header.Cells.Add("Header 1"); + header.Cells.Add("Header 2"); + header.Cells.Add("Header 3"); + + // Add a few data rows + for (int i = 1; i <= 5; i++) + { + Row row = table.Rows.Add(); + row.Cells.Add($"Row {i} Col 1"); + row.Cells.Add($"Row {i} Col 2"); + row.Cells.Add($"Row {i} Col 3"); + } + + // Position the table on the page (optional) + table.Margin = new MarginInfo { Top = 20, Left = 20 }; + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the document – guard against missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"Document saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"Document saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) is not available on this platform; PDF saved without rendering dependent features."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception ex) + { + Exception? current = ex; + while (current != null) + { + if (current is DllNotFoundException) + return true; + current = current.InnerException; + } + return false; + } +} diff --git a/working-with-tables/set-minimum-column-width-for-pdf-table.cs b/working-with-tables/set-minimum-column-width-for-pdf-table.cs new file mode 100644 index 00000000..b9eab221 --- /dev/null +++ b/working-with-tables/set-minimum-column-width-for-pdf-table.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // for TextFragment +using Aspose.Pdf.LogicalStructure; // not required for core Table, but kept for completeness + +class Program +{ + static void Main() + { + // Input and output PDF paths + const string inputPath = "input.pdf"; + const string outputPath = "output_mincolwidth.pdf"; + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing PDF document + using (Document doc = new Document(inputPath)) + { + // Create a new table and set a minimum column width (in points) + Table table = new Table + { + // DefaultColumnWidth is applied to any column that does not have an explicit width. + // Setting it to 50 points ensures no column becomes narrower than 50 points. + DefaultColumnWidth = "50" + }; + + // Optionally define explicit widths for each column. + // The widths are space‑separated; here we define three columns. + table.ColumnWidths = "50 70 90"; + + // Add a header row + Row header = table.Rows.Add(); + header.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 1") } }); + header.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 2") } }); + header.Cells.Add(new Cell { Paragraphs = { new TextFragment("Header 3") } }); + + // Add a data row + Row data = table.Rows.Add(); + data.Cells.Add(new Cell { Paragraphs = { new TextFragment("Data A") } }); + data.Cells.Add(new Cell { Paragraphs = { new TextFragment("Data B") } }); + data.Cells.Add(new Cell { Paragraphs = { new TextFragment("Data C") } }); + + // Insert the table into the first page of the document + Page firstPage = doc.Pages[1]; // 1‑based indexing + firstPage.Paragraphs.Add(table); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved with minimum column width to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-tables/set-table-width-80-percent.cs b/working-with-tables/set-table-width-80-percent.cs new file mode 100644 index 00000000..2a2fb418 --- /dev/null +++ b/working-with-tables/set-table-width-80-percent.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and set its width to 80% of the page width + Table table = new Table + { + // Use ColumnWidths with a percentage value to define the table width + ColumnWidths = "80%", + // Center the table on the page for better appearance + Alignment = HorizontalAlignment.Center + }; + + // Add a row with a single cell + Row row = table.Rows.Add(); + row.Cells.Add("Sample cell content"); + + // Add the table to the page's paragraphs collection + page.Paragraphs.Add(table); + + // Save the PDF to a file – guard the call on non‑Windows platforms where libgdiplus may be missing + string outputPath = "TableWidth80Percent.pdf"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + Console.WriteLine("Skipping Document.Save on non‑Windows platform because libgdiplus (GDI+) is required."); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-table-zindex-in-pdf.cs b/working-with-tables/set-table-zindex-in-pdf.cs new file mode 100644 index 00000000..72340bd2 --- /dev/null +++ b/working-with-tables/set-table-zindex-in-pdf.cs @@ -0,0 +1,91 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Drawing; + +class Program +{ + static void Main() + { + const string outputPath = "table_zindex.pdf"; + + // Create a new PDF document inside a using block for proper disposal + using (Document doc = new Document()) + { + // Add a blank page (1‑based indexing) + Page page = doc.Pages.Add(); + + // Create a table (inherits BaseParagraph, thus has ZIndex) + Table table = new Table + { + // Position the table on the page + Left = 50, + Top = 500, + + // Set ZIndex – higher value means the table will be drawn over + // other page elements with lower ZIndex. Negative values place it + // behind text. + ZIndex = 10, + + // Optional visual settings + Border = new BorderInfo(BorderSide.All, 1f, Color.Black), + DefaultCellBorder = new BorderInfo(BorderSide.All, 0.5f, Color.Gray), + DefaultCellPadding = new MarginInfo(5, 5, 5, 5) + }; + + // Define column widths (optional) + table.ColumnWidths = "100 150 100"; + + // Add a header row + Row header = table.Rows.Add(); + header.Cells.Add("ID"); + header.Cells.Add("Name"); + header.Cells.Add("Quantity"); + + // Add a few data rows + for (int i = 1; i <= 5; i++) + { + Row row = table.Rows.Add(); + row.Cells.Add(i.ToString()); + row.Cells.Add($"Item {i}"); + row.Cells.Add((i * 10).ToString()); + } + + // Add the table to the page's paragraph collection + page.Paragraphs.Add(table); + + // Save the PDF – guard against missing GDI+ (libgdiplus) on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'. (non‑Windows platform)"); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Warning: GDI+ (libgdiplus) is not available on this platform. PDF was not saved."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (e.g., missing libgdiplus) + private static bool ContainsDllNotFound(Exception? ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} diff --git a/working-with-tables/style-table-header-row-pdf.cs b/working-with-tables/style-table-header-row-pdf.cs new file mode 100644 index 00000000..cdc0ad1e --- /dev/null +++ b/working-with-tables/style-table-header-row-pdf.cs @@ -0,0 +1,92 @@ +using System; +using System.Runtime.InteropServices; +using Aspose.Pdf; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string outputPath = "styled_table.pdf"; + + // Create a new PDF document + using (Document doc = new Document()) + { + // Add a page to the document + Page page = doc.Pages.Add(); + + // Create a table and add it to the page + Table table = new Table + { + // Define three column widths (adjust as needed) + ColumnWidths = "100 150 150" + }; + page.Paragraphs.Add(table); + + // ----- Header row with distinct style ----- + Row headerRow = new Row + { + // Background color for the header row + BackgroundColor = Aspose.Pdf.Color.LightGray + }; + + // Set default text state for header cells (bold font) + headerRow.DefaultCellTextState = new TextState + { + Font = FontRepository.FindFont("Helvetica"), + FontSize = 12, + FontStyle = FontStyles.Bold, + ForegroundColor = Aspose.Pdf.Color.Black + }; + + // Add header cells + headerRow.Cells.Add("Product"); + headerRow.Cells.Add("Quantity"); + headerRow.Cells.Add("Price"); + + // Append the styled header row to the table + table.Rows.Add(headerRow); + + // ----- Data rows (regular style) ----- + for (int i = 0; i < 5; i++) + { + Row dataRow = new Row(); + dataRow.Cells.Add($"Item {i + 1}"); + dataRow.Cells.Add((10 + i).ToString()); + dataRow.Cells.Add($"${(20 + i * 5):0.00}"); + table.Rows.Add(dataRow); + } + + // Save the PDF; handle missing GDI+ on non‑Windows platforms + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + else + { + try + { + doc.Save(outputPath); + Console.WriteLine($"PDF saved to '{outputPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("GDI+ (libgdiplus) not available; PDF could not be saved on this platform."); + } + } + } + } + + // Helper method to detect a nested DllNotFoundException + static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file