破解版完整demo请下载:https://download.youkuaiyun.com/download/m0_37951794/87631137
转换前word文档:
转换后图片:
实现代码如下:
package filePreview.filePreview_aspose_words;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.License;
import com.aspose.words.NodeType;
import com.aspose.words.PageSetup;
import com.aspose.words.Paragraph;
import com.aspose.words.ParagraphFormat;
import com.aspose.words.SaveFormat;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws Throwable
{
String file_path = "C:/Users/shx/Desktop/test.docx";//需要转换的文件
File file = new File(file_path);
String name = file.getName();
String file_name = name.substring(0,name.lastIndexOf("."));//获取文件名
String file_suffix_name = file_path.substring(file_path.lastIndexOf("."));//文件类型
if(file_suffix_name.equals(".docx") || file_suffix_name.equals(".doc")) {
FileOutputStream os = null;
try {
//String licensexml = "";
//ByteArrayInputStream is = new
//ByteArrayInputStream(licensexml.getBytes());
//License license = new License();
//license.setLicense(is);
long old = System.currentTimeMillis();
//word文档
Document doc = new Document(file_path);
DocumentBuilder builder = new DocumentBuilder(doc);
Iterator iterator = doc.getChildNodes(NodeType.PARAGRAPH,true).iterator();
while(iterator.hasNext()) {
Paragraph next = (Paragraph)iterator.next();
ParagraphFormat pf = next.getParagraphFormat();
pf.setSpaceAfter(0);
pf.setSpaceBefore(0);
}
PageSetup pageSetup = builder.getPageSetup();
pageSetup.setBottomMargin(0);
pageSetup.setTopMargin(0);
pageSetup.setLeftMargin(0);
pageSetup.setRightMargin(0);
//支持RTF HTML OpenDocument PDF EPUB XPS转换
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
options.setResolution(400); //设置图片大小
int pageCount = doc.getPageCount();//获取文档页面数
//根据文档页数依次生成图片
String outDir = "C:/Users/shx/Desktop/imagefile";
List<String> paths = new ArrayList<>();
for(int i=0;i<pageCount;i++) {
File file_image = new File(outDir+"/"+file_name+"_"+i+".png");
System.out.print("正在进行words转换图片:"+file_image.getPath());
os = new FileOutputStream(file_image);
options.setPageIndex(i);
doc.save(os,options);
//转换后图片全路径名放入list
String path = file_image.getPath();
//path = path.replaceAll("\\\\", "/");
paths.add(path);
os.close();
}
long now = System.currentTimeMillis();
System.out.print(file_path+"word转图片完成" + ((now - old) / 1000.0) +"秒");
System.out.print("转换后的图片在:"+paths);
} catch (Exception e) {
System.out.print("word转图片失败!");
}finally {
if(os !=null) {
try {
os.close();
} catch (IOException e) {
System.out.print("失败:" +e.toString());
}
}
}
}else {
System.out.print("文件类型错误,只支持docx,doc类型");
}
}
}