java生成pdf打印_java使用freemarker和itextpdf生成pdf实现打印功能

本文介绍了如何在Java中利用Freemarker模板生成HTML,然后使用iTextPDF将其转换为PDF,以实现打印功能。首先,添加相关依赖,如iTextPDF和Freemarker。接着,通过Freemarker填充数据生成HTML,处理图片路径。然后,创建PDF文档,设置文档大小,并将HTML转换为PDF。最后,解决了中文乱码问题。
摘要由CSDN通过智能技术生成

maven依赖

com.itextpdf

itextpdf

5.5.10

com.itextpdf

itext-asian

5.2.0

com.itextpdf.tool

xmlworker

5.5.8

org.xhtmlrenderer

flying-saucer-pdf-itext5

9.1.6

org.freemarker

freemarker

2.3.28

1.通过freemaker模板生成html

//获取模板并填充数据

public static String getContent(String fileName, Object data) throws Exception {

// 创建一个Configuration对象

Configuration configuration = new Configuration(Configuration.getVersion());

// 告诉config对象模板文件存放的路径。

// configuration.setDirectoryForTemplateLoading(new File(Test3.class.getClassLoader().getResource("/").getPath()));

configuration.setClassForTemplateLoading(Test3.class, "/");

// 设置config的默认字符集。一般是utf-8

configuration.setDefaultEncoding("utf-8");

//从config对象中获得模板对象。需要制定一个模板文件的名字。

Template template = configuration.getTemplate(fileName + ".ftl");

StringWriter writer = new StringWriter();

//模版和数据匹配

template.process(data, writer);

writer.flush();

String html = writer.toString();

return getImgs(html);

}

//替换html中的图片路径

private static String getImgs(String content) {

String img = "";

Pattern p_image;

Matcher m_image;

String str = "";

String[] images = null;

String regEx_img = "(]*?>)";

p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);

m_image = p_image.matcher(content);

if (m_image != null) {

while (m_image.find()) {

img = m_image.group();

Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)")

.matcher(img);

if (m != null) {

while (m.find()) {

String tempSelected = m.group(1);

str = tempSelected;

String classpath = getRootPath();

String ulr = classpath.substring(5, classpath.length());

content = content.replace(str, ulr + "templates/" + str);

}

}

}

}

return content;

}

2.生成pdf

public static void exportToResponse(String templateName, Object data) throws Exception {

String html = getContent(templateName, data);

FileOutputStream out = new FileOutputStream("d:/test3.pdf");

try {

//设置文档大小

Document document = new Document(PageSize.A4);

PdfWriter writer = PdfWriter.getInstance(document, out);

writer.setStrictImageSequence(true);

//输出为PDF文件

convertToPDF(writer, document, html);

} catch (Exception ex) {

ex.printStackTrace();

} finally {

out.close();

}

}

private static void convertToPDF(PdfWriter writer, Document document, String htmlString) throws Exception {

out.println(htmlString);

document.open();

MyFontsProvider fontProvider = new MyFontsProvider();

fontProvider.addFontSubstitute("lowagie", "garamond");

fontProvider.setUseUnicode(true);

CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);

htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

XMLWorkerHelper.getInstance().getDefaultCssResolver(true);

// if (TEMPLATENAMES.equals("合同") || TEMPLATENAMES.equals("合同模版"))

// writer.setPageEvent(new BackGroundImage());

// if (TEMPLATENAMES.equals("设计合同"))

// writer.setPageEvent(new SheJiGroundImage()); //这里初始化分页监听类

//指定文件预设开档时的缩放为100%

try {

XMLWorkerHelper.getInstance().parseXHtml(writer, document,

new ByteArrayInputStream(htmlString.getBytes("UTF-8")),

// XMLWorkerHelper.class.getResourceAsStream("/default.css"),

Charset.forName("UTF-8"), fontProvider);

} catch (IOException e) {

e.printStackTrace();

} finally {

document.close();

}

}

3.解决中文乱码

/**

* 设置字符集

*/

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 fntnames = fontname;

Font FontChinese = null;

if (fntnames == null) {

fntnames = "宋体";

}

if (size == 0) {

size = 4;

}

try {

BaseFont bfChinese = BaseFont.createFont("STSong-Light",

"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

FontChinese = new Font(bfChinese, size, style);

} catch (Exception e) {

e.printStackTrace();

}

if (FontChinese == null) {

FontChinese = super.getFont(fntnames, encoding, size, style);

}

return FontChinese;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值