您的位置:首页 > 编程语言 > Java开发

java转word含图片 (选项中的图片也显示了)

2017-03-29 00:00 246 查看
摘要: 选项只考虑纯图片没有考虑文字 数据格式是
<img src="c:/xxx/xxx/xxx041.jpg"/>;<img src="c:/xxx/xxx/xxx042.jpg"/>

代码如下
@SuppressWarnings("unchecked")
public String exportWord(){

//清除错误和提示消息
this.clearErrorsAndMessages();

//map得到用户编号
@SuppressWarnings("unused")
Map session = ActionContext.getContext().getSession();

//获得数据集
QuestionLibrary questionLibrary=this.appraiseModelFactoryFacade.getCriterionModelFactory().findQuestionLibraryById(actionForm.getQuestionLibraryId());

//得到response对象
HttpServletResponse response = ServletActionContext.getResponse();

//定义A4页面大小
Rectangle rectPageSize = new Rectangle(PageSize.A4);

//定义Document对象
Document document = new Document(rectPageSize);

try{

//设置返回头
response.setContentType("application/vnd.ms-word");
response.setHeader("Content-Disposition","attachment;filename=\""+URLEncoder.encode(questionLibrary.getName()+".doc", "UTF-8")+"\"");
response.setHeader("Cache-Control","must-revalidate,post-check=0,pre-check=0");
response.setHeader("Pragma","public");
response.setDateHeader("Expires", 0);

RtfWriter2.getInstance(document, response.getOutputStream());

document.open();

//中文字体
// BaseFont bfChinese=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
BaseFont bfChinese = BaseFont.createFont("C:\\Windows\\Fonts\\simkai.ttf", BaseFont.IDENTITY_H , BaseFont.EMBEDDED);
//设置加粗、字号
Font fontChinese=new Font(bfChinese,14,Font.HELVETICA);

//设置正常字体、字号
Font fontChinese2 = new Font(bfChinese,12,Font.NORMAL);

//设置加粗、字号
Font fontChinese3 = new Font(bfChinese,12,Font.HELVETICA);

//设置标题名称写入并集中
Paragraph title =new Paragraph(questionLibrary.getName()+"题库中所有题目",fontChinese);
//设置段前间距
title.setAlignment(1);
document.add(title);

// //将题库名称写入并集中
// Paragraph paragraphTestPaper =new Paragraph(questionLibrary.getName(),fontChinese);
//

// paragraphTestPaper.setSpacingBefore(15f);
//

// //设置段后间距
// paragraphTestPaper.setSpacingAfter(5f);
//
// //居中 setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。
// paragraphTestPaper.setAlignment(1);
//

// document.add(paragraphTestPaper);

int i = 0;

int j = 0;

//定义选项
String option = "";

//定义答案
String anwer = "";

//定义题目
String questionName = "";

//得到题目集合
ArrayList<QuestionExtend> questionList= this.appraiseModelFactoryFacade.getCriterionModelFactory().findQuestionList(actionForm.getQuestionLibraryId() );
//获取识图题 测试展示效果
//ArrayList<QuestionExtend> questionList= this.appraiseModelFactoryFacade.getCriterionModelFactory().findQuestionListByshitu(actionForm.getQuestionLibraryId() );
//依次得到每道题目
for (QuestionExtend question : questionList){

j++;

if("案例分析题".equals(question.getTx())){
//过滤掉案例分析题
j--;
}else{

3ff0

if(question.getParentId() != null || "".equals(question.getParentId()) ){

// //通过子题的 parentId 得到题干内容 并进行截取替换
List<Question> questions = this.appraiseModelFactoryFacade.getCriterionModelFactory().findQuestionByParentId(question.getParentId());
for(Question question2 : questions) {
if(Pattern.compile(question2.getName()).matcher(question.getName()).find()){
questionName = question.getName() ;
}else{
questionName =question2.getName() + question.getName() ;
}
}
questionName = question.getName() + "" ;
}
questionName = j + ". " +question.getName();
//如果是判断题在后边加上括号
if (question.getTx().equals("判断题")) {

questionName = questionName + "  (  )";
}
//保存原来题目 为后面显示图片截取图片地址
String  questionNameByReplace = questionName;
int a = 1;
while (Pattern.compile("<img(.*?)>").matcher(questionNameByReplace).find()) {
questionNameByReplace = questionNameByReplace.replaceFirst("<img(.*?)>", "<"+ a +">");
a++;
}
//将题目和题号
Paragraph paragraphTestPaperQuestion = new Paragraph(questionNameByReplace,fontChinese2);

//设置段前间距
paragraphTestPaperQuestion.setSpacingBefore(15f);

//设置段后间距
paragraphTestPaperQuestion.setSpacingAfter(5f);

document.add(paragraphTestPaperQuestion);

String  imgpath ="";
//图片保存的绝对路径 盘符 指定为 C盘
String  imgpath1 ="C:";
List<String> imageString = getImgPathListByName(questionName);
//截取图片地址后将 正则匹配后的内容返回给 questionName
questionName = questionNameByReplace;
Iterator<String> iterator = imageString.iterator();
int b = 1;
while (iterator.hasNext()) {
imgpath = (String) iterator.next();
/* 测试添加一张图片 */
int z = 0 ;
Image img = Image.getInstance("c:\\b.jpg");
try {
img = Image.getInstance(imgpath1+imgpath);
z++;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(z == 0){
img = Image.getInstance("c:\\b.jpg");
}
}

//img.scaleAbsolute(60, 60);// 直接设定显示尺寸
//img.setAlignment(Image.LEFT);// 设置图片显示位置
//img.scaleAbsolute(60, 60);// 直接设定显示尺寸
img.scalePercent(100);//表示显示的大小为原尺寸的50%
//img.scalePercent(25, 12);//图像高宽的显示比例
document.add(img);
Paragraph paragraphTestPaperQuestion1 = new Paragraph("<"+ b +">",fontChinese2);
document.add(paragraphTestPaperQuestion1);
b++;
}

//判断是否是单选题、多选题
if (question.getTx().equals("识图题") || question.getTx().equals("多选题") || question.getTx().equals("单选题")|| question.getTx().equals("计算题")) {
//判断是否有选项
if(question.getOptions() == null || "".equals(question.getOptions())){
option = option + "";
}else{
String[] optionArray = question.getOptions().split("\\$;\\$");

//依次得到每个选项
for (int k = 0; k < optionArray.length; k++){
//选项中的图片显示
if(Pattern.compile("<img(.*?)>").matcher(optionArray[k]).find()){
//List<String> list = getImgPathListByName(optionArray[k]);
String  optionImgPath ="";
//图片保存的绝对路径 盘符 指定为 C盘
String  optionImgPath1 ="C:";
List<String> optionImageString = getImgPathListByName(optionArray[k]);
//截取图片地址后将 正则匹配后的内容返回给 questionName
//questionName = questionNameByReplace;
Iterator<String> optionIterator = optionImageString.iterator();
while (optionIterator.hasNext()) {
optionImgPath = (String) optionIterator.next();
/* 测试添加一张图片 */
int z = 0 ;
Image img = Image.getInstance("c:\\b.jpg");
try {
img = Image.getInstance(optionImgPath1+optionImgPath);
z++;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(z == 0){
img = Image.getInstance("c:\\b.jpg");
}
}

//img.scaleAbsolute(60, 60);// 直接设定显示尺寸
//img.setAlignment(Image.LEFT);// 设置图片显示位置
//img.scaleAbsolute(60, 60);// 直接设定显示尺寸
img.scalePercent(100);//表示显示的大小为原尺寸的50%
//img.scalePercent(25, 12);//图像高宽的显示比例
option = option + StringUtil.numberToString(k) + ".  ";

//将选项加入
Paragraph paragraphTestPaperQuestionOption = new Paragraph(option,fontChinese2);

//设置段前间距
paragraphTestPaperQuestionOption.setSpacingBefore(10f);

//设置段后间距
paragraphTestPaperQuestionOption.setSpacingAfter(5f);

document.add(paragraphTestPaperQuestionOption);
document.add(img);
}
}else{
option = option + StringUtil.numberToString(k) + ".  " +  optionArray[k] + ";  ";
//将选项加入
Paragraph paragraphTestPaperQuestionOption = new Paragraph(option,fontChinese2);

//设置段前间距
paragraphTestPaperQuestionOption.setSpacingBefore(10f);

//设置段后间距
paragraphTestPaperQuestionOption.setSpacingAfter(5f);

document.add(paragraphTestPaperQuestionOption);
}
//将选项清空,以备下一题使用
option = "";
}
}

}
anwer = "标准答案: ";

//判断是否为判断题
if (question.getTx().equals("判断题")){

//如果答案为B则为错,否则为对
if (question.getAnswer().equals("B")){

anwer = anwer + "错";
}

if (question.getAnswer().equals("A")){

anwer = anwer + "对";
}

//如果是案例分析题  将标准答案隐藏
}

// else if(question.getTx().equals("案例分析题")){
// anwer = "";
// }
else{

anwer = anwer + question.getAnswer();
}

Paragraph paragraphAnwer = new Paragraph(anwer,fontChinese3);

//设置段前间距
paragraphAnwer.setSpacingBefore(10f);

//设置段后间距
paragraphAnwer.setSpacingAfter(5f);

document.add(paragraphAnwer);

//将答案清空,以备下一题使用
anwer = "";
}

//每个题型之间空一行
document.add(new Paragraph(""));
}
//将题号清零,以备下一题型重新排号
j = 0;
i++;

// }
}catch (Exception e) {

e.printStackTrace();
}

//关闭对象流
document.close();

return null;
}
/**
*通过正则表达式截取图片的路径
* imgpath 提取前的内容
* [@return](https://my.oschina.net/u/556800) 图片地址的集合
*/
public static List<String> getImgPathListByName(String imgpath){
List<String> list = new ArrayList<String>();
String[] imageString = null;

//正则表达式  截取 <img >中间的内容
String  regstr = "<img[^<]*>";
Pattern pt = Pattern.compile(regstr);
Matcher matcher = pt.matcher(imgpath);

while(matcher.find())
{
//得到双引号之间的内容
String  regstr1 = "/[^\"]*\"";
String  img = matcher.group();
Pattern pt1 = Pattern.compile(regstr1);
Matcher ma = pt1.matcher(img);
while(ma.find())
{
img = ma.group();
imageString = img.split("\"");
for (int i = 0; i < imageString.length; i++) {
list.add(imageString[i]);
}
}
}

return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息