cancel
Showing results for 
Search instead for 
Did you mean: 
Reply

get x and y coordinates on the basis of text in pdf using power automate desktop

Hi,

is it possible to find particular text and get x and y coordinates for that text

already help is provided by @Deenuji very thankful for him

Like - 

neerajpokh_0-1710183015630.png

 

 

want to find x and y coordinates for that highlighted text in pdf.

Please help

Thanks

Neeraj

14 REPLIES 14
Deenuji
Community Champion
Community Champion

@neerajpokh 

Thanks for creating new topic.

Here you go for the requested code.

 

Input Parameters variables:

  1. FilePath
  2. Text to Search

Output Parameters variables:

  1. Text found at page Number
  2. X coordinate 
  3. Y coordinate

You can utilize the same ITextsharp dll version for the use case and add one more reference in .Net script reference textbox:

Deenuji_0-1710232387391.png

Code[Copy and paste the below code into your PAD designer]

 

SET InputFilePath TO $'''C:\\Users\\Documents\\PAD_Document.pdf'''
SET Search_Text TO $'''add text and image to existing pdf in power automate desktop'''
SET Text_Found_At_PageNo TO $'''%''%'''
SET Result_X TO $'''%''%'''
SET Result_Y TO $'''%''%'''
Scripting.RunDotNetScript Imports: $'''iTextSharp.text
iTextSharp.text.pdf
iTextSharp.text.pdf.parser''' Language: System.DotNetActionLanguageType.CSharp ReferenceRootPath: $'''C:\\Deenu\\Assemblies''' Script: $'''using (PdfReader reader = new PdfReader(filePath))
{
    for (int pageNum = 1; pageNum <= reader.NumberOfPages; pageNum++)
    {
        // Extract text with coordinates using the custom strategy
        string text = PdfTextExtractor.GetTextFromPage(reader, pageNum);

        // Split the extracted text into lines
        string[] lines = text.Split(\'\\n\');

        // Loop through each line of text
        foreach (string line in lines)
        {
            // Check if the search text is found in the current line
            if (line.Contains(searchText))
            {
                // Output page number and coordinates of the found text
                StrPageNum =Convert.ToString(pageNum);
                Str_Cordinates_X = Convert.ToString(reader.GetPageSize(pageNum).Width / 2);
                Str_Cordinates_Y = Convert.ToString(reader.GetPageSize(pageNum).Top - reader.GetPageSize(pageNum).Bottom);
                
                break; // Exit the loop after finding the text
            }
        }
    }
}''' @'name:filePath': InputFilePath @'type:filePath': $'''String''' @'direction:filePath': $'''In''' @'name:searchText': Search_Text @'type:searchText': $'''String''' @'direction:searchText': $'''In''' @'name:StrPageNum': $'''''' @'type:StrPageNum': $'''String''' @'direction:StrPageNum': $'''Out''' @'name:Str_Cordinates_X': $'''''' @'type:Str_Cordinates_X': $'''String''' @'direction:Str_Cordinates_X': $'''Out''' @'name:Str_Cordinates_Y': $'''''' @'type:Str_Cordinates_Y': $'''String''' @'direction:Str_Cordinates_Y': $'''Out''' @StrPageNum=> Text_Found_At_PageNo @Str_Cordinates_X=> Result_X @Str_Cordinates_Y=> Result_Y

 

 
Thanks,
Deenuji Loganathan
🤖Automation Evangelist
Deenuji - Follow me on LinkedIn

-------------------------------------------------------------------------------------------------------------
If I've helped solve your query, kindly mark my response as the solution ✔ and give it a thumbs up!👍 Your feedback supports future seekers 🌟

Hi @Deenuji 

 

Split(\'\\n\');

 

is throwing error

@neerajpokh 

Share some screenshot pls? you are copy and pasted the same code in your PAD flow?

 

Hi @Deenuji 

ran it in visual studio first

Hi @Deenuji 

here is my code

requirement is to get text position and add image there

using (var reader = new PdfReader("C:\\New folder\\New folder\\Altagas.pdf"))
{

using (var stamper = new PdfStamper(reader, new FileStream("C:\\New folder\\output.pdf", FileMode.Create)))
{
var count = reader.NumberOfPages;
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfContentByte content = stamper.GetOverContent(i);
iTextSharp.text.pdf.PdfDocument doc = new iTextSharp.text.pdf.PdfDocument();
if (i == 1)
{
//add text
content.BeginText();
iTextSharp.text.Rectangle pagesize = reader.GetPageSize(1);
float x = pagesize.Left + 200;
float y = pagesize.Top - 40;
content.SetFontAndSize(BaseFont.CreateFont(), 12);
content.ShowTextAligned(0, "Hello how are you?", x, y, 0);
content.EndText();
}

// Add image
if (count == i)
{
iTextSharp.text.Rectangle pagesize = reader.GetPageSize(i);
//float x = pagesize.Left + 100;
//float y = pagesize.Top - 680;
var Str_Cordinates_X = "";
var Str_Cordinates_Y = "";
var textfound=false;
float x = 0;
float y = 0;
string text = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i);
string[] lines = text.Split(\'\\n\');
foreach (string line in lines)
{
// Check if the search text is found in the current line
if (line.Contains("Confirmed on the date first above written:"))
{
// Output page number and coordinates of the found text
var StrPageNum = Convert.ToString(i);
Str_Cordinates_X = Convert.ToString(reader.GetPageSize(i).Width / 2);
Str_Cordinates_Y = Convert.ToString(reader.GetPageSize(i).Top - reader.GetPageSize(i).Bottom);
textfound = true;
}
if (textfound == true)
{
break;
}
//break;
}
//Str_Cordinates_X= float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
x = float.Parse(Str_Cordinates_X, CultureInfo.InvariantCulture.NumberFormat);
y=float.Parse(Str_Cordinates_Y, CultureInfo.InvariantCulture.NumberFormat);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("C:\\New folder\\New folder\\Kirby Linzmeyer.png");
//image.SetAbsolutePosition(100, 100); // Set position
//object result=stamper.fin
//content.ShowTextKerned("on the date first above written:");
image.SetAbsolutePosition(x, pagesize.Top - 680);
content.AddImage(image);
}
}
}
}

Deenuji
Community Champion
Community Champion

@neerajpokh 

Please first try the code for what you asked then talk about your integration issue please.

However, please find the updated code for your use case(Insert text and image + Get X and Y coordinates for given text).

Code: 

 

using (var reader = new PdfReader("C:\\Users\\Documents\\Loading.pdf"))
{

using (var stamper = new PdfStamper(reader, new FileStream("C:\\Deenu\\RPA.pdf", FileMode.Create)))
{
var count = reader.NumberOfPages;
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfContentByte content = stamper.GetOverContent(i);
iTextSharp.text.pdf.PdfDocument doc = new iTextSharp.text.pdf.PdfDocument();
if (i == 1)
{
//add text
content.BeginText();
iTextSharp.text.Rectangle pagesize = reader.GetPageSize(1);
float x = pagesize.Left + 200;
float y = pagesize.Top - 40;
content.SetFontAndSize(BaseFont.CreateFont(), 12);
content.ShowTextAligned(0, "Contents", x, y, 0);
content.EndText();
}

// Add image
if (count == i)
{
iTextSharp.text.Rectangle pagesize = reader.GetPageSize(i);
//float x = pagesize.Left + 100;
//float y = pagesize.Top - 680;
var Str_Cordinates_X = "";
var Str_Cordinates_Y = "";
var textfound = false;
float x = 0;
float y = 0;
string text = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i);
// Split the extracted text into lines
string[] lines = text.Split('\n');


foreach (string line in lines)
{
// Check if the search text is found in the current line
if (line.Contains("Loading Reference: 12345 "))
{
// Output page number and coordinates of the found text
var StrPageNum = Convert.ToString(i);
Str_Cordinates_X = Convert.ToString(reader.GetPageSize(i).Width / 2);
Str_Cordinates_Y = Convert.ToString(reader.GetPageSize(i).Top - reader.GetPageSize(i).Bottom);
textfound = true;
}
if (textfound == true)
{
break;
}
//break;
}
//Str_Cordinates_X= float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
x = float.Parse(Str_Cordinates_X, CultureInfo.InvariantCulture.NumberFormat);
y = float.Parse(Str_Cordinates_Y, CultureInfo.InvariantCulture.NumberFormat);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("C:\\Users\\Downloads\\Download BAckup\\Article1\\6.png");
//image.SetAbsolutePosition(100, 100); // Set position
//object result=stamper.fin
//content.ShowTextKerned("on the date first above written:");
image.SetAbsolutePosition(x, pagesize.Top - 680);
content.AddImage(image);
}
}
}
}

Hope you are using System.Globalization dll as well for your above code.

 


Thanks,
Deenuji Loganathan
🤖 Automation Evangelist
Deenuji - Follow me on LinkedIn

-------------------------------------------------------------------------------------------------------------
If I've helped solve your query, kindly mark my response as the solution ✔ and give it a thumbs up!👍 Your feedback supports future seekers 🌟

 

Hi @Deenuji 

in that case from above code, x and y coordinates values are same for pdfs 

like some has more bottom space and some has less but x and y are coming  same

Hello @neerajpokh,

 

Could you please elaborate your issue with some example and screenshot please?

Hi @Deenuji 

i have multiple pdfs are available and need to insert image in different pdf

 

neerajpokh_0-1710265517444.png

 

screenshot above has more space in bottom

 

neerajpokh_1-1710265594484.png

and here we have less space in bottom

so want to find text and get corresponding x and y coordinates so can insert image in correct place

 

hope you understand

@neerajpokh 

So, with respect to which text input are you aiming to obtain the X and Y coordinates in the above attached pdf like last title? If feasible, could you share a PDF with me via private message? Please provide screenshots highlighting the specific text you are looking to obtain X and Y values from, as well as indicating where you would like the images to be placed(Do it manually and share some screenshot for my understanding)

 

Additionally, are you inserting the same images across all PDFs, or are they different? Will the image size vary, or is it fixed?

 

 

hi @Deenuji 

i have attached files

trying to find text in last page - Confirmed on the date first above written:

and image will be shown to yellow highlighted place

 

neerajpokh_0-1710267234907.png

 

output file is attached

 

 

Deenuji
Community Champion
Community Champion

@neerajpokh 

Below attached code working fine for me in VS. So please try that in VS first and deploy to PAD and add required dll's.

Spire version:

Deenuji_0-1710353835286.png

 

 

using Spire.Additions.Xps.Schema;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Texts;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net;
using static System.Runtime.InteropServices.JavaScript.JSType;


//Create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Load a PDF file
doc.LoadFromFile("C:\\Users\\deenu\\Downloads\\dummy2.pdf");

//Load an image
PdfImage image = PdfImage.FromFile("C:\\Users\\deenu\\Downloads\\kirby_sign.png");

//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;

//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;




//Loop through all pages
foreach (PdfPageBase page in doc.Pages)
{
    //Create a PdfTextFinder object
    PdfTextFinder finder = new PdfTextFinder(page);

    //Set the find options
    PdfTextFindOptions options = new PdfTextFindOptions();
    options.Parameter = TextFindParameter.IgnoreCase;
    finder.Options = options;

    //Find all instances of a specific text
    List<PdfTextFragment> fragments = finder.Find("Confirmed on the date first above written");



    //Loop through the instances
    foreach (PdfTextFragment fragment in fragments)
    {
        //Get the position of a specific instance
        PointF found = fragment.Positions[0];
        //Draw the image at a specified location on the page
        page.Canvas.DrawImage(image, found.X+50, found.Y+100, width, height);

        //Save the result document
        doc.SaveToFile("dummy4.pdf", FileFormat.PDF);
        Console.WriteLine(found);
    }
}

 


Thanks,
Deenuji Loganathan
🤖 Automation Evangelist
Deenuji - Follow me on LinkedIn

-------------------------------------------------------------------------------------------------------------
If I've helped solve your query, kindly mark my response as the solution ✔ and give it a thumbs up!👍 Your feedback supports future seekers 🌟

 

Hi @Deenuji 

that is failing while using in PAD but works fine in VS

 

neerajpokh_0-1710398133198.png

 

Helpful resources

Announcements

Community will be READ ONLY July 16th, 5p PDT -July 22nd

Dear Community Members,   We'd like to let you know of an upcoming change to the community platform: starting July 16th, the platform will transition to a READ ONLY mode until July 22nd.   During this period, members will not be able to Kudo, Comment, or Reply to any posts.   On July 22nd, please be on the lookout for a message sent to the email address registered on your community profile. This email is crucial as it will contain your unique code and link to register for the new platform encompassing all of the communities.   What to Expect in the New Community: A more unified experience where all products, including Power Apps, Power Automate, Copilot Studio, and Power Pages, will be accessible from one community.Community Blogs that you can syndicate and link to for automatic updates. We appreciate your understanding and cooperation during this transition. Stay tuned for the exciting new features and a seamless community experience ahead!

Summer of Solutions | Week 4 Results | Winners will be posted on July 24th

We are excited to announce the Summer of Solutions Challenge!    This challenge is kicking off on Monday, June 17th and will run for (4) weeks.  The challenge is open to all Power Platform (Power Apps, Power Automate, Copilot Studio & Power Pages) community members. We invite you to participate in a quest to provide solutions to as many questions as you can. Answers can be provided in all the communities.    Entry Period: This Challenge will consist of four weekly Entry Periods as follows (each an “Entry Period”)   - 12:00 a.m. PT on June 17, 2024 – 11:59 p.m. PT on June 23, 2024 - 12:00 a.m. PT on June 24, 2024 – 11:59 p.m. PT on June 30, 2024 - 12:00 a.m. PT on July 1, 2024 – 11:59 p.m. PT on July 7, 2024 - 12:00 a.m. PT on July 8, 2024 – 11:59 p.m. PT on July 14, 2024   Entries will be eligible for the Entry Period in which they are received and will not carryover to subsequent weekly entry periods.  You must enter into each weekly Entry Period separately.   How to Enter: We invite you to participate in a quest to provide "Accepted Solutions" to as many questions as you can. Answers can be provided in all the communities. Users must provide a solution which can be an “Accepted Solution” in the Forums in all of the communities and there are no limits to the number of “Accepted Solutions” that a member can provide for entries in this challenge, but each entry must be substantially unique and different.    Winner Selection and Prizes: At the end of each week, we will list the top ten (10) Community users which will consist of: 5 Community Members & 5 Super Users and they will advance to the final drawing. We will post each week in the News & Announcements the top 10 Solution providers.  At the end of the challenge, we will add all of the top 10 weekly names and enter them into a random drawing.  Then we will randomly select ten (10) winners (5 Community Members & 5 Super Users) from among all eligible entrants received across all weekly Entry Periods to receive the prize listed below. If a winner declines, we will draw again at random for the next winner.  A user will only be able to win once overall. If they are drawn multiple times, another user will be drawn at random.  Individuals will be contacted before the announcement with the opportunity to claim or deny the prize.  Once all of the winners have been notified, we will post in the News & Announcements of each community with the list of winners.   Each winner will receive one (1) Pass to the Power Platform Conference in Las Vegas, Sep. 18-20, 2024 ($1800 value). NOTE: Prize is for conference attendance only and any other costs such as airfare, lodging, transportation, and food are the sole responsibility of the winner. Tickets are not transferable to any other party or to next year’s event.   ** PLEASE SEE THE ATTACHED RULES for this CHALLENGE**   Week 1 Results: Congratulations to the Week 1 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge.   Community MembersNumber SolutionsSuper UsersNumber Solutions Deenuji 9 @NathanAlvares24  17 @Anil_g  7 @ManishSolanki  13 @eetuRobo  5 @David_MA  10 @VishnuReddy1997  5 @SpongYe  9JhonatanOB19932 (tie) @Nived_Nambiar  8 @maltie  2 (tie)   @PA-Noob  2 (tie)   @LukeMcG  2 (tie)   @tgut03  2 (tie)       Week 2 Results: Congratulations to the Week 2 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 2: Community MembersSolutionsSuper UsersSolutionsPower Automate  @Deenuji  12@ManishSolanki 19 @Anil_g  10 @NathanAlvares24  17 @VishnuReddy1997  6 @Expiscornovus  10 @Tjan  5 @Nived_Nambiar  10 @eetuRobo  3 @SudeepGhatakNZ 8     Week 3 Results: Congratulations to the Week 3 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 3:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji32ManishSolanki55VishnuReddy199724NathanAlvares2444Anil_g22SudeepGhatakNZ40eetuRobo18Nived_Nambiar28Tjan8David_MA22   Week 4 Results: Congratulations to the Week 4 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 4:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji11FLMike31Sayan11ManishSolanki16VishnuReddy199710creativeopinion14Akshansh-Sharma3SudeepGhatakNZ7claudiovc2CFernandes5 misc2Nived_Nambiar5 Usernametwice232rzaneti5 eetuRobo2   Anil_g2   SharonS2  

Check Out | 2024 Release Wave 2 Plans for Microsoft Dynamics 365 and Microsoft Power Platform

On July 16, 2024, we published the 2024 release wave 2 plans for Microsoft Dynamics 365 and Microsoft Power Platform. These plans are a compilation of the new capabilities planned to be released between October 2024 to March 2025. This release introduces a wealth of new features designed to enhance customer understanding and improve overall user experience, showcasing our dedication to driving digital transformation for our customers and partners.    The upcoming wave is centered around utilizing advanced AI and Microsoft Copilot technologies to enhance user productivity and streamline operations across diverse business applications. These enhancements include intelligent automation, AI-powered insights, and immersive user experiences that are designed to break down barriers between data, insights, and individuals. Watch a summary of the release highlights.    Discover the latest features that empower organizations to operate more efficiently and adaptively. From AI-driven sales insights and customer service enhancements to predictive analytics in supply chain management and autonomous financial processes, the new capabilities enable businesses to proactively address challenges and capitalize on opportunities.    

Updates to Transitions in the Power Platform Communities

We're embarking on a journey to enhance your experience by transitioning to a new community platform. Our team has been diligently working to create a fresh community site, leveraging the very Dynamics 365 and Power Platform tools our community advocates for.  We started this journey with transitioning Copilot Studio forums and blogs in June. The move marks the beginning of a new chapter, and we're eager for you to be a part of it. The rest of the Power Platform product sites will be moving over this summer.   Stay tuned for more updates as we get closer to the launch. We can't wait to welcome you to our new community space, designed with you in mind. Let's connect, learn, and grow together.   Here's to new beginnings and endless possibilities!   If you have any questions, observations or concerns throughout this process please go to https://aka.ms/PPCommSupport.   To stay up to date on the latest details of this migration and other important Community updates subscribe to our News and Announcements forums: Copilot Studio, Power Apps, Power Automate, Power Pages

Users online (2,212)