cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
neerajpokh
Helper III
Helper III

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?

 

neerajpokh
Helper III
Helper III

Hi @Deenuji 

ran it in visual studio first

neerajpokh
Helper III
Helper III

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?

neerajpokh
Helper III
Helper III

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
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 🌟

 
neerajpokh
Helper III
Helper III

Hi @Deenuji 

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

 

neerajpokh_0-1710398133198.png

 

Helpful resources

Announcements

Celebrating the May Super User of the Month: Laurens Martens

  @LaurensM  is an exceptional contributor to the Power Platform Community. Super Users like Laurens inspire others through their example, encouragement, and active participation. We are excited to celebrated Laurens as our Super User of the Month for May 2024.   Consistent Engagement:  He consistently engages with the community by answering forum questions, sharing insights, and providing solutions. Laurens dedication helps other users find answers and overcome challenges.   Community Expertise: As a Super User, Laurens plays a crucial role in maintaining a knowledge sharing environment. Always ensuring a positive experience for everyone.   Leadership: He shares valuable insights on community growth, engagement, and future trends. Their contributions help shape the Power Platform Community.   Congratulations, Laurens Martens, for your outstanding work! Keep inspiring others and making a difference in the community!   Keep up the fantastic work!        

Check out the Copilot Studio Cookbook today!

We are excited to announce our new Copilot Cookbook Gallery in the Copilot Studio Community. We can't wait for you to share your expertise and your experience!    Join us for an amazing opportunity where you'll be one of the first to contribute to the Copilot Cookbook—your ultimate guide to mastering Microsoft Copilot. Whether you're seeking inspiration or grappling with a challenge while crafting apps, you probably already know that Copilot Cookbook is your reliable assistant, offering a wealth of tips and tricks at your fingertips--and we want you to add your expertise. What can you "cook" up?   Click this link to get started: https://aka.ms/CS_Copilot_Cookbook_Gallery   Don't miss out on this exclusive opportunity to be one of the first in the Community to share your app creation journey with Copilot. We'll be announcing a Cookbook Challenge very soon and want to make sure you one of the first "cooks" in the kitchen.   Don't miss your moment--start submitting in the Copilot Cookbook Gallery today!     Thank you,  Engagement Team

Announcing Power Apps Copilot Cookbook Gallery

We are excited to share that the all-new Copilot Cookbook Gallery for Power Apps is now available in the Power Apps Community, full of tips and tricks on how to best use Microsoft Copilot as you develop and create in Power Apps. The new Copilot Cookbook is your go-to resource when you need inspiration--or when you're stuck--and aren't sure how to best partner with Copilot while creating apps.   Whether you're looking for the best prompts or just want to know about responsible AI use, visit Copilot Cookbook for regular updates you can rely on--while also serving up some of your greatest tips and tricks for the Community. Check Out the new Copilot Cookbook for Power Apps today: Copilot Cookbook - Power Platform Community.  We can't wait to see what you "cook" up!    

Welcome to the Power Automate Community

You are now a part of a fast-growing vibrant group of peers and industry experts who are here to network, share knowledge, and even have a little fun.   Now that you are a member, you can enjoy the following resources:   Welcome to the Community   News & Announcements: The is your place to get all the latest news around community events and announcements. This is where we share with the community what is going on and how to participate.  Be sure to subscribe to this board and not miss an announcement.   Get Help with Power Automate Forums: If you're looking for support with any part of Power Automate, our forums are the place to go. From General Power Automate forums to Using Connectors, Building Flows and Using Flows.  You will find thousands of technical professionals, and Super Users with years of experience who are ready and eager to answer your questions. You now have the ability to post, reply and give "kudos" on the Power Automate community forums. Make sure you conduct a quick search before creating a new post because your question may have already been asked and answered. Galleries: The galleries are full of content and can assist you with information on creating a flow in our Webinars and Video Gallery, and the ability to share the flows you have created in the Power Automate Cookbook.  Stay connected with the Community Connections & How-To Videos from the Microsoft Community Team. Check out the awesome content being shared there today.   Power Automate Community Blog: Over the years, more than 700 Power Automate Community Blog articles have been written and published by our thriving community. Our community members have learned some excellent tips and have keen insights on the future of process automation. In the Power Automate Community Blog, you can read the latest Power Automate-related posts from our community blog authors around the world. Let us know if you'd like to become an author and contribute your own writing — everything Power Automate-related is welcome.   Community Support: Check out and learn more about Using the Community for tips & tricks. Let us know in the Community Feedback  board if you have any questions or comments about your community experience. Again, we are so excited to welcome you to the Microsoft Power Automate community family. Whether you are brand new to the world of process automation or you are a seasoned Power Automate veteran - our goal is to shape the community to be your 'go to' for support, networking, education, inspiration and encouragement as we enjoy this adventure together.     Power Automate Community Team

Hear what's next for the Power Up Program

Hear from Principal Program Manager, Dimpi Gandhi, to discover the latest enhancements to the Microsoft #PowerUpProgram, including a new accelerated video-based curriculum crafted with the expertise of Microsoft MVPs, Rory Neary and Charlie Phipps-Bennett. If you’d like to hear what’s coming next, click the link below to sign up today! https://aka.ms/PowerUp  

Tuesday Tip | How to Report Spam in Our Community

It's time for another TUESDAY TIPS, your weekly connection with the most insightful tips and tricks that empower both newcomers and veterans in the Power Platform Community! Every Tuesday, we bring you a curated selection of the finest advice, distilled from the resources and tools in the Community. Whether you’re a seasoned member or just getting started, Tuesday Tips are the perfect compass guiding you across the dynamic landscape of the Power Platform Community.   As our community family expands each week, we revisit our essential tools, tips, and tricks to ensure you’re well-versed in the community’s pulse. Keep an eye on the News & Announcements for your weekly Tuesday Tips—you never know what you may learn!   Today's Tip: How to Report Spam in Our Community We strive to maintain a professional and helpful community, and part of that effort involves keeping our platform free of spam. If you encounter a post that you believe is spam, please follow these steps to report it: Locate the Post: Find the post in question within the community.Kebab Menu: Click on the "Kebab" menu | 3 Dots, on the top right of the post.Report Inappropriate Content: Select "Report Inappropriate Content" from the menu.Submit Report: Fill out any necessary details on the form and submit your report.   Our community team will review the report and take appropriate action to ensure our community remains a valuable resource for everyone.   Thank you for helping us keep the community clean and useful!

Users online (2,936)