java导出html静态页面,包含页面中引用的css、js
js代码如下
/**
*
*/
/**
* 导出html report function
*/
function printHtml(){
var json = getJson();
var encodejson = encodeURIComponent(encodeURIComponent(JSON.stringify(json)))
// 获取当前显示页面(包括时间选项,按钮操作 和 下方的报表)
var urlStr = document.documentElement.outerHTML;
// 处理特殊字符<,>,//
urlStr = urlStr.replace(new RegExp("<", "g"), "<").replace(new RegExp(">", "g"), ">").replace(/\//g, "?");
// exportHTMLInfo.showURLInfo( urlStr,"/Report", "", "wq",callBack);
$.post("./auditreport/printHtml.do",{
'urlStr':urlStr,
'rootPath':'/ta-server',
'sysPath':"",
'zipType':'report',
'encodejson':encodejson,//导出html是将系统中 书目录 的锚配置的路径传后台replace掉 此参数为paramJson的值
'dbId':$("#dbId").text()
},function(returnInfo){
loaderHide();
var returnInfo= eval(returnInfo);
del_returnInfo=returnInfo;
if(returnInfo[0]){
var url = '/ta-server'+returnInfo[2];
// IE
if (!!window.ActiveXObject || "ActiveXObject" in window) {
// Loading.hide(); // loading层
loaderHide();
window.location.href(url);
tips = "文件下载结束";
// 其他浏览器
} else {
var opened = window.open(url);
if (!opened) {
// Loading.hide(); // loading层
loaderHide();
tips = "下载失败,请调整浏览器安全设置!";
} else {
// Loading.hide(); // loading层
loaderHide();
tips = "文件下载结束";
}
}
$("#modal-demo").modal("hide");
}else{
$("#modal-demo").modal("hide");
tips = "文件下载失败";
$.Huimodalalert(tips,2000);
}
$('#tipMessage').html(tips);
$("#export-tip").modal("show");
});
}
注意:需要在导出的html中加入<div class=\"exportHTML breakLine\"></div>标记位,具体的java导出类如下,代码大概逻辑思维是,先将导入引用的js、css从服务器上下载下来放到index文件夹中,然后将html中src的路径全部全部改为/index/xxx.js
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.esafenet.ta.common.paramconfig.ParamConfig;
import com.esafenet.ta.da.auditreport.constants.AuditReportConstant;
public class ExportHTMLInfo {
// private static String FILE_PATH = "/usr/local/tomcat/webapps";
// private static String FILE_PATH =
// "E:/MY_SVN/linux-scripts/数据库审计开发/dbaudit/software/tomcat/webapps";
// private static String FILE_PATH = "E:/apache7/webapps";
private String FILE_PATH = ParamConfig.class.getResource("/").getPath()
.replace("classes/", "").replace("/WEB-INF/", "");
public String[] showURLInfo(String urlStr, String rootPath, String sysPath,
String zipType,String encodejson,String dbId) {
// /E:/apache7/webapps/ta-server/download/
String[] returnInfo = new String[4];
String temStr = urlStr;
temStr = temStr.replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("\\?", "/");
// <base href="http://localhost:8080/ta-server/"> 去掉声明的href
int index = temStr.indexOf("<base");
int endIndex = temStr.indexOf("<title>");
String base = temStr.substring(index, endIndex);
temStr = temStr.replace(base, "");
//auditreport/toAuditReport.do?sourceType=2¶mJson=
// int a = temStr.indexOf(encodejson);
// int b = temStr.indexOf("auditreport/toAuditReport.do/sourceType=2&paramJson=");
temStr = temStr.replaceAll(encodejson, "");
temStr = temStr.replaceAll("auditreport/toAuditReport.do/sourceType=1&tabConfig=1", "index.html");
temStr = temStr.replaceAll("auditreport/toAuditReport.do/sourceType=2&dbId="+dbId+"&paramJson=", "index.html");
// <base href="http://localhost:8080/ta-server/"> 去掉声明的href end
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String createTime = sdf.format(date);
rootPath = FILE_PATH.substring(FILE_PATH.lastIndexOf("/"),
FILE_PATH.length());
FILE_PATH = FILE_PATH.substring(0, FILE_PATH.lastIndexOf("/"));
String rootFilePath = FILE_PATH + rootPath; // "E:/apache7/webapps/ROOT"
String downloadPath = "/download/";
String createNewFilePath = downloadPath + createTime + zipType; // "/download/20171030195425AllDBDaily"
String zipTargetFile = rootFilePath + downloadPath + createTime // "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily.zip"
+ zipType + ".zip";
String strName = rootFilePath + createNewFilePath + "/"; // "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/"
String fileName = strName + "index.html"; // "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.html"
String directoryName = strName + "index"; // "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.htmlindex"
checkFileExist(strName, fileName, directoryName); // 检查文件是否存在
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/" strName
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.html"
// fileName
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.htmlindex"
// directoryName
// "/ROOT" rootPath
// "" sysPath
boolean fileWrite = writeQueryInfo(fileName, temStr, strName, rootPath,
sysPath);
if (fileWrite) {
boolean flagZip = zip(zipTargetFile, strName);
String temPath = rootFilePath + createNewFilePath + ".zip";
boolean fileExist = isFileExist(temPath);
if ((flagZip) && (fileExist)) {
returnInfo[0] = "true";
} else {
returnInfo[0] = "false";
}
returnInfo[1] = temPath;
returnInfo[2] = (createNewFilePath + ".zip");
returnInfo[3] = strName;
} else {
returnInfo[0] = "false";
returnInfo[1] = rootFilePath;
returnInfo[2] = (createNewFilePath + ".zip");
returnInfo[3] = strName;
}
return returnInfo;
}
private boolean isFileExist(String filePath) {
boolean flag = false;
File temFile = new File(filePath);
flag = temFile.exists();
return flag;
}
private void checkFileExist(String strName, String fileName,
String directoryName) {
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/" strName
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.html"
// fileName
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.htmlindex"
// directoryName
File mainFile = new File(strName);
File temFile = new File(fileName);
File temDirectory = new File(directoryName);
boolean isMainFileExist = mainFile.exists();
boolean isFileExist = temFile.exists();
boolean isDirectoryExist = temDirectory.exists();
try {
if (!isMainFileExist) {
mainFile.mkdirs();
}
if (!isFileExist) {
temFile.createNewFile();
}
if (!isDirectoryExist) {
temDirectory.mkdirs();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean zip(String zipFileName, String inputFileName) {
boolean flag = zip(zipFileName, new File(inputFileName));
return flag;
}
private boolean zip(String zipFileName, File inputFile) {
boolean flag = false;
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
flag = zip(out, inputFile, "");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
private boolean zip(ZipOutputStream out, File f, String base) {
FileInputStream in = null;
try {
int i;
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base + "/";
for (i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
}
}
}
private boolean writeQueryInfo(String fileName, String strInfo,
String saveFilePath, String proName, String sysPath) {
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/" strName
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.html"
// fileName
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/index.htmlindex"
// directoryName
// "/ROOT" rootPath
// "" sysPath
// writeQueryInfo(fileName, temStr, strName, rootPath,sysPath);
OutputStreamWriter osw = null;
strInfo = changeCode(strInfo);
// strInfo 页面读取html的字符串
// saveFilePath
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/"
// proName "/ROOT"
// sysPath ""
// dealUrlQueryInfo(strInfo, saveFilePath, proName, sysPath);
// 该方法是将html截取组装为自己想要导出的部分 也就是报表+导航
strInfo = dealUrlQueryInfo(strInfo, saveFilePath, proName, sysPath);
try {
osw = new OutputStreamWriter(new FileOutputStream(fileName),
"utf-8");
int len = strInfo.length();
osw.write(strInfo, 0, len);
osw.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (osw != null) {
osw.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
private String changeCode(String strInfo) {
String[] dealStr = { "<HTML", "</HTML>", "<BODY", "</BODY>", "<LINK",
"<SCRIPT", "</SCRIPT>", "<DIV", "</DIV>", "DISPLAY" };
for (int i = 0; i < dealStr.length; i++) {
strInfo = strInfo.replaceAll(dealStr[i], dealStr[i].toLowerCase());
}
return strInfo;
}
private String dealUrlQueryInfo(String strInfo, String saveFilePath,
String proName, String sysPath) {
// strInfo 页面读取html的字符串
// saveFilePath
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/"
// proName "/ROOT"
// sysPath ""
String temStr = strInfo;
int index = checkNum(temStr, "<link");
String headFile = "";
if (index > 0) { // 判断获取的html串中有没有<link 有的话截取 没有不截取wq
headFile = temStr.substring(0, index).trim();
}
int linkIndex = checkNum(temStr, "<link");
int bodyInt = checkNum(temStr, "<body");
String cssFile = "";
if (linkIndex > 0) { // 判断获取的html串中有没有<link 有的话截取 没有不截取wq
cssFile = temStr.substring(linkIndex, bodyInt).trim();
}
int exportIndex = checkNum(temStr,
"<div class=\"exportHTML breakLine\"></div>");
int scriptIndex = checkNum(temStr, "<script");
String bodyFile = "<body>"
+ temStr.substring(exportIndex, scriptIndex).trim();
String jsFile = temStr.substring(checkNum(temStr, "<script")).trim();
cssFile = dealFilePath(cssFile, "<link ",
new String[] { "href", ".css" }, saveFilePath, proName, sysPath);
jsFile = dealFilePath(jsFile, "<script ",
new String[] { "src", ".js" }, saveFilePath, proName, sysPath);
// jsFile temStr.substring(checkNum(temStr, "<script")).trim();
// 就是body中引js的代码段
// "<script "
// new String[] { "src", ".js" }
// saveFilePath
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/"
// proName "/ROOT"
// sysPath
temStr = headFile + cssFile + bodyFile + jsFile;
return temStr;
}
private int checkNum(String targetStr, String numStr) {
return targetStr.indexOf(numStr);
}
private String dealFilePath(String filePath, String splitStr,
String[] linkStr, String saveFilePath, String proName,
String sysPath) {
// jsFile temStr.substring(checkNum(temStr, "<script")).trim();
// 就是body中引js的代码段
// "<script "
// new String[] { "src", ".js" }
// saveFilePath
// "E:/apache7/webapps/ROOT/download/20171030195425AllDBDaily/"
// proName "/ROOT"
// sysPath
String[] temFilePath = filePath.split(splitStr);
String fileStr = "";
for (int i = 1; i < temFilePath.length; i++) {
if (temFilePath[i].indexOf("BirtReportGeneration.js") <= -1) {
if ((temFilePath[i].indexOf(linkStr[0]) > -1)
&& (temFilePath[i].indexOf(".js/v=") <= -1)) {
if (temFilePath[i].indexOf("style=\"display: block") > -1) {
temFilePath[i] = temFilePath[i]
.replace("block", "none");
}
// pathStr <script
// src="./report-viewer/birt/ajax/lib/echarts.js"
// type="text/javascript"></script>
String pathStr = new StringBuilder().append(splitStr)
.append(temFilePath[i]).toString();
fileStr = fileStr
+ changeFilePath(pathStr, linkStr[0], linkStr[1],
linkStr[0], saveFilePath, proName, sysPath);
}
}
}
return fileStr;
}
private String changeFilePath(String pathStr, String linkStr,
String suffix, String breakStr, String saveFilePath,
String proName, String sysPath) {
// pathStr <script src="./report-viewer/birt/ajax/lib/echarts.js"
// type="text/javascript"></script>
// linkStr src
// suffix .js
// breakStr src
// saveFilePath E:/apache7/webapps/ROOT/download/20171101175548wq/
int temPathIndex = checkNum(pathStr, linkStr + "=\"");
int pathStrIndex = checkNum(pathStr, suffix + "\"");
String temPath = pathStr.substring(temPathIndex, pathStrIndex);
// temPath src="./dwr/interface/exportHTMLInfo
String[] temStr = temPath.split("\\/");
// temPath [src="., dwr, interface, exportHTMLInfo]
String useFile = temStr[(temStr.length - 1)] + suffix;
// useFile exportHTMLInfo.js
String targetPath = temPath + suffix + "\"";
// targetPath src="./dwr/interface/exportHTMLInfo.js"
String replacement = linkStr + "=\"./index/" + useFile + "\"";
// replacement src="./index/exportHTMLInfo.js"
// showTemPath(src="./dwr/interface/exportHTMLInfo.js",src,exportHTMLInfo.js,E:/apache7/webapps/ROOT/download/20171101175548wq/,/ROOT,"")
showTemPath(targetPath, breakStr, useFile, saveFilePath, proName,
sysPath);
pathStr = pathStr.replaceAll(targetPath, replacement);
return pathStr;
}
private void showTemPath(String path, String breakStr, String useFile,
String saveFilePath, String proName, String sysPath) {
// showTemPath(src="./dwr/interface/exportHTMLInfo.js",src,exportHTMLInfo.js,E:/apache7/webapps/ROOT/download/20171101175548wq/,/ROOT,"")
// path src="./dwr/interface/exportHTMLInfo.js"
// breakStr src
// useFile exportHTMLInfo.js
// saveFilePath E:/apache7/webapps/ROOT/download/20171101175548wq/
// proName /ROOT
// sysPath ""
String temFilePath = path.substring(breakStr.length() + 2,
path.lastIndexOf("\""));
if (!sysPath.equals("")) {
temFilePath = temFilePath.substring(proName.length());
}
// File f = new File(FILE_PATH + proName + temFilePath);
// //原代码需要加上传过来的项目名称路径
File f = new File(FILE_PATH + temFilePath);
if (f.exists()) {
BufferedInputStream bin = null;
OutputStream out = null;
try {
bin = new BufferedInputStream(new FileInputStream(f));
String targetPath = saveFilePath + "index/" + useFile;
File file = new File(targetPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
out = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte['?'];
while ((len = bin.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();
return;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bin != null) {
bin.close();
}
if (out != null) {
out.close();
}
} catch (Exception e2) {
}
}
}
}
public boolean deleteZipFile(String flag, String filePath,
String directoryPath) {
File dirName = new File(directoryPath);
boolean dirFlag = deleteDir(dirName);
File fileName = new File(filePath);
boolean fileFlag = fileName.delete();
return (dirFlag) && (fileFlag);
}
private boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void main(String[] args) {
File file = new File("D:/Test/www");
String[] a = file.list();
System.out.println(a);
File[] b = file.listFiles();
System.out.println(b);
System.out.println(file.hashCode());
deleteFile(file);
}
private static boolean deleteFile(File file) {
boolean a = file.isDirectory();
if (a) {
File[] fileArray = file.listFiles();
for (int i = 0; i < fileArray.length; i++) {
deleteFile(fileArray[i]);
}
}
return file.delete();
}
}