java-pdf-itext 生成pdf 文档(支持中文字体)

来源:互联网 发布:淘宝手机网站模板 编辑:程序博客网 时间:2024/05/19 01:10


java-pdf-itext 生成pdf 文档(支持中文字体)


itext 版本:2.1.7

package com.demo.preview;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import org.junit.Test;import org.springframework.format.annotation.DateTimeFormat;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.Font;import com.lowagie.text.Paragraph;import com.lowagie.text.pdf.AcroFields;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfCopy;import com.lowagie.text.pdf.PdfImportedPage;import com.lowagie.text.pdf.PdfReader;import com.lowagie.text.pdf.PdfStamper;import com.lowagie.text.pdf.PdfWriter;import com.sun.tools.corba.se.idl.StringEntry;import me.grass.extend.DateExtend;import me.grass.extend.PathExtend;import me.grass.extend.StringExtend;/** * * @author xxj * @version 创建时间:2017年4月28日 上午9:47:30 */public class ITextPdfTest {@Testpublic void createPdf() {// 生成的新文件路径String fileName = StringExtend.format("itext-pdf-{0}.pdf", DateExtend.getDate("yyyyMMddHHmmss"));String newPDFPath = PathExtend.Combine("D:/Temp/pdf/", fileName);BaseFont bf;Font font = null;Document document = new Document();try {//字体String font_cn = getChineseFont();bf = BaseFont.createFont(font_cn+",1", //注意这里有一个,1 BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);font = new Font(bf,12);//生成PdfWriter.getInstance(document, new FileOutputStream(newPDFPath));document.open();document.add(new Paragraph("hello word"));document.add(new Paragraph("你好,世界!",font));document.close();} catch (Exception e) {e.printStackTrace();}}/** * 获取中文字体位置 * @return *  @author xxj 2017年4月28日 */private String getChineseFont(){//宋体(对应css中的 属性 font-family: SimSun; /*宋体*/)String font1 ="C:/Windows/Fonts/simsun.ttc";//判断系统类型,加载字体文件java.util.Properties prop = System.getProperties();String osName = prop.getProperty("os.name").toLowerCase();System.out.println(osName);if (osName.indexOf("linux")>-1) {font1="/usr/share/fonts/simsun.ttc";}if(!new File(font1).exists()){throw new RuntimeException("字体文件不存在,影响导出pdf中文显示!"+font1);}return font1;}}


0 0