Изменить текст слайда в java с помощью aspose api ppt
public void save()
{ Presentation pres = new Presentation(filename);
ISlide slide = pres.getSlides().get_Item(0);
IShape shape= null;
for (int i = 0 ; i < slide.getShapes().size() ; i++)
{ shape = slide.getShapes().get_Item(i);
if (shape.getPlaceholder() != null)
{
((IAutoShape)shape).getTextFrame().setText(txtArea.getText());
}
}
pres.save(filename,SaveFormat.Ppt);
}
Этот код предназначен для изменения текста, но он не работает. Я использовал два API одновременно, код показа ниже:
public void Display(int currentPage, String source)
{
try {
// Create a slideshow object; this creates an underlying POIFSFileSystem object for us
SlideShow ppt = new SlideShow(new HSLFSlideShow(source));
current=currentPage;
// Get all of the slides from the PPT file
Slide[] slides = ppt.getSlides();
Dimension pgsize = ppt.getPageSize();
all = slides.length;
String temp="";
lblPage.setText(currentPage+" / "+all);
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
//render
slides[currentPage-1].draw(graphics);
//save the output
/*FileOutputStream out = new FileOutputStream("slide-" + (i + 1) + ".png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
//ImageIcon icon = new ImageIcon("slide-" + (i + 1) + ".png");*/
ImageIcon icon = new ImageIcon(img);
lblPresentasi.setIcon(icon);
// Obtain metrics about the slide: its number and name
int number = slides[currentPage-1].getSlideNumber();
String title = slides[currentPage-1].getTitle();
// Obtain the embedded text in the slide
TextRun[] textRuns = slides[currentPage-1].getTextRuns();
System.out.println("Slide " + number + ": " + title);
System.out.println("\tText Runs");
txtArea.setText("Slide : " + number + " Title : " + title + "\n");
for (int j = 0; j < textRuns.length; j++) {
// Display each of the text runs present on the slide
System.out.println("\t\t" + j + ": " + textRuns[j].getText());
temp=txtArea.getText();
txtArea.setText(temp+"\t\t" + textRuns[j].getText() + "\n");
}
// Obtain the notes for this slide
System.out.println("\tNotes: ");
Notes notes = slides[currentPage-1].getNotesSheet();
if (notes != null) {
// Notes are comprised of an array of text runs
TextRun[] notesTextRuns = notes.getTextRuns();
for (int j = 0; j < notesTextRuns.length; j++) {
System.out.println("\t\t" + notesTextRuns[j].getText());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Может кто-нибудь, пожалуйста, помогите, я пытаюсь сделать простой редактор PowerPoint на Java. Я хочу изменить текст в текстовой области, нажмите кнопку сохранения, чтобы текст изменился, и вызовите функцию отображения.
2 ответа
Я ознакомился с вашим примером кода и хотел бы поделиться с вами тем, что в отношении кода, связанного с Aspose.Slides, проблем нет, и он совершенно прав. Вы можете убедиться в этом, открыв сохраненную презентацию с измененным текстом в PowerPoint. Если у вас возникнут какие-либо проблемы в этом, мы будем рады помочь вам в дальнейшем. Вы также можете связаться с нами на форумах поддержки Aspose.Slides.
Я работаю с Aspose в качестве разработчика евангелиста.
Похоже, вы используете Aspose.Slides, который, безусловно, является отличным инструментом для удовлетворения таких требований, в то время как я обычно использую Free Spire.Presentation for Java , который также удовлетворит ваши потребности, попробуйте этот код:
import com.spire.presentation.*;
import java.util.HashMap;
import java.util.Map;
public class ReplaceText {
public static void main(String[] args) throws Exception {
//create a Presentation object
Presentation presentation = new Presentation();
//load the template file
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");
//get the first slide
ISlide slide= presentation.getSlides().get(0);
//create a Map object
Map map = new HashMap();
//add several pairs of keys and values to the map
map.put("#name#","John Smith");
map.put("#age#","28");
map.put("#address#","Oklahoma City, United States");
map.put("#tel#","333 123456");
map.put("#email#","johnsmith@outlook.com");
//replace text in the slide
replaceText(slide,map);
//save to another file
presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
}
/**
* Replace text within a slide
* @param slide Specifies the slide where the replacement happens
* @param map Where keys are existing strings in the document and values are the new strings to replace the old ones
*/
public static void replaceText(ISlide slide, Map map) {
for (Object shape : slide.getShapes()
) {
if (shape instanceof IAutoShape) {
for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
) {
ParagraphEx paragraphEx = (ParagraphEx)paragraph;
for (String key : map.keySet()
) {
if (paragraphEx.getText().contains(key)) {
paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
}
}
}
}
}
}
}