Could not Find And Replace text In PPT for Java


#1

Hello ! I want to find and replace text in poewrpoint files in java. I have written the following code, but it’s not working. I am attaching the input file too !
Please get it done, thankyou !

public static void main(String[]args) {
Presentation presentation = new Presentation(“E:\samplepptx.pptx”);
presentation.joinPortionsWithSameFormatting();
String strToReplace = “Done”;
ITextFrame[] tb = SlideUtil.getAllTextFrames(presentation, true);
String strToFind = “Sample”;
System.out.println(“Before for”);
for (int i = 0; i < tb.length; i++)
{
for (IParagraph ipParagraph : tb[i].getParagraphs())
{
for (IPortion iPortion : ipParagraph.getPortions())
{
if (iPortion.getText().contains(strToFind))
{
iPortion.setText(iPortion.getText().replace(strToFind,strToReplace));
System.out.println(“replaced”);
}
}
}
}
presentation.save(“E:\Output.pptx”,SaveFormat.Pptx);
}


#2

@Kushal.20,

I have observed the sample code shared by you and there seems no issue in code. Can you please share what is the issue incurring on your end in terms of replacing the text. Please provide the source file, generated file and desired output file as well for working on our end. I also suggest you to please consider your following sample example that is in fact extracting the text on portion level inside presentation. You can modify this by adding sample code for verifying portion text and then setting replacement accordingly. One thing you need to make sure is that when you are verifying text on portion level, you need to provide a string of portion and not paragraph or Textframe.

public static void GetFonts(String presName,String path)

{
    
    // Create Empty presentation instance


    path="C:\\Aspose Data\\DumpAllText\\";
    presName="test.ppt";
    Presentation pres = new Presentation(path+presName);
    /*for(int z=0;z<pres.getFontsManager().getFonts().length;z++)
     {
        System.out.println("Fonts used: "+ pres.getFontsManager().getFonts()[z]);
     }*/
    ISlideCollection slides = pres.getSlides();

    ISlide slide = null;
    IShape shape = null;
    for (int i = 0; i < slides.size(); i++) 
    {
       slide = slides.get_Item(i);

        for (int j = 0; j < slide.getShapes().size(); j++) 
        {
             shape = slide.getShapes().get_Item(j);

              // if (shape.getPlaceholder() != null) 
              if(shape instanceof AutoShape)
              {
                if (((IAutoShape)shape).getTextFrame() != null) 
                {
                    ExtractFonts(((IAutoShape) shape).getTextFrame());

                }

              }
              else if(shape instanceof LegacyDiagram)
              {
                  LegacyDiagram legacy=(LegacyDiagram)shape;

                  ISmartArt smart=legacy.convertToSmartArt();
                  for(ISmartArtNode node:smart.getAllNodes())
                  {
                      if(node.getTextFrame()!=null)
                      {
                         ExtractFonts(node.getTextFrame());
                      }

                  }

              }
              else if(shape instanceof SmartArt)
              {
                  ISmartArt smart=(ISmartArt)shape;
                  for(ISmartArtNode node:smart.getAllNodes())
                  {
                      if(node.getTextFrame()!=null)
                      {
                         ExtractFonts(node.getTextFrame());
                      }

                  }

              }

              else if (shape instanceof Table)
              {
                  ITable table=(ITable)shape;
                  for(int u=0;u<table.getRows().size();u++)
                  {
                      for(int v=0;v<table.getColumns().size();v++)
                      {
                          ICell cell=table.get_Item(v, u);
                          if(cell.getTextFrame()!=null )
                          {
                           ExtractFonts(cell.getTextFrame());
                          }

                      }
                  }

              }
            }
       }
    }

public static void ExtractFonts(ITextFrame tf2)
{

    for (int k = 0; k < tf2.getParagraphs().getCount(); k++) 
    {
        IParagraph paragraph = tf2.getParagraphs().get_Item(k);
        for (int n = 0; n < paragraph.getPortions().getCount(); n++) 
        {
            IPortion portion = paragraph.getPortions().get_Item(n);
            IPortionFormat pformat=portion.getPortionFormat();
            System.out.println("Portion Text: "+portion.getText());

 /*           if(pformat.getFillFormat().getFillType()==FillType.Solid)
            {
                System.out.println("Portion Color: R"+pformat.getFillFormat().getSolidFillColor().getR()+"  G"+pformat.getFillFormat().getSolidFillColor().getG()+"  B"+pformat.getFillFormat().getSolidFillColor().getB());
            }
   */         
  /*          if(pformat.getLatinFont()!=null)
                 System.out.println(pformat.getLatinFont().getFontName());
            if(pformat.getEastAsianFont()!=null)
               System.out.println(pformat.getEastAsianFont().getFontName());
            if(pformat.getEastAsianFont()!=null)
               System.out.println(pformat.getEastAsianFont().getFontName());
            if(pformat.getComplexScriptFont()!=null)
               System.out.println(pformat.getComplexScriptFont().getFontName());
            if(pformat.getSymbolFont()!=null)
               System.out.println(pformat.getSymbolFont().getFontName());
*/
        }
    }
}

#3

@mudassir.fayyaz, Thanks !
Well, I already attached the input file. Anyways, am attaching it once again as, ‘samplepptx.zip’. Kindly find it and do let me know if my piece of code is correct ! samplepptx.zip (394.3 KB)

The output file am getting is exactly the replica of the input file. But, my desired output is to replace the word, ‘sample’ with ‘done’ in the file. Kindly look into it and let me know.


#4

@mudassir.fayyaz

I did not understand your code much, but yeah, still I gave it a try.
following is the modification I made to count the word,‘sample’ in the file. Is it any good ? Or do I need to do something else ? Here goes the code snippet :
IParagraph paragraph = tf2.getParagraphs().get_Item(k);
for (int n = 0; n < paragraph.getPortions().getCount(); n++)
{
IPortion portion = paragraph.getPortions().get_Item(n);
IPortionFormat pformat=portion.getPortionFormat();
if(portion.getText().contains(“sample”)) {
count++;
}
System.out.println("Portion Text: "+count);


#5

@Kushal.20,

I have shared sample code with you along with generated result for your kind reference. Please check attachment and share feedback with us if there is still an issue.

Output.zip (362.4 KB)

Presentation presentation = new Presentation(“samplepptx.pptx”);
presentation.joinPortionsWithSameFormatting();
String strToReplace = “Done”;
ITextFrame[] tb = SlideUtil.getAllTextFrames(presentation, true);
String strToFind = “Sample”;
System.out.println(“Before for”);
for (int i = 0; i < tb.length; i++)
{
for (IParagraph ipParagraph : tb[i].getParagraphs())
{
for (IPortion iPortion : ipParagraph.getPortions())
{
if (iPortion.getText().toLowerCase().contains(strToFind.toLowerCase()))
{
iPortion.setText(iPortion.getText().replaceAll("(?i)"+strToFind, strToReplace));
System.out.println(“replaced”);
}
}
}
}
presentation.save(“Output.pptx”,SaveFormat.Pptx);


#6

@Adnan.Ahmad
I have used the same code as above, but still am not getting the output. The word, ‘sample’ is not replaced by ‘done’ in my case. Although, the code is exactly the same.
Find the output file here : Output.zip (364.5 KB)

Please guide !


#7

@Kushal.20,

I have checked your output file. I like to inform that you are using Aspose.Slides 19.2 on your end. Please try to use latest version Aspose.Slides 19.5 on your end and share feedback with us if there is still an issue.


#8

@Adnan.Ahmad
Now, I have tried it with 19.5 too, still am not able to resolve this. Please Help !


#9

@Kushal.20,

Can you please share complete environment details with us. As you know i have already shared generated result with you for your kind reference.


#10

@Adnan.Ahmad
I am using Java 1.8 i.e; jre1.8.0_131 and the jars for aspose.slides : 1. aspose-slides-19.5-jdk16.jar and 2. aspose-slides-19.5-javadoc.jar
This is the environment I am working in !

I have tried almost everything. Kindly look into this and let me know where actually the fault is !


#11

@Kushal.20,

I have observed the sample code shared by you. The issue lies in the code where you are trying to replace string with bullet rather than only text. I suggest you to please try using following sample code on your end.

public static void ReplacePresentationText()
{
    String path="C:\\Users\\Muhammad\\Downloads\\samplepptx\\";
    Presentation presentation = new Presentation(path+"samplepptx.pptx");
    presentation.joinPortionsWithSameFormatting();
    String strToReplace = "Done";
    ITextFrame[] tb = SlideUtil.getAllTextFrames(presentation, true);
    String strToFind = "Sample";
    System.out.println("Before for");
    for (int i = 0; i < tb.length; i++)
    {
        for (IParagraph ipParagraph : tb[i].getParagraphs())
        {
            for (IPortion iPortion : ipParagraph.getPortions())
            {
                if (iPortion.getText().toLowerCase().contains(strToFind.toLowerCase()))
                {
                    iPortion.setText(iPortion.getText().toLowerCase().replaceAll(strToFind, strToReplace));
                    System.out.println("replaced");
                }
            }
        }
    }
    presentation.save(path+"Output.pptx",SaveFormat.Pptx);
}

Output.zip (362.4 KB)


#12

@mudassir.fayyaz, thanks for your continued support !
But, I am still getting the same unchanged output.

I am getting this, but after this, it’s not going inside the for loop , as previously said ! :confused:


#13

@Kushal.20,

Are you using licensed version of Aspose.Slide for Java or using without license. If you are using without license then in unlicensed version there is limit to access all paragraphs portions inside text frame. Otherwise, there is no issue at and I have already shared the output with you too.


#14

@mudassir.fayyaz
Nope ! Am using the trial version.
But, it should have atleast replaced once, in the trial version ? Or, it won’t ?

yeah,I saw the output you generated, but I am unable to get the result at my end. I have tried everything, neither getting any error/exception !


#15

@Kushal.20,

I like to inform that trial version has some limitations. Please use license version on your end to use this feature.


#16

@Adnan.Ahmad
Okay, i will try using license too ! In fact, I tried !
But, I have been using evaluation version for all other formats, since I am just exploring and testing the API’s, if they are suitable and I could buy them for using, and all of them have been working fine.
For Aspose.Slides, I read following on the official website :

Evaluation Version Limitation

Evaluation version of Aspose.Slides (without a license specified) provides full product functionality except that when you save your presentations using Aspose.Slides, an Evaluation Watermark is injected at the center of each slide as shown in the figure below

Kindly, let me know what the issue is and how to apply license, I tried the way given on the website but am getting the exception, that, LicenseStream is not available for reading. I did not get any license file in the jar folder that I downloaded.


#17

@Kushal.20,

You are right about watermark insertion. However. the evaluation version does impose some limitations like no full access to all paragraphs or portions inside TextFrame (You may have access to few portion of text while using evaluation version but not all if there are many portions. For simple presentation with one or two portions. it may work). There are some limits on some chart features too.

My suggestion to you is to try exploring the API using 30 days free license that you may use on your end to verify the API features.


#18

@mudassir.fayyaz
Finally, am done with this. I followed your suggestion . Thanks buddy ! :slight_smile:

Well, I need another assistance.This is the code that I have used for finding and replacing text :

public static void main(String[]args) {

		com.aspose.slides.License license = new com.aspose.slides.License();
		license.setLicense("xyz");
	
		Presentation presentation = new Presentation("E:\\docs\\samplepptx.pptx");
		presentation.joinPortionsWithSameFormatting();
		String strToReplace = "Done";
		ITextFrame[] tb = SlideUtil.getAllTextFrames(presentation, true);
		//String find = "sample";
		String strToFind= "(?i)\\b"+find+"\\b";
		//System.out.println("Before for :"+strToFind);
		for (int i = 0; i < tb.length; i++)
		{
			for (IParagraph ipParagraph : tb[i].getParagraphs()) 
			{	
				for (IPortion iPortion : ipParagraph.getPortions()) 
				{	
					if(iPortion.getText().toLowerCase().contains(strToFind.toLowerCase()))
					{ 	
						iPortion.setText(iPortion.getText().replaceAll(strToFind, strToReplace));
						System.out.println("replaced");
					}
				}
			}
		}
		presentation.save("E:\\docs\\Output.pptx",SaveFormat.Pptx);
	} 

Here the problem is with CASE. I am unable to pass text as case insensitive.Like for PDF, I used
String strFind = “sample”;
String find = “(?i)\b”+strFind+"\b";
This replaced all the occurrences of the word ‘sample’, be it in LowerCase or UpperCase
But, this isn’t working in this case of slides.
Thanks !


#19

@Kushal.20,

I have worked with sample code and source file shared by you. I have shared my generated result for your kind reference. Can you please check and share if this is acceptable for you.Output.zip (362.4 KB)


#20

@Adnan.Ahmad
Yes, as far as I can check, it’s correct. I want all samples to be replaced with Done, no matter I input sample or Sample.
I guess, this is correct.
Can you please share with me the syntax for case insensitivity with me?