java doc转图片_java后端将文档转为图片,图片最大65560px

这是一个Java方法,用于将PDF、Word和Excel文档转换为图片。首先,它使用Apache POI和Java的PDF处理库将文件转换为PDF,然后将PDF转换为图片。转换过程中考虑了图片的缩放比例和旋转角度,最后将多个页面的图片合并到一张宽幅图片中。
摘要由CSDN通过智能技术生成

//pdf转成图片

public void pdftoIamge(String pdfFile, String outpath) throws Exception {

InputStream is = new FileInputStream(pdfFile);

List piclist = new ArrayList();

Document document = new Document();

document.setFile(pdfFile);

float scale = 2.5f; // 缩放比例

float rotation = 0f; // 旋转角度

for (int i = 0; i 

BufferedImage image=(BufferedImage) document.getPageImage(i,GraphicsRenderingHints.SCREEN,

Page.BOUNDARY_CROPBOX, rotation, scale);

piclist.add(image);

}

document.dispose();

yPic(piclist, outpath);

is.close();

}

/**

* 将宽度相同的图片,竖向追加在一起,经过修改,没有了相同宽度这一限制

* @param piclist 文件流数组

* @param outPath 输出路径

*/

public void yPic(List piclist, String outPath) throws Exception{

// 纵向处理图片

if (piclist == null || piclist.size() <= 0) {

//Trace.logInfo(Trace.MODULE_ACTION, "图片数组为空!");

}

int height = 0, // 总高度

_width = 0, // 临时宽度

maxWidth = 0, // 最大宽度

_height = 0, // 临时的高度 , 或保存偏移高度

__height = 0, // 临时的高度,主要保存每个高度

picNum = piclist.size();// 图片的数量

int[] heightArray = new int[picNum]; // 保存每个文件的高度

int[] widthArray = new int[picNum]; // 保存每个文件的宽度

BufferedImage buffer = null; // 保存图片流

List imgRGB = new ArrayList(); // 保存所有的图片的RGB

int[] _imgRGB; // 保存一张图片中的RGB数据

for (int i = 0; i 

buffer = piclist.get(i);

if (buffer.getWidth() > maxWidth) {

// 获取最大宽度

maxWidth = buffer.getWidth();

}

}

for (int i = 0; i 

buffer = piclist.get(i);

heightArray[i] = _height = buffer.getHeight();// 图片高度

widthArray[i] = _width = buffer.getWidth();// 图片宽度

height += _height; // 获取总高度

_imgRGB = new int[_width * _height];// 从图片中读取RGB

_imgRGB = buffer.getRGB(0, 0, _width, _height, _imgRGB, 0, _width);

imgRGB.add(_imgRGB);

}

_height = 0; // 设置偏移高度为0

// 生成新图片

BufferedImage imageResult = new BufferedImage(maxWidth, height, BufferedImage.TYPE_INT_RGB);

for (int i = 0; i 

__height = heightArray[i];

_width = widthArray[i];

//if (i != 0)

_height += heightArray[i-1];// 计算偏移高度 ,若高度一致,则把此行打开

if (i != 0)

_height += heightArray[i - 1]; // 计算偏移高度 ,因高度不一致,所以i-1

//imageResult.setRGB(0,_height,widthArray[i],__height,imgRGB.get(i),0,widthArray[i]);//写入流中

// 居中,前两个参数为起始的宽度、高度

imageResult.setRGB((maxWidth-_width)/2,_height,_width,__height,imgRGB.get(i),0,_width);//写入流中

}

File outFile = new File(outPath);

try {

ImageIO.write(imageResult, "jpg", outFile);// 写图片

} catch (Exception e) {

// TODO: handle exception

throw new MyException(-20,"文件过大,不能通过审批直接查看");

}

}

/***

* 判断文件类型

* @param fileName

* @return

*/

public String getFileSufix(String fileName) throws Exception{

int splitIndex = fileName.lastIndexOf(".");

return fileName.substring(splitIndex + 1);

}

/***

*

* Word转PDF

*

* @param inputFile

* @param pdfFile

* @return

*/

public int word2PDF(String inputFile, String pdfFile) throws Exception{

// TODO Auto-generated method stub

try {

ComThread.InitSTA();

// 打开Word应用程序

ActiveXComponent app = new ActiveXComponent("Word.Application");

System.out.println("开始转化Word为PDF...");

long date = new Date().getTime();

// 设置Word不可见

app.setProperty("Visible", new Variant(false));// 禁用宏

app.setProperty("AutomationSecurity", new Variant(3));// 获得Word中所有打开的文档,返回documents对象

Dispatch docs = app.getProperty("Documents").toDispatch();

// 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document

Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();

File tofile = new File(pdfFile);

if (tofile.exists()) {

tofile.delete();

}

/***

*

* 调用Document对象的SaveAs方法,将文档保存为pdf格式

*

* Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF

* word保存为pdf格式宏,值为17 )

*

*/

Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF);// word保存为pdf格式宏,值为17

System.out.println(doc);            // 关闭文档

long date2 = new Date().getTime();

int time = (int) ((date2 - date) / 1000);

Dispatch.call(doc, "Close", false);// 关闭Word应用程序

app.invoke("Quit", 0);

return time;

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return -1;

}finally{

ComThread.Release();

}

}

/***

*

* Excel转化成PDF

*

* @param inputFile

* @param pdfFile

* @return

*/

public int Ex2PDF(String inputFile, String pdfFile)throws Exception {

try {

ComThread.InitSTA();

ActiveXComponent ax = new ActiveXComponent("Excel.Application");

System.out.println("开始转化Excel为PDF...");

long date = new Date().getTime();

ax.setProperty("Visible", false);

ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏

Dispatch excels = ax.getProperty("Workbooks").toDispatch();

System.out.println(inputFile);

Dispatch excel = Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[]

{

inputFile, new Variant(false),new Variant(false)

},new int[9]).toDispatch();

File tofile = new File(pdfFile);

if (tofile.exists()) {

tofile.delete();

}

// 转换格式

Dispatch.invoke(excel,"ExportAsFixedFormat",Dispatch.Method,new Object[]{new Variant(0),//PDF格式=0

pdfFile, new Variant(xlTypePDF) //0=标准(生成的PDF图片不会变模糊)1=最小文件},new int[1]);

// 这里放弃使用SaveAs

/*

* Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{

* pdfFile, new Variant(57), new Variant(false), new Variant(57),

* new Variant(57), new Variant(false), new Variant(true), new

* Variant(57), new Variant(true), new Variant(true), new

* Variant(true) },new int[1]);

*/

long date2 = new Date().getTime();

int time = (int) ((date2 - date) / 1000);

Dispatch.call(excel, "Close", new Variant(false));

if (ax != null) {

ax.invoke("Quit", new Variant[] {});

ax = null;

}

return time;

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return -1;

}finally{

ComThread.Release();

}

此为service层处理代码,可以在controller层进行文件的判断,我自己根据自身业务需要,

还是在service层进行的处理

public String fileToImg(String infile) throws Exception {

URL url = getClass().getProtectionDomain().getCodeSource().getLocation();

String path1 = url.toString();

int index = path1.indexOf("WebRoot");

if(index == -1){

index = path1.indexOf("classes");

}

if(index == -1){

index = path1.indexOf("bin");

}

path1 = path1.substring(0, index);

if(path1.startsWith("zip")){

//当class文件在war中时,此时返回zip:D:/...这样的路径

path1 = path1.substring(4);

}else if(path1.startsWith("file")){

//当class文件在class文件中时,此时返回file:/D:/...这样的路径

path1 = path1.substring(6);

}else if(path1.startsWith("jar")){

//当class文件在jar文件里面时,此时返回jar:file:/D:/...这样的路径

path1 = path1.substring(10);

}

path1 =  URLDecoder.decode(path1, "UTF-8");

path1 = path1.substring(0, path1.indexOf("PM Platform"));

String str1 = infile.replaceAll("\\\\", "/").replaceAll("//", "/");

String inputFile = str1.replaceAll( "///", "/").replaceAll("//", "/");

String kind = getFileSufix(inputFile);

File file = new File(inputFile);

String str = String.valueOf(new Date().getTime());

String pdfFile = path1+"image/"+str+".pdf";

String imgfile = path1+"image/"+str+".jpg";

//判断需要转化文件的类型(Excel、Word)

if (!file.exists()) {

return "0";//文件不存在

}

if (kind.equals("pdf")) {

try {

pdftoIamge(inputFile, imgfile);

return inputFile.substring(inputFile.lastIndexOf("/"), inputFile.length())+".jpg";//原文件就是PDF文件

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return "-20";

}

}

if (kind.equals("jpg")||kind.equals("png")) {

return infile;//原文件就是图片

}

if (kind.equals("doc")||kind.equals("docx")||kind.equals("txt")) {

word2PDF(inputFile, pdfFile);

try {

pdftoIamge(pdfFile, imgfile);

return str+".jpg";

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return "-20";

}

}else if(kind.equals("xls")||kind.equals("xlsx")){

Ex2PDF(inputFile, pdfFile);

try {

pdftoIamge(pdfFile, imgfile);

return str+".jpg";

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return "-20";

}

}else {

return "0";

}

}

因为自身业务,对于路径进行了处理,当pdf转化异常,进行了异常的处理。不需要可以根据需要更改

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值