Vue中Pdf预览及打印(自定义组件)
编写自定义组件PdfView.vue<template><div><pdf ref="myPdfComponent" hidden :src="this.url"></pdf><!--第一种 pdf展示--><!--<div style="height: 800px;overflow-y: auto;text-align: c
·
思路:
1. vue中使用ifream访问后台
2.封装共用vue组件
3.后台通过freemaker模板生成相应pdf
效果:
编写自定义组件PdfView.vue
<template>
<div>
<pdf ref="myPdfComponent" hidden :src="this.url"></pdf>
<!-- 第一种 pdf展示-->
<!-- <div style="height: 800px;overflow-y: auto;text-align: center;background-color: #525659;">-->
<!-- <pdf-->
<!-- v-for="i in numPages"-->
<!-- :key="i"-->
<!-- :src="src"-->
<!-- :page="i"-->
<!-- style="display: inline-block;width: 800px;text-align: center;margin-top: 10px;"-->
<!-- ></pdf>-->
<!-- </div>-->
<!-- 第二种 iframe展示-->
<iframe :src="url" frameborder="0" style="width: 100%; height: 700px;"></iframe>
<div style="text-align: center;">
<a-button type="primary" style="width: 120px;" icon="printer" @click="$refs.myPdfComponent.print()">打印</a-button>
</div>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: {
pdf
},
data () {
return {
// src: pdf.createLoadingTask(this.url),
// numPages: undefined
}
},
props: ['url'],
mounted () {
// this.src.promise.then(pdf => {
// this.numPages = pdf.numPages
// })
}
}
</script>
组件调用
<a-col :span="18">
<pdf-view :url="printSrc"></pdf-view>
</a-col>
iframe跳转地址
_self.printSrc = _self.baseUrl + '/pc/pdf/demoPrintPDF?familyId=' + _self.family.id + '&time=' + new Date().getTime() + "#toolbar=0";
后台方法
1. 访问方法
/**
* pdf模板预览
*/
@RequestMapping("demoPrintPDF")
public void demoPrintPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
//freemaker中的数据map
Map<String, Object> data = Maps.newHashMap();
String template = "oncePrintPDF.html";
String date = DateUtils.dateToStringFormat(new Date(), "yyyy年MM月dd日");
data.put("dateStr", date);
this.commonPrintPDF(data, template, response);
}
2. 公共打印方法
/**
* 公共打印方法
*
* @param map 数据map
* @param template 打印模板文件
* @throws Exception
*/
private void commonPrintPDF(Map<String, Object> map, String template, HttpServletResponse response) throws Exception {
PdfDocumentGenerator pdfDocumentGenerator = new PdfDocumentGenerator();
OutputStream outputStream = null;
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
outputStream = response.getOutputStream();
pdfDocumentGenerator.generate(template, map, outputStream);
}
3.PdfDocumentGenerator
package com.app.system.utils.pdf;
import com.app.system.log4j2.LogUtils;
import org.slf4j.Logger;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
/**
* PDF流加载
* Created by m`jj on 2019/1/16.
*/
@SuppressWarnings("all")
public class PdfDocumentGenerator {
private static Logger logger = LogUtils.getBusinessLogger();
public boolean generate(String template, Map<String, Object> variables, OutputStream outputStream) throws Exception {
try {
HtmlGenerator e = new HtmlGenerator();
String htmlContent = e.generate(template, variables);
this.generate(htmlContent, outputStream);
} catch (Exception var6) {
logger.error(var6.toString());
}
return true;
}
public void generate(String htmlContent, OutputStream outputStream) throws Exception {
Object out = null;
try {
DocumentBuilder e = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = e.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));
try {
ITextRenderer e1 = this.createTextRenderer();
e1.setDocument(doc, (String) null);
e1.layout();
e1.createPDF(outputStream);
} catch (Exception var11) {
logger.error(var11.toString());
}
} catch (Exception var12) {
throw var12;
} finally {
if (out != null) {
((OutputStream) out).close();
}
}
}
public ITextRenderer createTextRenderer() {
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
addFonts(fontResolver);
return renderer;
}
public static ITextFontResolver addFonts(ITextFontResolver fontResolver) {
String fontPath = null;
try {
fontPath = ResourceUtils.getURL("classpath:").getPath() + "static/fonts";
} catch (IOException var2) {
var2.printStackTrace();
}
File fontsDir = new File(fontPath);
logger.debug("fontPath=" + fontsDir.getAbsolutePath());
if (fontsDir != null && fontsDir.isDirectory()) {
File[] files = fontsDir.listFiles();
File[] arr = files;
int len = files.length;
for (int i = 0; i < len; ++i) {
File file = arr[i];
if (!file.isDirectory()) {
try {
logger.debug("字体文件:" + file.getAbsolutePath());
fontResolver.addFont(file.getAbsolutePath(), "Identity-H", false);
} catch (Exception var9) {
logger.debug("字体加载:" + var9.getMessage());
var9.printStackTrace();
}
}
}
}
return fontResolver;
}
}
4. HtmlGenerator
package com.app.system.utils.pdf;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
/**
* Created by m`jj on 2019/1/16.
*/
@SuppressWarnings("all")
public class HtmlGenerator {
public String generate(String template, Map<String, Object> variables) throws IOException, TemplateException {
BufferedWriter writer = null;
StringWriter stringWriter = null;
String htmlContent = "";
try {
Configuration e = FreemarkerConfiguration.getConfiguration();
e.setDefaultEncoding("utf-8");
Template tp = e.getTemplate(template);
stringWriter = new StringWriter();
writer = new BufferedWriter(stringWriter);
tp.process(variables, writer);
htmlContent = stringWriter.toString();
writer.flush();
} finally {
try {
if(stringWriter != null) {
stringWriter.close();
}
} catch (Exception var13) {
;
}
if(writer != null) {
writer.close();
}
}
return htmlContent;
}
}
5.FreemarkerConfiguration
import com.app.system.utils.WebUtils;
import freemarker.template.Configuration;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("all")
public class FreemarkerConfiguration {
private static Configuration config = null;
private FreemarkerConfiguration() {
}
public static synchronized Configuration getConfiguration() {
if (config == null) {
setConfiguration();
}
return config;
}
private static void setConfiguration() {
config = new Configuration();
String path = null;
try {
path = WebUtils.getRootPath() + "printPdf";
config.setDirectoryForTemplateLoading(new File(path));
} catch (IOException var2) {
var2.printStackTrace();
}
}
}
6.freemaker模板及字体文件存放位置
7.freemaker模板
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>转办模板</title>
<style>
body {
font-family: SimSun, Arial Unicode MS, Lucida Sans Unicode, Arial, verdana, arial, helvetica, sans-serif;
}
.printContent {
margin: 0px;
padding: 0px;
width: 700px;
font-size: 16px;
clear: both;
}
.printContent p {
margin: 5px 0;
padding: 0px;
text-align: left;
text-indent: 2em;
line-height: 20px;
}
.printContent .printTitle {
clear: both;
text-indent: 0em;
font-size: 28px;
text-align: center;
line-height: 30px;
font-weight: bold;
}
.dataTable {
width: 99%;
border-top: 1px solid #000000;
border-left: 1px solid #000000;
border-spacing: inherit;
line-height: 24px;
-fs-table-paginate: paginate; /*处理分页断行问题*/
}
.dataTable tr {
height: 24px;
}
.dataTable tr td {
text-align: center;
padding: 2px;
border-right: 1px solid #000000;
border-bottom: 1px solid #000000;
line-height: 50px;
}
.dataTable tr > td:first-child {
width: 150px;
}
.border {
padding-left: 20px;
padding-right: 20px;
border-bottom: 1px solid #000000;
}
.pageBreak {
page-break-before: always
}
@page {
@bottom-right {
content: element(footer);
}
}
#pagenumber:before {
content: counter(page);
}
#pagecount:before {
content: counter(pages);
}
@page {
margin: 5mm 5mm 10mm 11mm;
}
.printRight {
margin-left: 75% !important;
line-height: 50px !important;
}
</style>
</head>
<body>
<div class="printContent">
<p class="printTitle" style="padding-top: 100px;">朝阳区房屋管理局12345退单情况说明</p>
<p style="margin-top: 20px">签字要求:科长、主管主任、中心主任右上角签字</p>
<table class="dataTable">
<tr>
<td>案件编号</td>
<td></td>
</tr>
<tr>
<td style="line-height: 300px">案件内容</td>
<td></td>
</tr>
<tr>
<td>转派单位</td>
<td></td>
</tr>
<tr>
<td style="line-height: 300px">转派依据</td>
<td></td>
</tr>
</table>
<p class="printRight" style="margin-top: 30px">朝阳区房屋管理局</p>
<p class="printRight">${dateStr}</p>
</div>
</body>
</html>
8.字体文件: https://wws.lanzous.com/i6xoxjw9v9a
更多推荐
已为社区贡献2条内容
所有评论(0)