HTML to PDF, multi-web splicing
1. Due to the business needs of the company, I want to assemble and seal some web pages. The original HTML2PDfJS can not be used in too many pages or 404. 2. Search for the wkHTMLTopdf official website to download the required version (Windows, centos) 3. Will need to convert web links to arrays, using urls. OpenStream determines whether a web page is accessible to avoid errors during the conversion process. 4. Use PDF splicing method in IText package to splice converted PDF 5. Finally, delete the generated temporary files (to avoid taking up server storage space)
String htmltext="1.html,2.html";
String[] paths=htmltext.split(",");
String pdfpaths="";
String tmppath=System.getProperty("java.io.tmpdir") +"\\pdfsave\\";
for (int i=0; i<paths.length; i++){if(!"".equals(paths[i])&&paths[i]! =null){
String pdfpath=tmppath+ Utils.uuid()+".pdf";
if (!new File(tmppath).isDirectory()) {
boolean b=new File(tmppath).mkdirs();
System.out.println("New upload temporary folder");
}
if(checkUrlContent(paths[i])){
htmlToPdf(paths[i],pdfpath);
if(pdfpaths.equals("")){
pdfpaths=pdfpath;
}else {
pdfpaths=pdfpaths+","+pdfpath; }}else {
continue;
}
}
}
String[] all=pdfpaths.split(",");
String pdfpath=System.getProperty("java.io.tmpdir") +"\\pdfsave\\"+ Utils.uuid()+".pdf";
boolean a=mergePdfFiles(all,pdfpath);
if(a){
DownloadFileUtils.getExcel(pdfpath,"PDF" file.,response);
File f=newFile(pdfpath); f.delete(); }}public static void htmlToPdf(String htmpath,String pdfpath){
try{
Process process=Runtime.getRuntime().exec(getCommand(htmpath,pdfpath));
// call CMD to write whatever you want (getCommand)
process.waitFor();
}catch(Exception e){
throw newRuntimeException; }}public static boolean checkUrlContent(String urlString){
long lo=System.currentTimeMillis();
URL url;
try {
url=new URL(urlString);
InputStream in=url.openStream();
return true;
} catch (Exception e) {
return false; }}public static boolean mergePdfFiles(String[] files, String newfile) {
boolean retValue = false;
Document document = null;
try {
PdfReader reader1 = new PdfReader(files[0]);
document = new Document(reader1.getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
document.open();
for (int i = 0; i < files.length; i++) {
PdfReader reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
reader1.close();
copy.close();
retValue = true;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("End of execution");
document.close();
for (int i=0; i<files.length; i++){ File f=newFile(files[i]); f.delete(); }}return retValue;
}
Copy the code