在本章中,您將學(xué)習(xí)如何在演示文稿中創(chuàng)建超鏈接。
您可以使用 XSLFTextRun 類的 createHyperlink()方法讀取演示文稿中的超鏈接。 按照下面給出的過程在演示中創(chuàng)建超鏈接。
使用 XMLSlideShow 類創(chuàng)建一個空的演示文稿,如下所示:
XMLSlideShow ppt = new XMLSlideShow();
創(chuàng)建一個空白幻燈片,并使用正文和內(nèi)容布局創(chuàng)建幻燈片的文本框和正文。
//create an empty presentation XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0]; //creating a slide with title and content layout XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); XSLFSlide slide = ppt.createSlide(slidelayout); //selection of body place holder XSLFTextShape body = slide.getPlaceholder(1); //clear the existing text in the slide body.clearText();
創(chuàng)建一個文本運行對象并設(shè)置文本到它,如下所示:
XSLFTextRun textRun=body.addNewTextParagraph().addNewTextRun(); textRun.setText("Tutorials point");
使用 XSLFTextRun 類的 createHyperlink()方法創(chuàng)建超鏈接,如下所示:
XSLFHyperlink link = textRun.createHyperlink();
使用 XSLFHyperlink 類的 setAddress()方法將鏈接地址設(shè)置為超鏈接,如下所示:
link.setAddress("//www.o2fo.com/");
下面給出了在演示文稿中創(chuàng)建超鏈接的完整程序:
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xslf.usermodel.SlideLayout; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFHyperlink; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.apache.poi.xslf.usermodel.XSLFSlideLayout; import org.apache.poi.xslf.usermodel.XSLFSlideMaster; import org.apache.poi.xslf.usermodel.XSLFTextRun; import org.apache.poi.xslf.usermodel.XSLFTextShape; public class CreatingHyperlinks { public static void main(String args[]) throws IOException{ //create an empty presentation XMLSlideShow ppt = new XMLSlideShow(); //getting the slide master object XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0]; //select a layout from specified list XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); //creating a slide with title and content layout XSLFSlide slide = ppt.createSlide(slidelayout); //selection of title place holder XSLFTextShape body = slide.getPlaceholder(1); //clear the existing text in the slid body.clearText(); //adding new paragraph XSLFTextRun textRun = body.addNewTextParagraph().addNewTextRun(); //setting the text textRun.setText("Tutorials point"); //creating the hyperlink XSLFHyperlink link = textRun.createHyperlink(); //setting the link address link.setAddress("//www.o2fo.com/"); //create the file object File file=new File("hyperlink.pptx"); FileOutputStream out = new FileOutputStream(file); //save the changes in a file ppt.write(out); System.out.println("slide cretated successfully"); out.close(); } }
將上述Java代碼保存為 CreatingHyperlinks.java ,然后從命令提示符處編譯并執(zhí)行,如下所示:
$javac CreatingHyperlinks.java $java CreatingHyperlinks
它將編譯并執(zhí)行以生成以下輸出:
slide cretated successfully
新添加的幻燈片及其正文中的超鏈接如下所示:
更多建議: