一系列整合打印 参考了网上的文章
Map<String, Object> data = new HashMap<>();
data.put("list",list);
data.put("outFormNum", list.get(0).getOutFormNum());
data.put("date", datastr);
data.put("xsd", salesOrder);
data.put("CardName", CardName);
data.put("U_CardName2",U_CardName2);
data.put("U_NAME",U_NAME);
data.put("U_Address",U_Address);
data.put("U_Phone",U_Phone);
JavaToPdfHtmlFreeMarker.startsPDF(data,pdfFile,HTML1); //list 是列表的数据
由于打印机打印pdf无效 不知道原因,所以后来只能再转成png图片打印
package com.wxyding.common;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.wxyding.util.PathUtil;
import com.wxyding.util.PrintOutUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
//https://www.cnblogs.com/yunfeiyang-88/p/10984740.html
public class JavaToPdfHtmlFreeMarker {
// private static final String DEST = "D:/Scan22222.pdf";
// private static final String HTML = "scanToOut.html";
// private static final String FONT = "c:/Windows/Fonts/simsun.ttc";
// private static final String DEST = "D:/Scan22222.pdf";
// private static final String HTML = "template_freemarker.html";
private static String HTML = "";
private static final String FONT = "simhei.ttf";
private static final String IMG_EXT = "png";
private static Configuration freemarkerCfg = null;
static {
freemarkerCfg =new Configuration();
//freemarker的模板目录
try {
freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath()));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, DocumentException {
Date date= new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMddHHmmss") ; //使用了默认的格式创建了一个日期格式化对象。
String time = dateFormat.format(date); //可以把日期转换转指定格式的字符串
String pdfFile = "D:/scanpng/Scan"+time+".pdf";
Map<String,Object> data = new HashMap<>();
data.put("name","李连");
String content = JavaToPdfHtmlFreeMarker.freeMarkerRender(data,HTML);
JavaToPdfHtmlFreeMarker.createPdf(content,pdfFile,HTML);
}
public static void startsPDF(Map<String, Object> data,String pdfFile,String HTMLa) throws IOException, DocumentException {
HTML=HTMLa;
String DEST= "D:/scanpng/scanzx"+pdfFile+".pdf";
String content = JavaToPdfHtmlFreeMarker.freeMarkerRender(data, HTML);
JavaToPdfHtmlFreeMarker.createPdf(content, DEST,HTML);
//先PDF在png
String name = "scanjpg"+pdfFile;
JavaToPdfHtmlFreeMarker.pdf2png(DEST,name,"PNG");
//删除pdf
File file = new File(DEST);
if (file.isFile() && file.exists()) {
file.delete();
}
//html直接转png
// String htmlname= "D:/scanhtml"+pdfFile+".png";
// try {
// testHtml2Image(content,htmlname);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// 行不通的
// ByteArrayOutputStream pdfStream = JavaToPdfHtmlFreeMarker.createPdfpng(content);
// ByteArrayOutputStream imgSteam = JavaToPdfHtmlFreeMarker.pdfToImg(pdfStream.toByteArray(),2,1,IMG_EXT);
// FileOutputStream fileStream = new FileOutputStream(new File(DEST));
// fileStream.write(imgSteam.toByteArray());
// fileStream.close();
}
public static void testHtml2Image(String html,String htmlname) throws Exception {
JEditorPane editPane = new JEditorPane("text/html", html);
editPane.setEditable(false);
Dimension prefSize = editPane.getPreferredSize();
BufferedImage img = new BufferedImage(prefSize.width, prefSize.height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = img.getGraphics();
editPane.setSize(prefSize);
editPane.paint(graphics);
graphics.dispose();
ImageIO.write(img, "png", new File(htmlname));
}
/**
* 转换全部的pdf
* @param fileAddress 文件地址
* @param filename PDF文件名
* @param type 图片类型
*/
public static void pdf2png(String fileAddress,String filename,String type) {
// 将pdf装图片 并且自定义图片得格式大小
File file = new File(fileAddress);
PDDocument doc=null;
try {
doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
// BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
String pngname="D:\\scanpng\\zx"+filename+"_"+(i+1)+"."+type;
ImageIO.write(image, type, new File(pngname));
try {
// PrintOutUtils.goPrintOut(pngname); //打印
// File file1 = new File(pngname);
// if (file1.isFile() && file1.exists()) {
// file1.delete();
// }
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void createPdf(String content,String dest,String HTML) throws IOException, DocumentException {
// Document document = new Document();
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
//添加中文字体
BaseFont bfChinese = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//设置字体样式
Font textFont = new Font(bfChinese,11,Font.NORMAL); //正常
Font boldFont = new Font(bfChinese,11,Font.BOLD); //加粗
PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream(dest));
document.open();
//段落
Paragraph p1 = new Paragraph();
//短语
Phrase ph1 = new Phrase();
//块
Chunk c1 = new Chunk("广州雪尔达有限公司", boldFont) ;
Chunk c2 = new Chunk("图片", textFont);
//将块添加到短语
ph1.add(c1);
ph1.add(c2);
//将短语添加到段落
p1.add(ph1);
//Image对象
InputStream is = JavaToPdfHtmlFreeMarker.class.getClassLoader().getResourceAsStream("xedlogo.png");
// File file = new File("src/main/resources/");
// InputStream in = new FileInputStream(file);
byte[] byt = new byte[is.available()];
is.read(byt);
Image img = Image.getInstance(byt);
// img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(300, 60);//大小
img.setRotationDegrees(0);//旋转
img.setAbsolutePosition(430, 760); //设置 左边距、底边距
//将段落添加到短语
// document.add(p1);
document.add(img);
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register(FONT);
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
InputStream inputStream=null;
try {
worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(content.getBytes("UTF-8")),inputStream,Charset.forName("UTF-8"),fontImp);
} catch (Exception e) {
// TODO: handle exception
}finally {
document.close();
}
}
/**
* 根据模板生成pdf文件流
*/
public static ByteArrayOutputStream createPdfpng(String content) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ITextRenderer render = new ITextRenderer();
ITextFontResolver fontResolver = render.getFontResolver();
try {
fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (com.lowagie.text.DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 解析html生成pdf
render.setDocumentFromString(content);
//解决图片相对路径的问题
render.layout();
try {
render.createPDF(outStream);
return outStream;
} catch (com.lowagie.text.DocumentException e) {
e.printStackTrace();
} finally {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* freemarker渲染html
*/
public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
Writer out = new StringWriter();
try {
// 获取模板,并设置编码方式
freemarkerCfg.setDefaultEncoding("utf-8");
Template template = freemarkerCfg.getTemplate(htmlTmp);
// template.setEncoding("UTF-8");
// 合并数据模型与模板
template.process(data, out); //将合并后的数据和模板写入到流中,这里使用的字符流
out.flush();
return out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 根据pdf二进制文件 生成图片文件
*
* @param bytes pdf二进制
* @param scaling 清晰度
* @param pageNum 页数
*/
// public static ByteArrayOutputStream pdfToImg(byte[] bytes, float scaling, int pageNum,String formatName) {
// //推荐的方法打开PdfDecoder
// PdfDecoder pdfDecoder = new PdfDecoder(true);
// FontMappings.setFontReplacements();
// //修改图片的清晰度
// pdfDecoder.scaling = scaling;
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try {
// //打开pdf文件,生成PdfDecoder对象
// pdfDecoder.openPdfArray(bytes); //bytes is byte[] array with PDF
// //获取第pageNum页的pdf
// BufferedImage img = pdfDecoder.getPageAsImage(pageNum);
//
// ImageIO.write(img, formatName, out);
// } catch (IOException e){
// e.printStackTrace();
// } catch (org.jpedal.exception.PdfException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return out;
// }
}
package com.wxyding.util;
import java.io.*;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
public class PrintOutUtils {
/**
* pacakgelist 打印服务 穿文件路径
*/
public static void goPrintOut(String str) throws Exception {
File file = new File(str); // 获取选择的文件 ami1.pdf
HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(MediaSizeName.ISO_A4); //A4默认
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
// 定位默认的打印服务
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if (defaultService != null) {
FileInputStream fis = null; // 构造待打印的文件流
DocAttributeSet das = null;
try {
DocPrintJob job = defaultService.createPrintJob(); // 创建打印作业
fis = new FileInputStream(file); // 构造待打印的文件流
das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
} catch (Exception e) {
e.printStackTrace();
}finally {
fis.close();
das.clear();
}
}
}
}
数据都set入模板里面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>金中南打印出库单</title>
<style>
body {
font-family: SimHei;
}
#isbody {
padding-top: 75px;
}
h3 {
text-align: center;
}
table, table tr td {
border: 1px solid #999;
}
table {
border-collapse: collapse;
padding: 2px;
width: 700px;
margin-top: 15px;
margin-left: 45px;
table-layout: fixed;
}
tr {
line-height: 40px;
}
td {
word-wrap: break-word;
line-height: 1em;
padding: 5px;
}
.tab_attr {
width: 23%;
}
.tab_attr_id {
width: 7%;
}
.tab_content {
width: 23%;
}
.tab_content_id {
width: 7%;
}
#tablediv {
margin-top: 15px;
}
#date {
text-align: right;
}
.left {
float: left;
width: 50%;
}
.right {
float: right;
width: 100%;
}
</style>
</head>
<body>
<div id="isbody">
<div>
<h3>装箱箱号:${outFormNum}</h3>
</div>
<div class="left">
<div>制造商:鹤山市雪尔达冷冻设备有限公司</div>
<div>地址:鹤山</div>
<div>联系人:余经理</div>
<div>电话:1234567</div>
</div>
<div class="right">
<div>客户名称:${CardName}</div>
<div>收货方名称:${U_CardName2}</div>
<div>联系人:${U_NAME}</div>
<div>地址:${U_Address}</div>
<div>电话:${U_Phone}</div>
</div>
<div>
<div>销售单:${xsd}</div>
<div>打印日期:${date}</div>
</div>
<div id="tablediv">
<table>
<tr>
<td class="tab_attr_id">序号</td>
<td class="tab_attr">品名</td>
<td class="tab_attr">型号</td>
<td class="tab_attr_id">数量</td>
<td class="tab_attr_id">单位</td>
<td class="tab_attr">备注</td>
</tr>
<#list list as item>
<tr>
<td class="tab_content_id" id="item_name">${item.id}</td>
<td class="tab_content" id="item_name">${item.item_name}</td>
<td class="tab_content" id="item_model">${item.item_model}</td>
<td class='tab_content_id' id="quantity">${item.quantity}</td>
<td class='tab_content_id' id="unitMsr">${item.unitMsr}</td>
<td class='tab_content' id="note"></td>
</tr>
</#list>
</table>
</div>
</div>
</body>
</html>