Using eclispse as a development platform
Referenced jar package:
First:
How to start download in project JSP
/ *
* Generate pdf browsing page
* /
function downLoadToPDF (taskId) {
var rootpath = BaseContext + "/ DemoController / download? TaskId =" + taskId; // Access path
window.open (rootpath, "_blank"); // New Interface
}
Then enter this DemoController
/ * Background code for generating PDF
*/
public class TestPDFUtil {
public static void main (String [] args) {
String templateName = "template"; // The name of the template to be used
String targetPathRoot = "D: / temp /"; // The target location of the generated PDF
Map <String, Object> map = generateUnitOpenAccountApplicationData (); // The data needed to build the template, according to their own needs
try {
String path = PDFUtil.getPath (); // First get the project path Call the method
PDFUtil.generateToFile (path, ".. in the tool class ..... / "+ templateName +" .ftl ", path +" / images / ", map, targetPathRoot + templateName +" .pdf "); // Path ==》 According to the template file
System in your project . out.println ("Successful PDF generation!");
} catch (Exception e) {
e.printStackTrace ();
System.out.println ("Failed to generate PDF!");
}
}
Then comes the auxiliary tools:
package util.PDFUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.Locale;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
@SuppressWarnings("all")
public class PDFUtil {private static final Logger logger = LoggerFactory.getLogger(PDFUtil.class);
public static void generateToFile(String ftlPath,String fileName,String imageDisPath,Object data,String outputFile) throws Exception{
OutputStream out=null;
ITextRenderer render =null;
try{
String html=getPdfContent(ftlPath,ftlName,data);
out =new FileOutputStream(outputFile);
render = getRender ();
render.setDocumentFromString(html);
if(imageDiskPath != null && !imageDispath.equals("")){
// If there is a picture in html, the path of the picture uses the absolute path of the project. This is used as the root path
render.getSharedContext().setBaseURL("file:/"+iamgeDisPath);
}
render.layerout();
render.createPDF();
render.finishPDF();
render=null;
return out;
}catch(Exception e){
logger.error("Exception:",e);
throw e;}finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.error("Exception:",e);
throw e;
}
}
}}
// Get PDF content
public static String getPdfContent(String ftlPath,String ftlName,Object o) throws Exception {
return userTemplate(ftlPath,ftlName,o);
}
// Use freeMake to get html content
public static String useTemplate(String ftlPath,String ftlName,Object o)throws Exception {
String html =null;
Template tpl=getFreemakerConfig(ftlPath).getTemplate(ftlName);
tpl.setEcncoding("UTF-8");
StringWriter writer =newStringWriter();
tpl.process(o,writer);
writer.flush();
html=writer.toString();
return html;
}
// Get freemarker configuration
private static Configutation getFreemarkerConfig(String templatePath)throws IOException{
Configuration config=new Configuration();
config.setDirectoryForTemplateLoading(new File(templatePath));
config.setEncoding(Locale.CHINA,"utf-8");
return config;
}
public static ITextRenderer getRender() throws() DocumentException,IOException{
ITextRenderer render =new ITextRender();
String path =getPath();
// Add fonts to support Chinese font file path to find the right
render.getFontResolver().addFont(path+"../fonts/ARIALUNI.TTF",BaseFont,IDENTITY_H,BaseFont.NOT_EMBEDDED);
render.getFontResolver().addFont(path+"../fonts/SIMSUNB.TTF",BaseFont,IDENTITY_H,BaseFont.NOT_EMBEDDED);
return render;
}
// Get the project root path
public static String getPath(){
// return PDFUtil.class.getResource ("") .getPath () .substring (1): // return class path (path where current class is)
// return PDFUtil.class.getResource ("/"). getPath (). substring (1); // Return root path (root path after compilation)
return PDFUtil.class.getClassLoader().getResource("").getPath();
}
}
For the required methods in the tool class, you must see the path problem clearly, otherwise you will not be able to access the data, so you must adjust the breakpoint when debugging to find a project path that matches your own.
Then store data, use map collection to store
/ **
* Add various parameters required by the page
* @param patient
* @param task
* @param mettTask
* @param request
* @return
* /
private Map generateUnitOpenAccountApplicationData (Patient patient,
Task task, List <MettTask> mettTask, List <ScaleTask> scaleTask,
HttpServletRequest request, List <CemtTask> cemtTask) {
Map <String, Object> total_map = new HashMap <String, Object> (); // Store the overall data
Map <String, Object> map = new HashMap <String , Object> (); // Store the overall data
map = Word_stage_Util.createModel (patient, task); // Get the data and integrate it. This is to select the data to be stored and read and write the database
. map); // Total
return total_map;
}
Html interface display of download template
FTL internal preview:
Font requirements:
*** This technology is supported by LHF, jar packages and fonts will be uploaded later