aspose words(插入图片131行)
示例代码
下面展示一些 内联代码片
。
// aspose.words打印,电子签名转化插入文档方法示例
package com.epoint.szjs.qyapp.mobile.action;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import com.aspose.words.WrapType;
import com.epoint.basic.api.common.ApiBaseController;
import com.epoint.core.dao.CommonDao;
import com.epoint.core.grammar.Record;
import com.epoint.core.utils.classpath.ClassPathUtil;
import com.epoint.core.utils.code.Base64Util;
import com.epoint.core.utils.container.ContainerFactory;
import com.epoint.core.utils.date.EpointDateUtil;
import com.epoint.core.utils.file.FileManagerUtil;
import com.epoint.core.utils.string.StringUtil;
import com.epoint.frame.service.attach.api.IAttachService;
import com.epoint.frame.service.attach.entity.FrameAttachInfo;
import com.epoint.szjs.common.database.ProductDBNameConstant;
import freemarker.template.Configuration;
public class SafeBJService2 extends ApiBaseController
{
private CommonDao dao = CommonDao.getInstance(ProductDBNameConstant.ZLAQ);
private static final String DATE_FORMAT ="yyyy年MM月dd日";
private static final String DATE_FILE ="yyyyMMddhhmmss";
/**
*
* [安监监督记录、限期整改等文档打印]
* @param params
* @return
* @exception/throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public JSON asposePrintDoc(String params) {
//解析接口入参
JSONObject json = JSON.parseObject(params);
JSONObject jsonObj = new JSONObject();
JSONObject status = new JSONObject();
JSONObject custom = new JSONObject();
IAttachService attachService = ContainerFactory.getContainInfo().getComponent(IAttachService.class);
String rowguid = json.get("rowguid").toString();
String type = json.get("doctype").toString();
String sql = "select * from jzjcdoc where rowguid = '"+rowguid+"'";
String pdf = json.get("pdf").toString();
Record info = dao.find(sql,Record.class);
String docName = "施工安全监督记录2.docx";
if ("1".equals(type)) {
docName = "施工安全监督记录2.docx";
}else if ("2".equals(type)) {
docName = "限期整改通知书.docx";
}else if ("3".equals(type)) {
docName = "停工整改通知书.docx";
}else if ("4".equals(type)) {
docName = "恢复施工安全监督告知书.docx";
}
//获取证书,用于去除水印
// File file = new File(ClassPathUtil.getDeployWarPath() + "WEB-INF/license.xml");
String licenseName = ClassPathUtil.getClassesPath() + "EpointAsposeWords.lic";
System.out.println(licenseName);
try {
License license = new License();
if (license !=null) {
license.setLicense(licenseName);
}
}
catch (Exception e1) {
e1.printStackTrace();
}
//模板路径
String path = ClassPathUtil.getDeployWarPath() + "Template" + File.separator + "safeaspose" + File.separator+docName;
try {
//获取文档对象
Document tempdoc = new Document(path);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//创建名称为zlList的DataTable,并绑定字段
//此为单字段填充
List<String> list = new ArrayList<String>();
list.add("gcmc");//填报日期
list.add("docnumber");//填报日期
list.add("xxjd");//形象进度
list.add("ccbw");//抽查部位
list.add("ccfw");//抽查范围
list.add("checkdate");//检查日期
//以下为字段填充内容
String[] fieldNames = list.toArray(new String[list.size()]);
List<Object> listObject = new ArrayList<Object>();
listObject.add(info.getStr("gcmc"));
listObject.add(info.getStr("docnumber"));
listObject.add(info.getStr("xxjd"));
listObject.add(info.getStr("ccbw"));
listObject.add(info.getStr("ccfw"));
listObject.add(EpointDateUtil.convertDate2String(info.getDate("checkdate"), "yyyy年MM月dd日"));
Object[] values = listObject.toArray(new Object[listObject.size()]);
// 路径
String basePath = ClassPathUtil.getDeployWarPath() + "AttachStorage" + File.separator + "picpath"
+ File.separator + rowguid + File.separator ;
try {
//插入图片代码
DocumentBuilder builder = new DocumentBuilder(tempdoc);
builder.endBookmark("picjs");
//insertimage("路径","水平位置","左偏移量","垂直位置","上边距","图片宽","图片高","图片环绕类型");
builder.insertImage(basePath+ "11" + File.separator+"11" + ".png", RelativeHorizontalPosition.MARGIN, 300, RelativeVerticalPosition.MARGIN, 430, 100, 25, WrapType.NONE);
builder.endBookmark("picsg");
builder.insertImage(basePath+ "11" + File.separator+"11" + ".png", RelativeHorizontalPosition.MARGIN, 300, RelativeVerticalPosition.MARGIN, 460, 80, 15, WrapType.NONE);
builder.endBookmark("picjl");
builder.insertImage(basePath+ "11" + File.separator+"11" + ".png", RelativeHorizontalPosition.MARGIN, 300, RelativeVerticalPosition.MARGIN, 490, 80, 15, WrapType.NONE);
}
catch (Exception e1) {
e1.printStackTrace();
}
//对字段内容进行填充
tempdoc.getMailMerge().execute(fieldNames, values);
//合成文件流
tempdoc.save(outputStream, SaveOptions.createSaveOptions(SaveFormat.DOCX));
// 输出文档路径及名称
String outpath2 = ClassPathUtil.getDeployWarPath() + "Template" + File.separator + "temp";
//输出文件
getFileByBytes(outputStream.toByteArray(), outpath2, docName);
FileInputStream stream = null;
try {
stream = new FileInputStream(outpath2 + File.separator + docName);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
//创建文件对象,准备入库
FrameAttachInfo attachinfo = new FrameAttachInfo();
try {
byte[] buf;
stream = new FileInputStream(outpath2 + File.separator + docName);
byte[] b = new byte[1000];
int n;
while ((n = stream.read(b)) != -1) {
outputStream.write(b, 0, n);
}
buf = outputStream.toByteArray();
attachinfo.setAttachLength((long) buf.length);
}
catch (Exception e) {
e.printStackTrace();
}
InputStream content;
try {
//先判断数据库是否存在此附件,如果存在则删除替换
FrameAttachInfo framePdfAttachInfo = attachService.getAttachInfoDetail(rowguid);
content = saveInputStream(outpath2 + File.separator + docName);
if (StringUtil.isNotBlank(framePdfAttachInfo)) {
attachService.deleteAttachByAttachGuid(rowguid);
}
attachinfo.setAttachGuid(rowguid);
attachinfo.setCliengGuid(rowguid);
attachinfo.setCliengTag(type);
attachinfo.setCliengInfo("接口系统生成");
attachinfo.setUploadUserGuid("appuserguid");
attachinfo.setUploadUserDisplayName("appdisplayname");
attachinfo.setUploadDateTime(new Date());
attachinfo.setAttachFileName(docName);
long size = content.available();
attachinfo.setAttachLength(size);
attachinfo.setContentType(".docx");
attachService.addAttach(attachinfo, content);
custom.put("attachGuid", rowguid);
custom.put("filename", docName);
jsonObj.put("custom", custom);
status.put("text", "保存成功!");
status.put("code", 1);
jsonObj.put("status", status);
//1标识为输出pdf文件
if ("1".equals(pdf)) {
//输出pdf
printPdf(attachService, rowguid);
custom.put("attachGuid", "pdf_" + rowguid);
}
return jsonObj;
}
catch (IOException e) {
e.printStackTrace();
}
jsonObj.put("custom", "error");
status.put("text", "保存失败!");
status.put("code", 0);
jsonObj.put("status", status);
return jsonObj;
}
catch (Exception e) {
e.printStackTrace();
}
custom.put("attachGuid", rowguid);
custom.put("filename", docName);
jsonObj.put("custom", custom);
status.put("text", "保存成功!");
status.put("code", 1);
jsonObj.put("status", status);
return jsonObj;
}
/**
*
* [转pdf]
* @param attachService
* @param rowguid
* @param docName
* @param path
* @param in
* @throws FileNotFoundException
* @throws IOException
* @exception/throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
private void printPdf(IAttachService attachService, String rowguid)
throws FileNotFoundException, IOException {
//pdf无附件id
String pdfrowguid = "pdf_" + rowguid;
FrameAttachInfo frameAttachInfo = attachService.getAttachInfoDetail(rowguid);
FrameAttachInfo framePdfAttachInfo = attachService.getAttachInfoDetail(pdfrowguid);
if (StringUtil.isNotBlank(framePdfAttachInfo)) {
attachService.deleteAttachByAttachGuid(pdfrowguid);
}
framePdfAttachInfo = new FrameAttachInfo();
framePdfAttachInfo.setAttachGuid(pdfrowguid);
framePdfAttachInfo.setAttachFileName(EpointDateUtil.convertDate2String(new Date(), "yyyyMMddhhmmss") + ".pdf");
framePdfAttachInfo.setAttachStorageGuid(pdfrowguid);
framePdfAttachInfo.setContentType(".pdf");
// 将word转pdf
String licenseName = ClassPathUtil.getClassesPath() + "EpointAsposeWords.lic";
try {
License license = new License();
if (license !=null) {
license.setLicense(licenseName);
}
Document document = new Document(attachService.getInputStreamByInfo(frameAttachInfo));
FontSettings.setFontsFolder(ClassPathUtil.getDeployWarPath() + "fonts" + File.separator, true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//设置字体,避免在Linux上字体乱码
FontSettings.setFontsFolder((ClassPathUtil.getDeployWarPath()+"WEB-INF/fonts/").replace("/",File.separator), true);
document.save(outputStream, SaveFormat.PDF);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
framePdfAttachInfo.setAttachLength((long) inputStream.available());
attachService.addAttach(framePdfAttachInfo, inputStream);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* [文件内容写入]
* @param bytes 二进制流
* @param filePath 输出路径
* @param fileName 文件名
* @exception/throws [Exception] [文件找不到]
* @see [类、类#方法、类#成员]
*/
public void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
String path =filePath + File.separator + fileName;
file = FileManagerUtil.createFile(path);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (bos != null) {
try {
bos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 本地文件(图片、excel等)转换成Base64字符串
*
* @param imgPath
*/
public static String convertFileToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
Base64Util.encode(data);
// 对字节数组进行Base64编码,得到Base64编码的字符串
String base64Str = Base64.encodeBase64String(data);
return base64Str;
}
/**
*
* [保存电子签名]
* @param params
* @return
* @exception/throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public JSON signatureSave(String params) {
JSONObject json = JSON.parseObject(params);
JSONObject jsonObj = new JSONObject();
JSONObject status = new JSONObject();
JSONObject custom = new JSONObject();
String yewuguid = json.get("yewuguid").toString();
String danweitype = json.get("danweitype").toString();
String directory = json.get("directory").toString();
String base64 = json.get("base64").toString();
String basePath = ClassPathUtil.getDeployWarPath() + "AttachStorage" + File.separator + directory
+ File.separator + yewuguid + File.separator + danweitype + File.separator;
String photoname="";
if (StringUtil.isNotBlank(danweitype)) {
photoname = danweitype + ".png";
byte[] photobyte = Base64.decodeBase64(base64);
// 原图片的数据流
ByteArrayInputStream sgbais = new ByteArrayInputStream(photobyte);
FileManagerUtil.deleteFile(basePath);
File srcfile = FileManagerUtil.createFile(basePath + photoname);
// 将原图片的数据流写入原文件
FileManagerUtil.writeContentToFileByStream(basePath, photoname, sgbais);
BufferedImage image;
try {
image = ImageIO.read(FileManagerUtil.createFile(basePath + photoname));
ImageIO.write(image, "png", srcfile);
}
catch (IOException e) {
e.printStackTrace();
}
}
custom.put("attachGuid", yewuguid);
custom.put("filename", photoname);
jsonObj.put("custom", custom);
status.put("text", "保存成功!");
status.put("code", 1);
jsonObj.put("status", status);
return jsonObj;
}
/**
* 获取临时文件中保存的签字图片
*
* @param basePath
* @param photoname
* @param dataMap
* @param leftOffset
* 签字距离左边的距离
* @param topOffset
* 签字图片距离上方的距离
* @return
*/
public Map<String, Object> getSignature(String basePath, String photoname, Map<String, Object> dataMap,
int leftOffset, int topOffset, String pictype, FileInputStream fis) {
File file = FileManagerUtil.createFile(basePath + photoname + ".png");
if (FileManagerUtil.isExistFileDir(basePath, false)) {
try {
BufferedImage image = ImageIO.read(file);
if (image != null) {
if (fis == null) {
fis = new FileInputStream(file);
}
HashMap<String, Object> map = new HashMap<>();
map.put("width", image.getWidth());
map.put("height", image.getHeight());
map.put("leftOffset", leftOffset);
map.put("topOffset", topOffset);
map.put("type", "png");
map.put("stream", fis);
dataMap.put(pictype, map);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
return dataMap;
}
@SuppressWarnings("resource")
public InputStream saveInputStream(String filepath) throws IOException {
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(filepath);
byte[] buf = FileManagerUtil.getContentFromInputStream(fileInputStream);
ByteArrayInputStream content = new ByteArrayInputStream(buf);
return content;
}
}