richTextPdf.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <!-- 富文本PDF预览与下载组件 (小程序版本) -->
  2. <template>
  3. <view class="rich-text-pdf-wrapper">
  4. <scroll-view scroll-y class="content-scroll">
  5. <view class="rich-content">
  6. <rich-text :nodes="content"></rich-text>
  7. </view>
  8. </scroll-view>
  9. </view>
  10. </template>
  11. <script>
  12. export default {
  13. name: 'RichTextPdf',
  14. props: {
  15. content: {
  16. type: String,
  17. default: ''
  18. },
  19. examId: {
  20. type: [String, Number],
  21. default: ''
  22. }
  23. },
  24. data() {
  25. return {
  26. loading: false
  27. };
  28. },
  29. methods: {
  30. // 微信小程序版本:使用 Canvas 生成图片后保存
  31. async downloadPDF() {
  32. if (!this.content) {
  33. uni.showToast({
  34. title: '没有可下载的内容',
  35. icon: 'none'
  36. });
  37. return;
  38. }
  39. this.loading = true;
  40. uni.showLoading({ title: '生成中...' });
  41. try {
  42. // 由于小程序限制,这里使用简化方案:
  43. // 1. 将富文本内容通过截图保存为图片
  44. // 2. 或者直接保存HTML内容供后续查看
  45. // 方案1: 使用 Canvas 截图(需要配合后端或使用第三方服务)
  46. // 由于小程序无法直接将 rich-text 渲染到 canvas,
  47. // 这里采用保存为图片的简化方案
  48. this._saveAsImage();
  49. } catch (error) {
  50. console.error('PDF 生成失败:', error);
  51. uni.showToast({
  52. title: 'PDF下载失败,请重试',
  53. icon: 'none'
  54. });
  55. } finally {
  56. this.loading = false;
  57. uni.hideLoading();
  58. }
  59. },
  60. // 调用后端PDF下载接口
  61. _saveAsImage() {
  62. const { config } = require('@/api/request/config.js');
  63. const token = uni.getStorageSync('token');
  64. const url = config.base_url + '/exam/user/exam/commitment/download?examId=' + this.examId;
  65. uni.downloadFile({
  66. url,
  67. header: {
  68. 'Authorization': token
  69. },
  70. success: (res) => {
  71. if (res.statusCode === 200) {
  72. uni.saveFile({
  73. tempFilePath: res.tempFilePath,
  74. success: () => {
  75. uni.showToast({ title: '下载成功', icon: 'success' });
  76. },
  77. fail: () => {
  78. uni.showToast({ title: '保存失败,请重试', icon: 'none' });
  79. }
  80. });
  81. } else {
  82. uni.showToast({ title: 'PDF下载失败', icon: 'none' });
  83. }
  84. },
  85. fail: () => {
  86. uni.showToast({ title: 'PDF下载失败,请重试', icon: 'none' });
  87. }
  88. });
  89. }
  90. }
  91. };
  92. </script>
  93. <style lang="stylus" scoped>
  94. .rich-text-pdf-wrapper {
  95. width: 100%;
  96. height: 100%;
  97. display: flex;
  98. flex-direction: column;
  99. background: #fff;
  100. }
  101. .content-scroll {
  102. flex: 1;
  103. overflow: hidden;
  104. }
  105. .rich-content {
  106. padding: 40rpx;
  107. font-size: 28rpx;
  108. line-height: 1.8;
  109. color: #333;
  110. word-wrap: break-word;
  111. }
  112. </style>