html 字符串 生成pdf 完美解决中文不显示
//maven
<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>

 

 

//java

 

package com.leoodata.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.leoodata.entity.Report;
import org.jsoup.Jsoup;
import java.io.*;
import java.nio.charset.Charset;
import static java.awt.SystemColor.info;

/**
 * User: 杨永生
 * Date: 15:45 2018/4/10
 * Email: kevin@hiibook.com
 */

public class PDFReport {
public static void htmlToPDF(Report report,String fileNameAndURL) { try { //创建html String reportData = " <tr style='border-bottom: 1px solid black;'>\n" + " <td>"+report.getName()+"</td>\n" + " <td>"+report.getPhone()+"</td>\n" + " <td>"+report.getIdentificationNuber()+"</td>\n" + " </tr>\n" ;
String body = "<h1 style='text-align: center'>报告</h1>\n" + "<div style='width:100%;margin:0 auto;'>\n" + "<table border='1px' style='border: 1px solid black;width:100%;text-align: center;border-collapse:collapse;'>\n" + " <thead>\n" + " <tr style='border: 1px solid black;'>\n" + " <th>姓名</th>\n" + " <th>电话</th>\n" + " <th>身份证号</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + // reportData+ " </tbody>\n" + "</table>\n" + "</div>";
StringBuilder html = new StringBuilder(); html.append("<html>"); html.append("<body style='font-size:20px;font-family:SimSun;'>"); html.append(body); html.append("</body>"); html.append("</html>");
InputStream is = new ByteArrayInputStream(html.toString().getBytes("utf-8"));
File files=new File(fileNameAndURL); //打印查看上传路径 System.out.println(fileNameAndURL); if(!files.getParentFile().exists()){ files.getParentFile().mkdirs(); }
OutputStream os = new FileOutputStream(fileNameAndURL); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, os); document.open(); // 将html转pdf XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, Charset.forName("UTF-8")); document.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Report report=new Report(); String url= "E:/HiibookIntellijProject/svn2/leoodata/target/leoodata/static/upload/report/余*157**446732018_04_11_17_37_21_891.pdf"; htmlToPDF(report,url); } }