网上很多都是自己写一个servlet,然后url改成自己的。但是servlet只支持IE,在google浏览器上得不到参数值,所以改造servlet成为action。其中需要引入三个jar包。三个jar包在附件。
package com.creditease.ccsp.action;
import java.io.StringReader;
import javax.servlet.ServletOutputStream;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.fop.svg.PDFTranscoder;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
@Namespace("/manage")
@ParentPackage("manage")
public class ImageExportAction extends ActionImpl{
/**
*
*/
private static final long serialVersionUID = 7547110498655678209L;
@Action(value = "exportChart", results = { @Result(name = "success", type = "json") })
public String execute() throws Exception {
request.setCharacterEncoding("utf-8");//注意编码
String type = request.getParameter("type");
String svg = request.getParameter("svg");
ServletOutputStream out = response.getOutputStream();
if (null != type && null != svg){
svg = svg.replaceAll(":rect", "rect");
String ext = "";
Transcoder t = null;
if (type.equals("image/png")) {
ext = "png";
t = new PNGTranscoder();
} else if (type.equals("image/jpeg")) {
ext = "jpg";
t = new JPEGTranscoder();
} else if (type.equals("application/pdf")) {
ext = "pdf";
t = new PDFTranscoder();
} else if (type.equals("image/svg+xml")) {
ext = "svg";
}
response.addHeader("Content-Disposition", "attachment; filename=chart."+ext);
response.addHeader("Content-Type", type);
if (null != t){
TranscoderInput input = new TranscoderInput(new StringReader(svg));
TranscoderOutput output = new TranscoderOutput(out);
try {
t.transcode(input,output);
} catch (TranscoderException e){
out.print("Problem transcoding stream. See the web logs for more details.");
e.printStackTrace();
}
} else if (ext == "svg"){
out.print(svg);
} else {
out.print("Invalid type: " + type);
}
} else {
response.addHeader("Content-Type", "text/html");
out.println("Usage:\n\tParameter [svg]: The DOM Element to be converted.\n\tParameter [type]: The destination MIME type for the elment to be transcoded.");
}
out.flush();
out.close();
return NONE;
}
@Override
public Object getModel() {
// TODO Auto-generated method stub
return null;
}
}
?