java 生成 pdf html转pdf 支持 中文 自定义模板

java 生成pdf

DEMO

开发过程中遇到的坑

/**
* 切记 css 要定义在head 里,否则解析失败
* css 要定义字体
* 字体中英文 https://www.cnblogs.com/chbyiming-bky/articles/9789869.html
* 例如宋体 style=“font-family:SimSun” 用 simsun.ttc
*/
二话不说,直接撸代码

		<!-- pdf -->
		<!-- Thymeleaf 模板引擎 -->
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.xhtmlrenderer</groupId>
			<artifactId>core-renderer</artifactId>
			<version>R8</version>
		</dependency>
		<!-- pdf end -->
				<!--io常用工具类 -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>
package com.liyang.pdfdemo.pdf;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;

public class PdfTest {
	public static String FILE_DIR = "D:/pdfvm2.pdf";
	public static String FONT_PATH = "font/SIMSUN.TTC";
	public static String VMPATH = "templates/pdf/test.html.vm";
	private final static TemplateEngine templateEngine = new TemplateEngine();

	public static void main(String[] args) throws Exception {
		zip();
		//createPdf(getHtml(VMPATH), new FileOutputStream(FILE_DIR));
	}

	/**    
	 *   批量生成pdf,压缩文件
	 * @author liyang.yuan   
	 */  
	public static void zip() {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		try {
			ByteArrayOutputStream out1 = new ByteArrayOutputStream();
			ByteArrayOutputStream out2 = new ByteArrayOutputStream();
			try {
				// 添加到zip
				zip.putNextEntry(new ZipEntry("文件1.pdf"));
				createPdf(getHtml(VMPATH), out1);
				IOUtils.write(out1.toByteArray(), zip);
				IOUtils.closeQuietly(out1);

				// 添加到zip
				zip.putNextEntry(new ZipEntry("文件2.pdf"));
				createPdf(getHtml(VMPATH), out2);
				IOUtils.write(out2.toByteArray(), zip);
				IOUtils.closeQuietly(out2);
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			zip.flush();
			zip.closeEntry();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 
		String fileName = "D:/" + "pdf.zip";
		OutputStream out;
		try {
			out = new FileOutputStream(fileName);
			IOUtils.write(outputStream.toByteArray(), out);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**    
	 * 创建pdf
	 * @author liyang.yuan
	 * @param html
	 * @return
	 * @throws com.lowagie.text.DocumentException
	 * @throws IOException   
	 */
	public static void createPdf(String html, OutputStream out) throws com.lowagie.text.DocumentException, IOException {
		/**
		 * 切记 css 要定义在head 里,否则解析失败
		 * css 要定义字体
		 * 字体中英文 https://www.cnblogs.com/chbyiming-bky/articles/9789869.html
		 * 例如宋体   style="font-family:SimSun" 	用		simsun.ttc   
		 */
		ITextRenderer renderer = new ITextRenderer();
		// 解决中文支持问题
		ITextFontResolver fontResolver = renderer.getFontResolver();
		// 字体名称要大写,否则可能找不到
		fontResolver.addFont(FONT_PATH, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		renderer.setDocumentFromString(html);
		renderer.layout();
		renderer.createPDF(out);
	}
	
	/**    
	 * 根据模板生成文件
	 * @author liyang.yuan
	 * @param vmPath
	 * @return
	 * @throws IOException   
	 */
	public static String getHtml(String vmPath) throws IOException {
		Resource resource = new ClassPathResource(vmPath);
		File sourceFile = resource.getFile();
		Context context = new Context();
		Map<String, Object> params = new HashMap<>();
		context.setVariables(params);
		return templateEngine.process(getFileString(sourceFile), context);
	}

	/**    
	 * 读取文件
	 * @author liyang.yuan
	 * @param file   
	 */
	public static String getFileString(File file) {
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr);
			}
			reader.close();
			return sbf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}

}



在这里插入图片描述

字体在 在这里插入图片描述
在这里插入图片描述

字体库有点大,可以直接读取系统的字体。linux 要自己安装,windows 就读取上面的路径。根据系统判断读取的位置吧 java 导出pdf 到此结束

  • 更多字体对应
    宋体 SimSun
    黑体 SimHei
    微软雅黑 Microsoft YaHei
    微软正黑体 Microsoft JhengHei
    新宋体 NSimSun
    新细明体 PMingLiU
    细明体 MingLiU
    标楷体 DFKai-SB
    仿宋 FangSong
    楷体 KaiTi
    仿宋_GB2312 FangSong_GB2312
    楷体_GB2312 KaiTi_GB2312

宋体:SimSuncss中中文字体(font-family)的英文名称
Mac OS的一些:
华文细黑:STHeiti Light [STXihei]
华文黑体:STHeiti
华文楷体:STKaiti
华文宋体:STSong
华文仿宋:STFangsong
俪黑 Pro:LiHei Pro Medium
俪宋 Pro:LiSong Pro Light
标楷体:BiauKai
苹果俪中黑:Apple LiGothic Medium
苹果俪细宋:Apple LiSung Light
Windows的一些:
新细明体:PMingLiU
细明体:MingLiU
标楷体:DFKai-SB
黑体:SimHei
新宋体:NSimSun
仿宋:FangSong
楷体:KaiTi
仿宋_GB2312:FangSong_GB2312
楷体_GB2312:KaiTi_GB2312
微软正黑体:Microsoft JhengHei
微软雅黑体:Microsoft YaHei
装Office会生出来的一些:
隶书:LiSu
幼圆:YouYuan
华文细黑:STXihei
华文楷体:STKaiti
华文宋体:STSong
华文中宋:STZhongsong
华文仿宋:STFangsong
方正舒体:FZShuTi
方正姚体:FZYaoti
华文彩云:STCaiyun
华文琥珀:STHupo
华文隶书:STLiti
华文行楷:STXingkai
华文新魏:STXinwei
Windows 中的中文字体。
在默认情况下,也就是未自行安装新字体或者 Office 等文字处理软件的情况下,Windows 默认提供下列字体:
Windows 95/98/98SE 宋体、黑体、楷体_GB2312、仿宋_GB2312
Windows XP/2000/2003/ME/NT 宋体/新宋体、黑体、楷体_GB2312、仿宋_GB2312 (Windows XP SP3 宋体-PUA)
Windows Vista/7/2008 宋体/新宋体、黑体、楷体、仿宋、微软雅黑、SimSun-ExtB
那么每种字体能显示那些汉字呢?
Vista 之前的 Windows 中宋体/新宋体、黑体支持 GBK 1.0 字符集,
楷体_GB2312、仿宋_GB2312 支持 GB2312-80 字符集。
(注:Windows 3.X 只能支持 GB2312-80 字符集)
Vista 及之后的 Windows 中宋体/新宋体、黑体、楷体、仿宋、微软雅黑支持 GB18030-2000 字符集,
SimSun-ExtB 只支持 GB18030-2005 字符集扩展 B 部分。
下面对字符集进行简单的介绍:
GB2312-80 < GBK 1.0 < GB18030-2000 < GB18030-2005
GB2312-80 中的字符数量最少,GB18030-2005 字符数量最多。
GB2312-80 是最早的版本,字符数比较少;
GBK 1.0 中的汉字大致与 Unicode 1.1 中的汉字数量相同;
GB18030-2000 中的汉字大致与 Unicode 3.0 中的汉字数量相同,主要增加了扩展 A 部分;
GB18030-2005 中的汉字大致与 Unicode 4.1 中的汉字数量相同,主要增加了扩展 B 部分;
由于 Unicode 5.2 的发布,估计 GB18030 会在近期发布新版本,增加扩展 C 部分。
需要说明的是在 GB18030 中扩展 B 部分并不是强制标准。
如果想查看 GB18030 的标准文本,请访问 http://www.gb168.cn 中的强标阅读。
如果想了解 Unicode 的内容,请访问 http://www.unicode.org。
现在纠正网上普遍的一个错误:
GB18030-2000 和 GB18030-2005 都不支持单字节的欧元符号
与简体中文有关的代吗页如下:
936 gb2312 简体中文(GB2312)————其实是GBK
10008 x-mac-chinesesimp 简体中文(Mac)
20936 x-cp20936 简体中文(GB2312-80)
50227 x-cp50227 简体中文(ISO-2022)
51936 EUC-CN 简体中文(EUC)
52936 hz-gb-2312 简体中文(HZ)
54936 GB18030 简体中文(GB18030)
补充:
使用楷体_GB2312、仿宋_GB2312后,在 Windows 7/Vista/2008 中可能不再显示为对应的字体。
这是因为 Windows 7/Vista/2008 中有楷体、仿宋,默认情况下没有楷体_GB2312、仿宋_GB2312,字体名称相差“_GB2312”。

分类: 字体

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章