This commit is contained in:
linfso 2024-06-04 10:02:17 +08:00
parent 5f537bbfe9
commit b3b67acd1f
3 changed files with 292 additions and 185 deletions

View File

@ -31,8 +31,8 @@
</div>
<div class="tools">
<div style="width:100%;text-align: right;">
<el-button title="" type="primary" v-if="isA4" @click="showSinglePage">切换单页</el-button>
<el-button title="" type="primary" v-else @click="showA4Page">切换A4</el-button>
<el-button title="" type="primary" v-if="isA4" @click="showSinglePage(1)">切换单页</el-button>
<el-button title="" type="primary" v-else @click="showA4Page(1)">切换A4</el-button>
<el-button title="" type="primary" icon="el-icon-download" @click="downPDF">下载</el-button>
<el-button title="" type="primary" icon="el-icon-printer" @click="printPDF">打印</el-button>
</div>
@ -63,7 +63,6 @@
* 一定要使用4.2的话就手动装一下pdfjs-dist的2.5.207 ==> npm i pdfjs-dist@2.5.207
*/
import pdf from 'vue-pdf'
import { jsPDF } from "jspdf";
import PdfUtils from '@/utils/pdfUtils.js';
export default {
components: { pdf },
@ -78,6 +77,10 @@ export default {
isInitA4:{
type: Boolean,
default: false
},
isLoadComplete:{
type: Boolean,
default: false
}
},
data() {
@ -101,14 +104,8 @@ export default {
scale: 20,
preScale: 20,
// // A4
// newPrototype: [],
// newPrototypeValue: [],
// imgFiles: [], //pdf页数列表
// filelist: [], //列表
// //img
// realWidth: 720,
// dpr: '',
pdfUtils:new PdfUtils(),
loading: false,
}
@ -130,43 +127,91 @@ export default {
watch: {
pdfList(){
this.cacheFileList=this.pdfList;
this.pageCount=this.cacheFileList.length;
if(this.isA4){
setTimeout( this.showA4Page(),2000);
}
this.initA4List();
this.showFirstFile();
// if(this.isA4){
// this.pageCount=this.cacheA4FileList.length;
// setTimeout( this.showA4Page(this.cacheA4FileList.length),2000);
// }else{
// this.pageCount=this.cacheFileList.length;
// setTimeout( this.showSinglePage(1),2000);
// }
// console.log(this.loadPdfUrl);
// this.showFirstFile();
},
thisPageCount(value) {
// console.log("============11111====================")
// console.log(this.isA4)
if(this.isA4){
// if (value) this.page = 1
this.doScale(75);
}else{
this.doScale(20);
}
},
isLoadComplete(newVal,oldVal){
console.log("isLoadComplete==>"+this.isLoadComplete);
this.showA4Page(1);
}
},
mounted() {
this.initA4List();
this.showFirstFile();
window.addEventListener('mousewheel', this.handleScroll, { passive: false })
},
methods: {
showFirstFile(){
if(this.isA4){
// this.isA4=false;
setTimeout( this.showA4Page(),2000);
}else{
if(this.cacheFileList&& this.cacheFileList.length>0){
this.loadPdfUrl =this.pdfList[0].pdfUrl;
this.resetCountKey++;
initA4List(){
this.cacheA4FileList=[];
const newList = Object.assign([], this.pdfList);
if(newList&&newList.length>4){
let spliteArr = (array = [], subGroupLength = 0) => {
let index = 0;
const newArray = [];
while (index < array.length) {
newArray.push(array.slice(index, index += subGroupLength));
}
return newArray;
}
const subPdfList=spliteArr(newList, 4);
for (let i=0; i < subPdfList.length;i++){
let fileItem={
"billCode":"page-"+(i+1),
"pdfUrl":null,
"childreen":subPdfList[i]
}
this.cacheA4FileList.push(fileItem);
}
}else{
let fileItem={
"billCode":"page-"+1,
"pdfUrl":null,
"childreen":newList
}
this.cacheA4FileList.push(fileItem);
}
console.log(this.cacheA4FileList)
},
showFirstFile(){
// if(this.isA4){
// setTimeout( this.showA4Page(this.cacheA4FileList.length),2000);
// }else{
// if(this.cacheFileList&& this.cacheFileList.length>0){
// setTimeout( this.showSinglePage(this.cacheFileList.length),2000);
// this.resetCountKey++;
// }
// }
if(this.isA4){
this.pageCount=this.cacheA4FileList.length;
setTimeout( this.showA4Page(this.cacheA4FileList.length),2000);
}else{
this.pageCount=this.cacheFileList.length;
setTimeout( this.showSinglePage(1),2000);
}
this.resetCountKey++;
},
addPdfUrl(billCode,pdfUrl){
let item={
@ -240,13 +285,13 @@ export default {
let fileNo = this.currentPage - 1
if (fileNo < 1) return
this.currentPage = fileNo
this.loadPdfUrl =this.cacheFileList[this.currentPage-1].pdfUrl;
this.showSinglePage(this.currentPage)
}
else{
let fileNo = this.currentPage - 1
if (fileNo < 1) return
this.currentPage = fileNo
this.loadPdfUrl =this.cacheA4FileList[this.currentPage-1].pdfUrl;
this.showA4Page(this.currentPage)
}
},
nextPage() {
@ -255,13 +300,13 @@ export default {
let fileNo = this.currentPage + 1
if (fileNo > this.pageCount) return
this.currentPage = fileNo
this.loadPdfUrl =this.cacheFileList[this.currentPage-1].pdfUrl;
this.showSinglePage(this.currentPage)
}
else{
let fileNo = this.currentPage + 1
if (fileNo > this.pageCount) return
this.currentPage = fileNo
this.loadPdfUrl =this.cacheA4FileList[this.currentPage-1].pdfUrl;
this.showA4Page(this.currentPage)
}
},
// 下载
@ -269,13 +314,27 @@ export default {
// 下载所有预览的PDF文件
if(this.isA4){
if(this.cacheA4FileList&&this.cacheA4FileList.length>0){
this.cacheA4FileList.forEach(item=>{
this.cacheA4FileList.forEach(async item=>{
if(!item.pdfUrl){
// 分页生成文件,只渲染第一页
let thisSubList=item.childreen;
let needGenList=[];
for(let j=0;j<thisSubList.length;j++){
needGenList.push(thisSubList[j].pdfBase64)
}
item.pdfUrl=await this.pdfUtils.mergePdfToA4(needGenList);
}
this.downPdfFile(item.billCode,item.pdfUrl);
});
}
}else{
if(this.cacheFileList&&this.cacheFileList.length>0){
this.cacheFileList.forEach(item=>{
this.cacheFileList.forEach( item=>{
if(!item.pdfUrl){
item.pdfUrl = this.pdfUtils.getBlobUrl(item.pdfBase64);
}
this.downPdfFile(item.billCode,item.pdfUrl);
});
}
@ -298,7 +357,18 @@ export default {
// this.$refs.pdf.print()
if(this.isA4){
if(this.cacheA4FileList&&this.cacheA4FileList.length>0){
this.cacheA4FileList.forEach(item=>{
this.cacheA4FileList.forEach(async item=>{
if(!item.pdfUrl){
item.pdfUrl = this.pdfUtils.getBlobUrl(pdfBase64);
}
// 分页生成文件,只渲染第一页
let thisSubList=item.childreen;
let needGenList=[];
for(let j=0;j<thisSubList.length;j++){
needGenList.push(thisSubList[j].pdfBase64)
}
item.pdfUrl=await this.pdfUtils.mergePdfToA4(needGenList);
this.loadPdfUrl=item.pdfUrl;
this.$refs.pdf.print();
});
@ -307,147 +377,58 @@ export default {
this.$emit("onPrint");
}
},
// initA4() {
// //此功能是为了pdf.js内部,有时候会报for....in的错误,原因是原型方法被其他地方改变,这里需要改回来
// for (let key in Array.prototype) {
// if (!Array.prototype.hasOwnProperty(key)) continue;
// this.newPrototype.push(key);
// }
// // 存放原始键 原始方法
// this.newPrototypeValue = this.newPrototype.map((v) => ({ [v]: Array.prototype[v] }));
// // 删除直接属性
// this.newPrototype.forEach((v) => delete Array.prototype[v]);
// },
showSinglePage(){
this.showFirstFile();
showSinglePage(page){
this.isA4 = false;
if(!page || Object.is(page, NaN)){
page=1;
}
this.pageCount=this.cacheFileList.length;
const thisPage=this.cacheFileList[page-1];
const pdfBase64 = thisPage.pdfBase64;
this.loadPdfUrl = this.pdfUtils.getBlobUrl(pdfBase64);
this.doScale(20);
this.resetCountKey++;
},
async showA4Page(){
// this.initA4();
this.isA4 = true
this.doScale(75);
this.cacheA4FileList=[];
let pdfUtils= new PdfUtils();
let that = this;
const loadingInstance = this.$loading({
text: '正在生成A4预览...'
})
try {
let imgFiles = [];
for(let i=0;i<this.cacheFileList.length;i++){
let file=this.cacheFileList[i].pdfUrl;
const img = await pdfUtils.pdfToImg(file);
imgFiles.push(img);
async showA4Page(page){
this.isA4 = true
if(!page || Object.is(page, NaN)){
page=1;
}
// 每4个图片放一页
if(imgFiles&&imgFiles.length>0){
// 数组拆分
const subImageList=imgFiles.reduce((acc, curr, index) => {
if (index % 4 === 0) acc.push([])
acc[Math.floor(index / 4)].push(curr)
return acc
}, [])
// 分页生成文件
for(let i=0; i<subImageList.length;i++){
let thisSubList=subImageList[i];
let pageNo = i+1;
console.log(thisSubList);
let pdfUrl=this.mergeImgToPdf(pdfUtils,thisSubList,pageNo);
if(pdfUrl){
let fileItem={
"billCode":"page-"+pageNo,
"pdfUrl":pdfUrl,
}
this.cacheA4FileList.push(fileItem);
if(i==0){
loadingInstance.close();
this.loadPdfUrl=this.cacheA4FileList[0].pdfUrl;
this.pageCount=1;
this.page=1;
}
}
}
this.loadPdfUrl=this.cacheA4FileList[0].pdfUrl;
this.pageCount=this.cacheA4FileList.length;
this.currentPage=1;
this.page=1;
this.resetCountKey++;
}
// 自行更改要保存的pdf名字
// doc.save('a4pdf.pdf')
} catch (error) {
console.log(error);
}
},
mergeImgToPdf(pdfUtils,imgFiles,pageNo){
try {
var doc = new jsPDF('', 'pt', 'a4')
// doc.addPage() //添加页
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
// var imgWidth = 595.28
// var imgHeight = (592.28 / contentWidth) * contentHeight
// let imgRealWidth=595.28/2-50;
let imgRealHeight=841.89/2-50;
let x=0;
let y=0;
for(let i=0;i<imgFiles.length;i++){
let imgItem=imgFiles[i];
// 计算宽高比
let whRate=imgItem.imgWidth/imgItem.imgHeight;
var contentWidth = imgRealHeight*whRate
var contentHeight = imgRealHeight;
// imgRealWidth/whRate
var imgUrl = imgItem.url;
let left=40*(x+1)+x*contentWidth;
let top=40*(y+1)+y*contentHeight;
// console.log("top:"+top+",left:"+left);
doc.addImage(imgUrl, 'PNG',left, top, contentWidth, contentHeight)
// 0,0 1,0
// 0,1 1,1
// console.log("x:"+x+",y:"+y);
if(x==0){
x++;
}
else if(x==1){
x=0;
y++;
}
if(y>1){
x=0;
y=0;
// doc.addPage() //添加页
}
}
var pdfBase64 = doc.output('datauristring')
let pdfUrl=URL.createObjectURL(pdfUtils.base64ToBlob(pdfBase64));
return pdfUrl;
} catch (error) {
console.log(error);
return null;
if(!this.cacheA4FileList || this.cacheA4FileList.length==0){
return;
}
}
const loadingInstance = this.$loading({
text: '正在生成A4预览...'
})
this.pageCount=this.cacheA4FileList.length;
console.log(this.cacheA4FileList)
// 分页生成文件,只渲染第一页
let thisSubList=this.cacheA4FileList[page-1].childreen;
let needGenList=[];
for(let j=0;j<thisSubList.length;j++){
needGenList.push(thisSubList[j].pdfBase64)
}
let pdfUrl=await this.pdfUtils.mergePdfToA4(needGenList);
if(pdfUrl){
loadingInstance.close();
this.cacheA4FileList[page-1].pdfUrl=pdfUrl;
this.loadPdfUrl=this.cacheA4FileList[page-1].pdfUrl;
}
this.resetCountKey++;
},
}
}

View File

@ -1,9 +1,8 @@
import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import { degrees,PageSizes, PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import axios from "axios";
import Buffer from 'vue-buffer'
import * as pdfjs from 'pdfjs-dist';
import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
/**
* 浏览器打开新页签预览pdf
* blob(必选): pdf文件信息(Blob对象)【Blob】
@ -243,7 +242,7 @@ export default class PdfUtils {
* @param {Number} y - 页面展示高
* @param {String}fileName - 文件名称
*/
savePdfImage(newimgList, x, y, fileName) {
savePdfImage(newimgList, x, y, fileName) {
return new Promise((resolve, reject) => {
// 创建canvas
@ -403,6 +402,99 @@ export default class PdfUtils {
return URL.createObjectURL(mergedPdfBlob);
}
}
async mergePdfToA4(pdfFileList, fileName,isNeedDown=false) {
let pdfBuffers = [];
pdfFileList.map((item) => {
let dateArray=this.base64ToBuffer(item);
pdfBuffers.push(Buffer.from(dateArray));
});
const pdfDoc = await PDFDocument.create();
const pageA4 = pdfDoc.addPage(PageSizes.A4);
const drawHeight = pageA4.getHeight()/2;
const drawWidth = pageA4.getWidth()/2;
let i=0;
let x=0;
let y=0;
let width=0;
let height=0;
for (let buffer of pdfBuffers) {
const [page] = await pdfDoc.embedPdf(buffer);
const pageDims = page.scale(1.0);
// ...pageDims,
// rotate: degrees(30),
// opacity: 0.75,
// Optional blendMode
// Optional height
// Optional opacity
// Optional rotate
// Optional width
// Optional x
// Optional xScale
// Optional xSkew
// Optional y
// Optional yScale
// Optional ySkew
let rateDif=pageDims.width/pageDims.height;
// width = drawHeight*rateDif
width = drawWidth-1*rateDif;
height = drawHeight-1;
if(i==0){
x=0;
y=pageA4.getHeight()/2;
}
else if(i==1){
x=pageA4.getWidth()/2;
y=pageA4.getHeight()/2;
}
else if(i==2){
x=0;
y=0;
}
else if(i==3){
x=pageA4.getWidth()/2;
y=0;
}
pageA4.drawPage(page, {
x: x,
y: y,
width:width,
height:height
});
i++;
}
const uint8Array = await pdfDoc.save();
let mergeBuffer = Buffer.from(uint8Array);
var blob=new Blob([mergeBuffer]);
if(isNeedDown){
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", fileName);
if (typeof link.download === 'undefined') {
link.setAttribute('target', '_blank')
}
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}else{
const mergedPdfBlob = new Blob([mergeBuffer], {
type: "application/pdf",
});
return URL.createObjectURL(mergedPdfBlob);
}
}
downloadBase64(base64Str,fileName) {
let result = base64Str.replace(/[\r\n]/g, "");
let pdfBase64 = `data:application/pdf;base64,${result}`;
@ -419,11 +511,41 @@ export default class PdfUtils {
}
async urlToBlob(url) {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const byteArray = new Uint8Array(arrayBuffer);
return new Blob([byteArray], {type: response.headers.get('content-type')});
}
blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
fileTobase64(file) {
let reader = new FileReader();
reader.readAsDataURL(file)
}
blobToArrayBuffer(blob, callback) {
let reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = function () {
return callback(this.result);
}
}
// let blob = new Blob([1, 2, 3, 4, 5]);
// blobToArrayBuffer(blob, (arrayBuffer) => { console.log(arrayBuffer) })
base64ToFile(base64Data, filename) { // 64转file
if (typeof base64Data != 'string') {

View File

@ -59,7 +59,7 @@
<el-dialog class="printPreDialog" title="预览" :visible.sync="openPdfView" width="95%" height="100%" :close-on-click-modal="false" :destroy-on-close="true" v-dialogDrag append-to-body @close="handleClose">
<div style="height:100%;width:100%;overflow: auto;">
<PdfViewer ref="pdfViewer" v-if="openPdfView" :pdfList="pdfList" :isInitA4="isInitA4" @onPrint="onPdfViewPrint" ></PdfViewer>
<PdfViewer ref="pdfViewer" v-if="openPdfView" :pdfList="pdfList" :isLoadComplete="isLoadComplete" :isInitA4="isInitA4" @onPrint="onPdfViewPrint" ></PdfViewer>
</div>
</el-dialog>
@ -120,6 +120,8 @@
showCounter:0,
pdfList:[],
pdfBase64List:[],
isLoadComplete:false,
tanexPrinter:null,
printerDownUrl:null,
@ -271,21 +273,18 @@
that.pdfList=[];
that.showCounter=0;
this.tanexPrinter.batchGetPDFAdv(printDataList,billCount,async function(code,msg,data){
console.log(msg);
console.log(code);
if(code == 500){
that.$modal.msgError("打印出错:"+msg);
}
else if(code == 200){
const pdfData=deepClone(data);
loadingInstance.close();
let pdfUtils=new PdfUtils({});
let blobUrl= await pdfUtils.getBlobUrl(pdfData.file);
let pdfInfo={
"billCode":pdfData.ydSn,
"pdfUrl":blobUrl
"pdfUrl":null,
"pdfBase64":pdfData.file
}
that.pdfList.push(pdfInfo);
@ -298,7 +297,8 @@
}
else if(code == 800){
// 全部获取完成
// console.log("===预览全部获取完成====>");
console.log("===全部获取完成1====>");
that.isLoadComplete=true;
}
});
@ -351,17 +351,19 @@
that.$modal.msgError("打印出错:"+msg);
}
else if(code == 200){
console.log("===获取到数据====>");
const pdfData=deepClone(data);
loadingInstance.close();
let pdfUtils=new PdfUtils({});
let blobUrl= await pdfUtils.getBlobUrl(pdfData.file);
let pdfInfo={
"billCode":pdfData.ydSn,
"pdfUrl":blobUrl
"pdfUrl":null,
"pdfBase64":pdfData.file
}
that.pdfList.push(pdfInfo);
console.log(that.pdfList);
if(!that.openPdfView && that.showCounter==0){
that.openPdfView = true;
}
@ -370,7 +372,8 @@
}
else if(code == 800){
// 全部获取完成
// console.log("===全部获取完成====>");
console.log("===全部获取完成2====>");
that.isLoadComplete=true;
}
});
},
@ -429,6 +432,7 @@
pdfUtils.getBlobUrl(pdfData.file, pdfData.ydSn+".pdf",true )
}
else if(code == 800){
// 全部获取完成
// console.log("===全部获取完成====>");
}