Use maven to import dependencies for the jar package used
<!--PDF-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.3</version>
</dependency>
<!--PDF-->
/**
* Export to PDF
*
* @param
* @return
* @throws BusinessException
*/
public static String specialExportPDF(String moduleName, String fileName, Map<String, String> dataMap) throws BusinessException {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
//dataMap to fill in the data file of the template
//Set the template device method and path, FreeMarker supports multiple template loading methods. Can re-servlet, classpath, database loading,
//Here our template is placed under the template package
configuration.setDirectoryForTemplateLoading(new File(FileUtil.getWebRootPath() + "template//import//" + moduleName));
Template t = null;
try {
//.ftl is the template to be loaded
t = configuration.getTemplate(fileName + ".ftl");
} catch (IOException e) {
e.printStackTrace();
}
fileName = fileName + DateUtil.datetimeToNoSplashString(DateUtil.now()) + ".html";
String outputFilePath = getOutputXlsTempFilePath(fileName);
Writer out = null;
FileOutputStream fos = null;
try {
{
//Output document path and name
fos = new FileOutputStream(outputFilePath);
OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
//This place is indispensable to the encoding of the stream. When using main() alone, it should be ok, but if it is a web request to export, the word document will not be opened after the export, and the package XML file is wrong. The main reason is that the encoding format is incorrect and cannot be parsed.
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
t.process(dataMap, out);
String html = readString(outputFilePath);
//Create pdf
ItextUtil.createPdf(html,outputFilePath);
out.flush();
out.close();
fos.close();
//Delete html file
File file = new File(outputFilePath);
file.delete();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (TemplateException e1) {
e1.printStackTrace();
}
//4. Return the download address of the word file
return getDownloadXlsTempFileUrl(fileName.replace("html","pdf"));
} catch (Exception e) {
throw new BusinessException(e.getMessage(), e);
}
}
/**
* Read the file and convert it to a string
* @param FilePath
* @return
*/
private static String readString(String FilePath){
if(PubUtil.isEmpty(FilePath))return "";
int len=0;
StringBuffer str=new StringBuffer("");
File file=new File(FilePath);
try {
FileInputStream is=new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String line=null;
while( (line=in.readLine())!=null ){
if(len != 0) {// Deal with the problem of newlines
str.append("rn"+line);
}else{
str.append(line);
}
len++;
}
in.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
/** PDF generation tool **/
package com.etom.ebihm.utils;
import com.itextpdf.text.*;
//import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.ElementHandlerPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfWriter;
//import com.lowagie.text.html.simpleparser.HTMLWorker;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.List;
//import java.util.ArrayList;
/**
* Generate PDF tools
* Created by Administrator on 2017/8/21.
*/
public class ItextUtil {
//The html here is to convert html into a string, non-html file path
public static void createPdf(String html,String outPath) {
ItextUtil ih = new ItextUtil();
ih.htmlCodeComeFromFile(html,outPath.replace("html","pdf"));
}
public void htmlCodeComeFromFile(String html, String pdfPath) {
Document document = new Document();
try {
/*StyleSheet st = new StyleSheet();
st.loadTagStyle("body", "leading", "16,0");*/
PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
Paragraph context = new Paragraph( );
ElementList elementList = parseToElementList(html, null);
// Solve the Chinese problem
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
context.setFont(FontChinese);
for (com.itextpdf.text.Element element1 : elementList) {
context.add(element1);
}
document.add(context);
document.close();
System.out.println("Document created successfully");
}catch(Exception e) {
e.printStackTrace();
}
}
public ElementList parseToElementList(String html, String css) throws IOException {
// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
if (css != null) {
CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(css.getBytes()));
cssResolver.addCss(cssFile);
}
// HTML
MyXMLWorkerHelper.MyFontsProvider fontProvider = new MyXMLWorkerHelper.MyFontsProvider();
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.autoBookmark(false);
// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end);
CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
// XML Worker
XMLWorker worker = new XMLWorker(cssPipeline, true);
XMLParser p = new XMLParser(worker);
p.parse(new ByteArrayInputStream(html.getBytes()));
return elements;
}
}
/** Rewrite the XMLWorkerHelper class and use a custom font **/
package com.etom.ebihm.utils;
import com.etom.framework.constant.SystemConstants;
import com.etom.framework.utils.FileUtil;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import java.io.File;
/**
* Created by Administrator on 2017/8/21.
*/
public class MyXMLWorkerHelper {
public static class MyFontsProvider extends XMLWorkerFontProvider {
public MyFontsProvider() {
super(null, null);
}
@Override
public Font getFont(final String fontname, String encoding, float size, final int style) {
String fntname = fontname;
if (fntname == null) {
fntname = "Song Ti";
}
Font font = new Font();
String font_cn = getChineseFont();
BaseFont bf;
try {
bf = BaseFont.createFont(font_cn+",1", //Note that there is one, 1
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
font = new Font(bf,12);
font.setFamily("SYMBOL");
}catch (Exception e){
e.printStackTrace();
}
//return super.getFont(fntname, encoding, size, style);
return font;
}
}
/**
* Get Chinese font location
* @return
* @author xxj April 28, 2017
*/
private static String getChineseFont(){
// Song Ti (corresponding to the property font-family: SimSun; /* Song Ti*/ in css)
/* String font1 ="C:/Windows/Fonts/simsun.ttc";
//Determine the system type and load the font file
java.util.Properties prop = System.getProperties();
String osName = prop.getProperty("os.name").toLowerCase();
System.out.println(osName);*/
//File file = new File(FileUtil.getRealPath(SystemConstants.PATH_PRE_WEBROOT+"://res/font/simsun.ttc"));
/*if (osName.indexOf("linux")>-1) {
font1="/usr/share/fonts/simsun.ttc";
}
if(!new File(font1).exists()){
throw new RuntimeException("The font file does not exist, which affects the Chinese display of exported pdf!"+font1);
}*/
//The font is not installed in the linux server, so the font is passed in the project resource, just get the project font
File file = new File(FileUtil.getRealPath(SystemConstants.PATH_PRE_WEBROOT+"://res/font/simsun.ttc"));
String font1 =FileUtil.getRealPath(SystemConstants.PATH_PRE_WEBROOT+"://res/font/simsun.ttc");
if(!file.exists()){
throw new RuntimeException("The font file does not exist, which affects the Chinese display of exported pdf!"+font1);
}
return font1;
}
}
.