这个简短的教程将帮助您了解如何在 Java 中将 Word 转换为 JPG。您可以将 Word 转换为 Java 中的 JPG,这样 DOCX Word 文档的每一页都保存为单独的 JPG 图像。如果您想将选定范围的页面转换为 JPG 图像,也可以使用本教程来实现。
在 Java 中将 Word 转换为 JPG 的步骤
- 使用 Maven 存储库添加 Aspose.Words 库以将 Word 转换为 JPG
- 添加对 Document、ImageSaveOptions、IPageSavingCallback 和其他类的引用
- 加载示例 Word 文档
- 实例化 ImageSaveOptions 对象以将保存格式设置为 JPG
- 在 ImageSaveOptions 中设置要呈现的页面范围
- 设置每页存为图片时的回调函数
- 在回调函数中的每个图像文件名中插入页码
- 将每个页面保存为 JPG
在这些步骤中,我们加载输入的 Word 文件并实例化 ImageSaveOptions 对象以设置保存格式以使用 Java 将 Word 保存为 JPG。还设置了要呈现为 JPG 图像的页面范围。声明了一个回调函数,该函数将在保存每个页面之前调用,以使用其中的页面索引设置不同的图像文件名。
Java 中将 Word 文件转换为 JPG 的代码
import com.aspose.words.License; | |
import com.aspose.words.PageRange; | |
import com.aspose.words.PageSavingArgs; | |
import com.aspose.words.PageSet; | |
import com.aspose.words.SaveFormat; | |
import java.text.MessageFormat; | |
import com.aspose.words.Document; | |
import com.aspose.words.IPageSavingCallback; | |
import com.aspose.words.ImageSaveOptions; | |
public class HowToConvertWordToJPGInJava { | |
public static void main(String[] args) throws Exception { //main function for How To Convert Word To JPG In Java | |
// Initialize a license to avoid trial version watermark in the output JPG file | |
License license = new License(); | |
license.setLicense("Aspose.Words.lic"); | |
// Load the input document that is to be converted to JPG | |
Document doc = new Document("input.docx"); | |
// Instantiate the ImageSaveOptions for saving Word file to JPG | |
ImageSaveOptions wordpagestoimage = new ImageSaveOptions(SaveFormat.JPEG); | |
// Set the range of pages for conversion to images | |
PageRange pagerange = new PageRange(0, doc.getPageCount() - 1); | |
wordpagestoimage.setPageSet(new PageSet(pagerange)); | |
// Set callback function while saving each page | |
wordpagestoimage.setPageSavingCallback(new FileNamePageSavingCallback()); | |
// Save document's pages to JPG | |
doc.save("output.jpg", wordpagestoimage); | |
} | |
private static class FileNamePageSavingCallback implements IPageSavingCallback { | |
@Override | |
public void pageSaving(PageSavingArgs args) throws Exception { | |
String outFileName = MessageFormat.format("InputDocx.Page_{0}.jpg", args.getPageIndex()); | |
// Set a filename for the output image against each page | |
args.setPageFileName(outFileName); | |
} | |
} | |
} |
此代码将文档的每一页转换为单独的 JPG 图像。但是,如果您只想转换指定范围的页面,请在 PageRange 对象中设置它,其中第一个参数采用初始页码,第二个参数采用要转换为 JPG 的总页数。
在本教程中,我们学习了将 Word 文档转换为 Java 中的 JPEG。如果您想了解将 Word 文件转换为 PDF 的过程,请参阅 如何在 Java 中将 Word 转换为 PDF 上的文章。