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”。

分類: 字體

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