| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- <!-- 富文本PDF预览与下载组件 (小程序版本) -->
- <template>
- <view class="rich-text-pdf-wrapper">
- <scroll-view scroll-y class="content-scroll">
- <view class="rich-content">
- <rich-text :nodes="content"></rich-text>
- </view>
- </scroll-view>
- </view>
- </template>
- <script>
- export default {
- name: 'RichTextPdf',
- props: {
- content: {
- type: String,
- default: ''
- }
- },
- data() {
- return {
- loading: false
- };
- },
- methods: {
- // 微信小程序版本:使用 Canvas 生成图片后保存
- async downloadPDF() {
- if (!this.content) {
- uni.showToast({
- title: '没有可下载的内容',
- icon: 'none'
- });
- return;
- }
- this.loading = true;
- uni.showLoading({ title: '生成中...' });
- try {
- // 由于小程序限制,这里使用简化方案:
- // 1. 将富文本内容通过截图保存为图片
- // 2. 或者直接保存HTML内容供后续查看
- // 方案1: 使用 Canvas 截图(需要配合后端或使用第三方服务)
- // 由于小程序无法直接将 rich-text 渲染到 canvas,
- // 这里采用保存为图片的简化方案
- await this._saveAsImage();
- } catch (error) {
- console.error('PDF 生成失败:', error);
- uni.showToast({
- title: 'PDF下载失败,请重试',
- icon: 'none'
- });
- } finally {
- this.loading = false;
- uni.hideLoading();
- }
- },
- // 简化方案:保存为图片
- async _saveAsImage() {
- // 微信小程序中,rich-text 无法直接转为 canvas
- // 需要使用以下方案之一:
- // 1. 后端生成PDF接口
- // 2. 使用 web-view 加载HTML后截图
- // 3. 提示用户长按保存或分享
- uni.showModal({
- title: '提示',
- content: '微信小程序暂不支持直接生成PDF,建议在电脑端下载或长按保存内容',
- showCancel: false
- });
- // 如果有后端PDF生成接口,可以这样调用:
- // const result = await this._callBackendPdfApi();
- // if (result.pdfUrl) {
- // uni.downloadFile({
- // url: result.pdfUrl,
- // success: (res) => {
- // uni.saveFile({
- // tempFilePath: res.tempFilePath,
- // success: () => {
- // uni.showToast({ title: '保存成功' });
- // }
- // });
- // }
- // });
- // }
- },
- // 调用后端PDF生成接口(示例)
- async _callBackendPdfApi() {
- return new Promise((resolve, reject) => {
- uni.request({
- url: '/api/generate-pdf', // 替换为实际接口
- method: 'POST',
- data: {
- htmlContent: this.content
- },
- success: (res) => {
- if (res.data.code === 200) {
- resolve(res.data.data);
- } else {
- reject(new Error(res.data.message));
- }
- },
- fail: reject
- });
- });
- }
- }
- };
- </script>
- <style lang="stylus" scoped>
- .rich-text-pdf-wrapper {
- width: 100%;
- height: 100%;
- display: flex;
- flex-direction: column;
- background: #fff;
- }
- .content-scroll {
- flex: 1;
- overflow: hidden;
- }
- .rich-content {
- padding: 40rpx;
- font-size: 28rpx;
- line-height: 1.8;
- color: #333;
- word-wrap: break-word;
- }
- </style>
|