在这个简短的教程中,我们将学习如何使用 Java 在 Word 中插入图片。添加图片后,您可以将文件保存为 DOC 或 DOCX 格式。以下步骤可用于在您的应用程序中使用 Java 将图片添加到 Word 文档。
使用 Java 在 Word 中插入图片的步骤
- 从 Maven 存储库安装 Aspose.Words
- 使用 Document 类对象加载输入 Word 文档
- 实例化 DocumentBuilder 类对象
- 在 Word 文档页眉中插入图片
- 在Word文档中添加图片段落
- 插入图片后保存输出的Word文档
这些步骤初始化 Document 类以加载输入的 Word 文档,然后在页眉和段落中插入图片。输出文件以 DOCX 格式保存,但是您可以根据需要选择任何其他格式。
使用 Java 将图片添加到 Word 文档的代码
import com.aspose.words.Document; | |
import com.aspose.words.DocumentBuilder; | |
import com.aspose.words.HeaderFooterType; | |
import com.aspose.words.License; | |
import com.aspose.words.Shape; | |
public class InsertPictureInWordDocumentUsingJava | |
{ | |
public static void main(String[] args) throws Exception { //main function for InsertPictureInWordDocumentUsingJava class | |
// Initialize a license to avoid trial version watermark in the output Word file after adding image | |
License license = new License(); | |
license.setLicense("Aspose.Words.lic"); | |
// Load input Word DOCX document | |
Document AddImagesToWordDOC = new Document("input.docx"); | |
// Initialize DocumentBuilder class object to add image | |
DocumentBuilder imageWriter = new DocumentBuilder(AddImagesToWordDOC); | |
// Move the cursor to the Primary Header | |
imageWriter.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); | |
// Insert a picture in Word document header | |
Shape headerImage = imageWriter.insertImage("SampleImage.jpg"); | |
// Set Image Size in Header section | |
headerImage.setWidth(1 * 72); // equals to one inch | |
headerImage.setHeight(1 * 72); | |
// Move cursor to last Paragraph in Document | |
imageWriter.moveTo(AddImagesToWordDOC.getLastSection().getBody().getLastParagraph()); | |
// Add the picture to Word Document and Link it with the file | |
Shape imageAsLinkToFile = imageWriter.insertImage("SampleImage.jpg"); | |
imageAsLinkToFile.getImageData().setSourceFullName("SampleImage.jpg"); | |
// Save output DOCX file after inserting image | |
AddImagesToWordDOC.save("Word with Embedded and Linked Images.docx"); | |
} | |
} |
此 Java 代码示例无需 MS Word 应用程序或任何其他 Word 处理应用程序即可加载 Word 文档。然后将控制移动到标题和最后一段以分别插入图片。最后,您可以通过简单地提及正确的文件扩展名或使用 SaveFormat 枚举器作为保存函数中的第二个参数来保存文件。
在本教程中,我们学习了如何使用 Java 在 MS Word 中插入图片。如果您想学习如何从头开始创建 Word 文档,可以参考文章 如何使用 Java 创建 Word 文档。