打印pdf 前端请求数据并打印pdf文件

1、参考

vue接收后端传来的pdf文件流,前端调用预览PDF

html转换为pdf

2、原理

3、代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>pdf</title>
</head>
<div>
<input style="display:none" id="pdf_id" type="text" value="9715" />
<input style="display:none" id="nowUrl" type="text" value="http://127.0.0.1:46111" />
<input onclick="f111_print()" type="button" value="打印" />
<input onclick="f222_create()" type="button" value="生成" />
<input style="display:none" id="pdf_id" type="text" value="7890">
<input style="display:none" id="nowUrl" type="text" value="https://www.baidu.com/">
</div>
<body>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://www.layuicdn.com/layui-v2.5.6/layui.all.js"></script>
<script>
let request_url_prefix = "http://127.0.0.1:46111";
$(function () {
// request_url_prefix = $("#nowUrl").val();
// console.log("request_url_prefix", request_url_prefix);
// showOk("aa");
show_warn("bbbb");
})
function f111_print() {
let pdf_id = $("#pdf_id").val();
$.ajax({
type: 'get',
url: request_url_prefix + '/dialog/get_medical_record_data_is_ok?id=' + pdf_id,
dataType: "json",
success: function (obj) {
console.log("get_medical_record_data_is_ok ", obj);
if (obj.code == "01") {
showOk("正在处理中");
print_medical_record_pdf(pdf_id);
} else {
alert(obj.message);
}
}
})
}
function f222_create() {
create_pdf($("#pdf_id").val());
}
function print_medical_record_pdf(id) {
var url = request_url_prefix + "/dialog/get_medical_record_data?id=" + id;
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
// xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "arraybuffer"; // 返回类型blob
xhr.onload = function () {
console.log("get_medical_record_data", this.response);
const binaryData = [];
binaryData.push(this.response);
let pdfUrl = window.URL.createObjectURL(
new Blob(binaryData, { type: "application/pdf" })
);
if (pdfUrl) {
handle_print(pdfUrl);
}
};
xhr.send()
}
function handle_print(pdf_url) {
if (document.getElementById("print-iframe")) {
document.body.removeChild(document.getElementById("print-iframe"));
}
//判断iframe是否存在,不存在则创建iframe
let iframe = document.getElementById("print-iframe");
if (!iframe) {
iframe = document.createElement("IFRAME");
iframe.style = 'display: none';
let doc = null;
iframe.setAttribute("src", pdf_url);
iframe.setAttribute("id", "print-iframe");
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.close();
iframe.contentWindow.focus();
}
iframe.contentWindow.print();
}
function create_pdf(id) {
$.ajax({
type: 'post',
url: request_url_prefix + '/dialog/exportPdf?id=' + id,
dataType: "json",
success: function (obj) {
console.log("create_pdf ", obj);
if (obj.code == "01") {
alert(obj.message)
} else {
alert(obj.message)
}
}
})
}
function show_warn(msg) {
layer.msg("<span style='color: #000;'>" + msg + "</span>", { icon: 7, time: 2000 });
}
function showOk(msg) {
layer.msg("<span style='color: #000'>" + msg + "</span>", { icon: 6, time: 2000 });
}
function showError(msg) {
layer.msg("<span" + msg + "</span>", { icon: 2, time: 2000 });
}
</script>
</html>

4、java

@CrossOrigin
@GetMapping("/get_medical_record_data_is_ok")
@ResponseBody
public Result get_medical_record_data_is_ok(Integer id, HttpServletResponse response) {
Result result = new Result();
try {
if (redisTemplate.opsForValue().get(treatmentPdf.getRedisKey(id)) != null) {
return new Result("02", "正在生成中,请稍后");
}
System.out.println(" ===== get_medical_record_data 接收到的id=" + id);
String folder = treatmentPdf.getMedicalRecordFolder();
File file = new File(folder + File.separator + IDMake.createId() + ".html");
String absolutePath = file.getParentFile().getAbsolutePath();
String pdfName = FileUtil.getTreatmentPdfName(id);
String pdfUrl = absolutePath + File.separator + pdfName;
// 判断该路径下的文件是否存在
File filePdf = new File(pdfUrl);
if (!filePdf.exists()) {
return new Result("02", "请先点击生成");
}
return new Result("01", "可以下载打印");
} catch (Exception e) {
LogbackUtil.getErrorLogger().error(e.getMessage(), e);
return new Result("02", "下载失败 " + e.getMessage());
}
}
@CrossOrigin
@GetMapping("/get_medical_record_data")
public Result get_medical_record_data(Integer id, HttpServletResponse response) {
Result result = new Result();
try {
if (redisTemplate.opsForValue().get(treatmentPdf.getRedisKey(id)) != null) {
return new Result("02", "正在生成中,请稍后");
}
System.out.println(" ===== get_medical_record_data 接收到的id=" + id);
String folder = treatmentPdf.getMedicalRecordFolder();
File file = new File(folder + File.separator + IDMake.createId() + ".html");
String absolutePath = file.getParentFile().getAbsolutePath();
String pdfName = FileUtil.getTreatmentPdfName(id);
String pdfUrl = absolutePath + File.separator + pdfName;
// 判断该路径下的文件是否存在
File filePdf = new File(pdfUrl);
if (!filePdf.exists()) {
return new Result("02", "请先点击生成");
}
FileInputStream fis = new FileInputStream(filePdf);
response.setContentType("application/pdf");
//response.setHeader("content-Disposition", "attachment;filename=" + pdfName);
//response.setContentType("blob");
ServletOutputStream out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
fis.close();
out.close();
} catch (Exception e) {
LogbackUtil.getErrorLogger().error(e.getMessage(), e);
return new Result("02", "下载失败 " + e.getMessage());
}
return result;
}
//获取诊疗单病例信息
@GetMapping("/getDiseaseMessage")
public String getDiseaseMessage(String id) {
String html = "";
try {
//第四种方案使用resourceLoader下载
ResourceLoader resourceLoader = new DefaultResourceLoader();
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:/pdfFolder/diseaseTemplate.html");
// File file = resource.getFile();
InputStream inputStream = resource.getInputStream();
String folder = System.getProperty("user.dir");
String htmlId = IDMake.createId();
File file = new File(folder + File.separator + htmlId + ".html");
FileUtils.copyInputStreamToFile(inputStream, file);
html = service.exportHtmlPDF(file, id);
file.delete();
inputStream.close();
// System.out.println("生成的html====" + html);
} catch (Exception e) {
e.printStackTrace();
}
return html;
}
posted @   一只桔子2233  阅读(505)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签
历史上的今天:
2021-04-18 SpringBoot Ribbon负载均衡策略配置
2021-04-18 SpringBoot Eureka集群配置
2021-04-18 SpringBoot集成Eureka
2021-04-18 知 识 收 录
点击右上角即可分享
微信分享提示