JAVA打印文件后台操作在之前基础上进行优化,采用PDF的方式进行合并文件
基本思路就是将各类文件转成PDF文件,合并后在前端页面用 iframe 方式进行显示,然后调用浏览器的打印功能进行打印
1.DOC、DOCX、EXCLE文件转PDF
针对这几种文件转PDF,POI可以支持但是转换完成后格式会有少许偏差,我觉得比较好用的
是 ASPOSE 工具类,但是有一点不好就是收费的(很难受),网上有很多破解的jar包可以尝试下
word文件:aspose-words Excel文件:aspose-cells
aspose For Java的官网:[https://downloads.aspose.com/words/java]
POI的转换代码:
相关的jar包前面文章有对应的maven
/**
* 将word文档, 转换成pdf, 中间替换掉变量
* @param source 源为word文档, 必须为docx文档
* @param target 目标输出
* @param params 需要替换的变量
* @throws Exception
*/
public static void wordConverterToPdf(InputStream source,
OutputStream target, Map<String, String> params) throws Exception {
wordConverterToPdf(source, target, null, params);
}
/**
* 将word文档, 转换成pdf, 中间替换掉变量
* @param source 源为word文档, 必须为docx文档
* @param target 目标输出
* @param params 需要替换的变量
* @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
* @throws Exception
*/
public static void wordConverterToPdf(InputStream source, OutputStream target,
PdfOptions options, Map<String, String> params) throws Exception {
XWPFDocument doc = new XWPFDocument(source);
paragraphReplace(doc.getParagraphs(), params);
for (XWPFTable table : doc.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
paragraphReplace(cell.getParagraphs(), params);
}
}
}
// // 中文字体处理
// options.fontProvider(new IFontProvider() {
// @Override public com.lowagie.text.Font getFont(String familyName, String encoding, float size, int style, Color color) {
// try {
// com.lowagie.text.pdf.BaseFont bfChinese = com.lowagie.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// com.lowagie.text.Font fontChinese = new com.lowagie.text.Font(bfChinese,size,style,color);
// if (familyName != null)
// fontChinese.setFamily(familyName);
// return fontChinese;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
// });
PdfConverter.getInstance().convert(doc, target, options);
}
/** 替换段落中内容 */
private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, String> params) {
if (MapUtils.isNotEmpty(params)) {
for (XWPFParagraph p : paragraphs){
for (XWPFRun r : p.getRuns()){
String content = r.getText(r.getTextPosition());
if(StringUtils.isNotEmpty(content) && params.containsKey(content)) {
r.setText(params.get(content), 0);
}
}
}
}
}
Aspose将文件转为PDF:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>17.9</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
private static boolean getLicense() {
boolean result = false;
try {
InputStream is = new FileInputStream("E:\\ideaProject\\boccfc-post-lending-management\\src\\main\\webapp\\WEB-INF\\license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param wordPath 需要被转换的word全路径带文件名
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static void doc2pdf(String wordPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
File file = new File(pdfPath); //新建一个pdf文档
FileOutputStream os = new FileOutputStream(file);
com.aspose.words.Document doc = new com.aspose.words.Document(wordPath);
doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
os.close();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("Word 转 PDF 完成:" + pdfPath);
}
/**
* @param excelPath 需要被转换的excel全路径带文件名
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static void excel2pdf(String excelPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
Workbook wb = new Workbook(excelPath);// 原始excel路径
FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
fileOS.close();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("Excle 转 PDF 完成:" + pdfPath);
}
license.xml文件:
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>
</Data>
<Signature>2sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
2.将图片装换为PDF文件
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
/**
* @Description: 创建图片PDF
* @Param: imgPath 图片路径,pdfPath PDf路径
* @date: 2019/9/16 15:07
* @return:
*/
public static void createImagePdf(String imgPath, String pdfPath) throws Exception {
Document document = new Document(PageSize.A4, 20, 20, 50, 50);
OutputStream os = new FileOutputStream(new File(pdfPath));
PdfWriter.getInstance(document, os);
document.open();
Image image = Image.getInstance(imgPath);
float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
float documentHeight = documentWidth / 580 * 320;// 重新设置宽高
image.scaleAbsolute(documentWidth, documentHeight);// 重新设置宽高
document.add(image);
document.close();
logger.info("Picture PDF File create success: " + pdfPath);
}
3.创建PDF表格文件
依赖包同图片文件创建,这里贴部分核心代码:
Document document = new Document(PageSize.A4, 30, 30, 75, 75);
document.setMargins(30, 30, 75, 75);// 设置边距
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(f));
document.open();// 打开
float[] columnWidths = {20, 20};// 表格每一列的宽度
PdfPTable table = new PdfPTable(columnWidths);// 建立一个pdf表格
table.setSpacingBefore(30f);
table.setWidthPercentage(100);// 设置表格宽度为100%
// 设置字体
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 12);// 使用字体
Font headFont = new Font(bf, 16);// 标题
// 设置表头
PdfPCell cell = new PdfPCell(new Paragraph("诉讼材料用印打印文书数量统计",headFont));
cell.setBackgroundColor(BaseColor.WHITE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setColspan(2);
cell.setFixedHeight(48f);// 设置单元格高度
table.addCell(cell);
// 创建数据行
cell = new PdfPCell(new Paragraph("文书类型", font));
//cell.setRowspan(4);//合并单元格
cell.setFixedHeight(30f);// 设置单元格高度
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("份数", font));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
for (int i = 0; i < lists.size(); i++) {
Object[] list = (Object[]) lists.get(i);
cell = new PdfPCell(new Paragraph(list[0].toString(), font));
cell.setFixedHeight(30f);// 设置单元格高度
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
cell = new PdfPCell(new Paragraph(list[1].toString(), font));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
}
document.add(table);// 将表格添加到文档中
document.close();// 关闭
pdfWriter.close();
4.合并PDF文件
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-app</artifactId>
<version>1.7.1</version>
</dependency>
/**
* @Description: 合并PDF
* @Param: fromPath 要合并的文件路径集合,toPath 合并后的文件路径
* @date: 2019/9/4 15:09
* @return:
*/
public static void pdfMerge(List<String> fromPath,String toPath) throws Exception{
PDFMergerUtility mergerUtility = new PDFMergerUtility();
if (fromPath == null || fromPath.size() == 0){
throw new Exception(" fromPath can not be null!");
}
for (String string : fromPath) {
mergerUtility.addSource(string);
}
mergerUtility.setDestinationFileName(toPath);
mergerUtility.mergeDocuments();
logger.info("PDF File merge success: " + toPath);
}
5.前端打印
显示
<iframe class="printIframe" src="$path/query/readFile?path=(文件路径)" width="100%"
height="900" scrolling="no" frameborder="no" border="0" allowtransparency="true"
style="background-color=transparent" ></iframe>
js方法
$("#pdfContent iframe").each(function(){
$(this)[0].contentWindow.print();
});
整个打印功能就是这样的流程,具体效果的话亲测还是很好的,格式也很好的保存了,预览效果也是很好的,希望分享对大家有帮助!