348 lines
9.2 KiB
Vue
Raw Permalink Normal View History

2025-03-29 16:01:43 +08:00
<template>
<view class="page">
<canvas type="2d" :id="'canvas_'+ pageId"
style="width: 560px;height: 320px;position: fixed;left:8888px"></canvas>
<view id="img-box" style="width: 100%;height: calc(100vh - 200rpx);">
<image :src="url" mode="heightFix" style="width: 100%;height: calc(100vh - 200rpx);"
show-menu-by-longpress="true"></image>
</view>
<view class="flex justify-around">
<view class="btn" @click="savePdf('save')">
<image src="@/static/download.png" style="width: 48rpx;height: 48rpx"></image>
<text>保存文件</text></view>
<view class="btn" @click="savePdf('share')">
<text class="cuIcon-weixin" style="color:#39E5B1;font-size: 48rpx;"></text>
<text>微信好友</text>
</view>
</view>
</view>
</template>
<script>
import {
getTemplateDetail,
saveExportRecord,
getBeerInfo
} from "@/api/bar.js"
import {
base_url
} from '@/api/config.js'
export default {
data() {
return {
pageId: Math.random().toString(36).substr(2),
templateId: '',
templateInfo: {},
els: {
// background: 'https://ma.zdtap.com/profile/upload/2025/02/26/815068ec81b4cb1738a4773bee57970@2x_20250226224217A001.png',
// cover: {
// width: 304,
// height: 400,
// x: 28,
// y: 36,
// url: 'https://ma.zdtap.com/profile/upload/2025/02/26/beercover_20250226223149A001.jpg',
// },
},
imgPath: '',
url: '',
userInfo: {},
barInfo: {},
beer: {}
};
},
onLoad(options) {
this.templateId = options.templateId
this.form = {
amount: options.amount,
amount1: options.amount1,
specs: options.specs,
specs1: options.specs1,
no: options.no,
beerStyles: options.beerStyles,
brandName: options.brandName,
beerId: options.beerId
}
this.userInfo = uni.getStorageSync('userInfo')
this.barInfo = uni.getStorageSync('barInfo')
},
onReady() {
this.getTemplateInfo()
}, // onShareTimeline(res) {
// console.log('pyq',res)
// },
// onShareAppMessage(res) {
// if(res.form == 'menu') {
// console.log('分享按钮',res.target.id)
// return {
// imageUrl: this.url,
// }
// }
// },
methods: {
getBeerInfoFun() {
getBeerInfo(this.form.beerId).then(res => {
this.beer = res.data
this.els.brandName && (this.els.brandName.value = this.beer.brandName || '')
this.els.ABV && (this.els.ABV.value = this.beer.beerAbv|| '')
this.els.cover && (this.els.cover.url = this.beer.cover)
this.els.beerName && (this.els.beerName.value = this.beer.beerName || '')
this.els.beerStyle && (this.els.beerStyle.value = this.beer.beerStyles || '')
this.createPdf()
})
},
getTemplateInfo() {
getTemplateDetail(this.templateId).then(res => {
console.log(res)
this.templateInfo = res.data
this.els = JSON.parse(res.data.elements)
this.els.address && (this.els.address.value = this.barInfo.address|| '')
this.els.barName && (this.els.barName.value = this.barInfo.barName|| '')
this.els.phone && (this.els.phone.value = this.barInfo.barContactPhone|| '')
this.els.no && (this.els.no.value = this.form.no|| '')
this.els.amount && (this.els.amount.value = this.form.amount|| '')
this.els.amount1 && (this.els.amount1.value = this.form.amount1|| '')
this.els.specs && (this.els.specs.value = this.form.specs|| '')
this.els.specs1 && (this.els.specs1.value = this.form.specs1|| '')
this.getBeerInfoFun()
})
},
share() {
uni.showShareImageMenu({
path: this.url,
})
},
savePdf(key) {
uni.showLoading({
title: '正在生成',
mask: true,
})
uni.uploadFile({
url: base_url +
'/bar/bill/generatePdf', //仅为示例,非真实的接口地址
filePath: this.url,
header: {
'Authorization': 'Bearer ' + uni.getStorageSync('token')
},
name: 'file',
formData: {
type: 'file'
},
success: (uploadFileRes) => {
uni.downloadFile({
url: base_url + JSON.parse(uploadFileRes.data).pathFileName, //仅为示例,并非真实的资源
success: (res) => {
if (res.statusCode === 200) {
if (key == 'save') {
uni.getFileSystemManager().saveFile({
tempFilePath: res.tempFilePath,
success: (res) => {
console.log(res.savedFilePath)
uni.hideLoading()
uni.showToast({
title: '保存成功',
icon: 'success',
})
uni.openDocument({
filePath: res
.savedFilePath,
showMenu: true,
})
},
fail: (err) => {
uni.showToast({
title: '保存失败',
icon: 'none',
})
}
})
} else if (key == 'share') {
uni.showModal({
content: '分享微信好友',
success: (res1) => {
if (res1.confirm) {
uni.hideLoading()
uni.shareFileMessage({
filePath: res
.tempFilePath,
})
}else {
uni.hideLoading()
}
}
})
}
}
}
});
saveExportRecord(this.templateId)
},
fail: (err) => {
console.log(err)
uni.hideLoading()
uni.showToast({
title: '保存失败',
icon: 'none'
})
}
});
},
createPdf() {
uni.showLoading({
title: '加载中'
})
let _this = this
// 获取的画布
uni.createSelectorQuery().select('#canvas_' + _this.pageId).fields({
node: true,
size: true
}).exec((res) => {
console.log(res)
const ctx = res[0].node.getContext('2d')
const canvas = res[0].node
const dpr = uni.getWindowInfo().pixelRatio
// 设置画布的宽高
canvas.width = res[0].height * dpr
canvas.height = res[0].width * dpr
ctx.scale(dpr, dpr)
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.translate(160, 280)
ctx.rotate(90 * Math.PI / 180)
// wx.loadFontFace({
// family: 'Bitstream Vera Serif Bold',
// source: 'url("https://sungd.github.io/Pacifico.ttf")',
// scopes: ['webview', 'native'],
// success: console.log
// })
// 绘制背景
let imgArr = []
if(this.els.background) {
imgArr.push(this.els.background)
}
if(this.els.cover && this.els.cover.url) {
console.log(this.els.cover)
imgArr.push(this.els.cover.url)
}
this.downfile(imgArr, canvas).then(res => {
if(this.els.background) {
ctx.drawImage(res[0], -280, -160,560, 320)
}
if(this.els.cover && this.els.cover.url) {
ctx.drawImage(res[1], this.els.cover.x-280, this.els.cover.y-160, this.els.cover.w, this.els.cover
.h)
}
// 绘制文字
for (let key in this.els) {
if (key == "background" || key == "cover") {
continue;
} else {
if (this.els.hasOwnProperty(key)) {
let item = this.els[key];
if(key== 'specs' || key == 'specs1') {
item.value += 'ML'
}
if(key == 'amount' || key == 'amount1') {
item.value = '¥'+ item.value
}
ctx.font = `${item.fontWeight} ${item.fontSize}px Arial`
ctx.fillStyle = item.color
// 内容居右对齐
if(key== 'no') {
ctx.textAlign = 'center'
}else {
ctx.textAlign = 'left'
}
ctx.fillText(item.value, item.x-280, item.y-160)
}
}
}
// 保存图片
uni.canvasToTempFilePath({
canvas: canvas,
success: (res) => {
console.log(res.tempFilePath)
_this.url = res.tempFilePath
uni.hideLoading()
// 旋转屏幕
},
fail: (err) => {
console.log(err)
uni.showToast({
title: err,
})
uni.hideLoading()
},
})
})
})
},
downfile(imgUrls, canvas) { //下载网络图片的promise对象
var _load = function(imgUrl) {
//创建img标签
var img = canvas.createImage();
img.src = imgUrl;
//跨域选项
// img.setAttribute("crossOrigin", 'Anonymous');
return new Promise((resolve, reject) => {
//文件加载完毕
img.onload = function() {
resolve(img);
};
});
}
var _loadAll = function(imgUrls) {
var loadedImageUrls = [];
for (var i = 0, len = imgUrls.length; i < len; i++) {
loadedImageUrls.push(_load(imgUrls[i]));
}
return loadedImageUrls;
}
return Promise.all(_loadAll(imgUrls))
}
}
}
</script>
<style lang="scss" scoped>
.page {
height: 100vh;
padding: 24rpx;
background: #F2F2F2;
padding-bottom: calc(env(safe-area-inset-bottom) / 2);
display: flex;
flex-direction: column;
justify-content: space-between;
.btn {
width: 130rpx;
height: 130rpx;
border-radius: 12rpx;
background: #FFFFFF;
font-family: Roboto;
font-size: 24rpx;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #0B0E26;
transform: rotate(90deg);
}
}
</style>