We use Aspose.PDF for .NET and have a requirement to replace a text in PDF with a table (may contain upto 50 rows and few columns) . I can find a text in PDF using TextFragmentAbsorber but not finding a good way to replace that text with a table. It inserts the table on top of other content.
I have attached a document with Sample code. Please check and advise.
Hi Komal,
Thank you for looking into this. I have attached sample input and output document.
We have a requirement to replace a particular word with a table containing upto 75 rows. Table will be prepared dynamically depending upon data that we have available in the system.
In sample input pdf I have word [Table+C] and in sample output I have manually replaced that with a table. I want to achieve this programmatically.
Please let me know if you need any additional information. Thanks.
Hi Komal,
//open document<o:p></o:p>
Document pdfDocument = new Document("c:/pdftest/aspose-pdf-input.pdf");
//create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("[Table+C]");
textFragmentAbsorber.TextReplaceOptions.ReplaceAdjustmentAction =TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation;
//accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
//get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
//loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
// Initializes a new instance of the Table
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
table.Left = (float)textFragment.Rectangle.LLX;
table.Top = (float)textFragment.Rectangle.URX;
// Set the table border color as LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// set the border for table cells
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// create a loop to add 10 rows
for (int row_count = 1; row_count < 10; row_count++)
{
// add row to table
Aspose.Pdf.Row row = table.Rows.Add();
// add table cells
row.Cells.Add("Column (" + row_count + ", 1)");
row.Cells.Add("Column (" + row_count + ", 2)");
row.Cells.Add("Column (" + row_count + ", 3)");
}
// Add table object to first page of input document
pdfDocument.Pages[1].Paragraphs.Add(table);
}
pdfDocument.Save(“c:/pdftest/Text_Replace_output.pdf”);