溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

react打印樣式丟失如何解決

發(fā)布時間:2022-12-27 10:28:16 來源:億速云 閱讀:154 作者:iii 欄目:web開發(fā)

本篇內(nèi)容介紹了“react打印樣式丟失如何解決”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

react打印樣式丟失的解決辦法:1、通過“npm install --save html2canvas npm install jspdf --save”命令安裝jspdf;2、使用jspdf將需要打印的div轉成pdf;3、使用react重新打印即可。

vue print打印div樣式丟失 (react通用)

使用網(wǎng)上的print.js插件,打印發(fā)現(xiàn)樣式丟失。

解決方案 > 將html轉成pdf,再打印pdf

使用jspdf將需要打印的div轉成pdf(轉成的pdf樣式不會丟失,因為pdf.js是將div轉成canvas)

安裝jspdf

npm install --save html2canvas
npm install jspdf --save

上代碼

utli.js 直接復制,注意outPutPdf方法入?yún)⒓纯?/p>

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
// base64轉blob
export function toBlob(base64Data) {
  let byteString = base64Data
  if (base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = atob(base64Data.split(',')[1]); // base64 解碼
  } else {
    byteString = unescape(base64Data.split(',')[1]);
  }
  // 獲取文件類型
  const mimeString = base64Data.split(';')[0].split(":")[1]; // mime類型
  // ArrayBuffer 對象用來表示通用的、固定長度的原始二進制數(shù)據(jù)緩沖區(qū)
  // let arrayBuffer = new ArrayBuffer(byteString.length) // 創(chuàng)建緩沖數(shù)組
  // let uintArr = new Uint8Array(arrayBuffer) // 創(chuàng)建視圖
  const uintArr = new Uint8Array(byteString.length); // 創(chuàng)建視圖
  for (let i = 0; i < byteString.length; i += 1) {
    uintArr[i] = byteString.charCodeAt(i);
  }
  // 生成blob
  const blob = new Blob([uintArr], {
    type: mimeString
  })
  // 使用 Blob 創(chuàng)建一個指向類型化數(shù)組的URL, URL.createObjectURL是new Blob文件的方法,可以生成一個普通的url,可以直接使用,比如用在img.src上
  return blob;
};
/**
 * 輸出pdf
 * @param {*} idName  html元素
 * @param {*} pdfName  輸出pdf文件名
 * @param {*} isDownload  是否直接下載
 * @param {*} isPrint 是否直接打印
 * @param {*} callback  執(zhí)行后的回調(diào)  
 */
 export function outPutPdf(idName, pdfName, isDownload = false, isPrint = false, callback) {
  const element = document.getElementById(idName);  // 這個dom元素是要導出的pdf的div容器
  const w = element.offsetWidth;  // 獲得該容器的寬
  const h = element.offsetHeight;  // 獲得該容器的高
  const offsetTop = element.offsetTop; // 獲得該容器到文檔頂部的距離  
  const offsetLeft = element.offsetLeft; // 獲得該容器到文檔最左的距離
  const canvas = document.createElement("canvas");
  let abs = 0;
  const winI = document.body.clientWidth; // 獲得當前可視窗口的寬度(不包含滾動條)
  const winO = window.innerWidth; // 獲得當前窗口的寬度(包含滾動條)
  if (winO > winI) {
    abs = (winO - winI) / 2; // 獲得滾動條寬度的一半
  }
  canvas.width = w * 2; // 將畫布寬&&高放大兩倍
  canvas.height = h * 2;
  const context = canvas.getContext('2d');
  context.scale(2, 2);
  context.translate(-offsetLeft - abs, -offsetTop);
  // 這里默認橫向沒有滾動條的情況,因為offset.left(),有無滾動條的時候存在差值,因此translate的時候,要把這個差值去掉
  html2canvas(element, {
    useCORS: true, // 允許加載跨域的圖片
    allowTaint: true,
    scale: 2 // 提升畫面質(zhì)量,但是會增加文件大小
  }).then(cs => {
    const contentWidth = cs.width;
    const contentHeight = cs.height;
    // 一頁pdf顯示html頁面生成的canvas高度
    const pageHeight = contentWidth / 592.28 * 841.89;
    // 未生成pdf的html頁面高度
    let leftHeight = contentHeight;
    // 頁面偏移
    let position = 0;
    // a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
    const imgWidth = 595.28;
    const imgHeight = 592.28 / contentWidth * contentHeight;
    const pageDate = cs.toDataURL('image/jpeg', 1.0);
    const pdf = new jsPDF('', 'pt', 'a4');
    // 有兩個高度需要區(qū)分,一個是html頁面的實際高度,和生成pdf的頁面的高度(841.89)
    // 當內(nèi)容未超過pdf一頁顯示的范圍,無需分頁
    if (leftHeight < pageHeight) {
      pdf.addImage(pageDate, 'JPEG', 0, position, imgWidth, imgHeight);
    } else { // 分頁
      while (leftHeight > 0) {
        pdf.addImage(pageDate, 'JPEG', 0, position, imgWidth, imgHeight)
        leftHeight -= pageHeight;
        position -= 841.89;
        // 避免添加空白頁
        if (leftHeight > 0) {
          pdf.addPage()
        }
      }
    }
    if (isDownload) {
      pdf.save(`${pdfName}.pdf`);
    } 
    if (isPrint) {
      const link = window.URL.createObjectURL(toBlob(pdf.output('datauristring')));
            const myWindow = window.open(link);
      myWindow.print();
    }
    callback && callback(pdf);
  })
}

需要打印部分

<div id="printDiv"></div>

vue 全部代碼

<template>
  <a-modal
    v-model="visible"
    :title="title"
    :maskClosable="false"
    centered
    :width="1000"
    @cancel="close"
  >
    <div id="printDiv">
      <div v-if="!pdfing">
        <span></span>
        <span>入庫單</span>
        <a @click="printChart">打印報表</a>
      </div>
      <div class="maintain-view-title pdfing" v-else>
        <span>入庫單</span>
      </div>
      <a-form :colon="true" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
        <a-row>
          <a-col :span="8">
            <a-form-item label="入庫單號">
              <span>{{ viewInfo.accessNumber }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="供應商">
              <span>{{ viewInfo.supplier }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="入庫日期">
              <span>{{ viewInfo.accessDate && $moment(viewInfo.accessDate).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="倉庫">
              <span>{{ viewInfo.warehouse }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="來源">
              <span>{{ viewInfo.source }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="經(jīng)辦人">
              <span>{{ viewInfo.handledBy }}</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="采購單號">
              <span>{{ viewInfo.purchaseOrderNo }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="發(fā)票號">
              <span>{{ viewInfo.invoiceNo }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="合同號">
              <span>{{ viewInfo.contractNo }}</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="入庫類型">
              <span>{{ viewInfo.accessType }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="創(chuàng)建時間">
              <span>{{ viewInfo.addTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="備注">
              <span>{{ viewInfo.content }}</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-table
        style="marginTop: 10px;"
       
        :columns="columns"
        :data-source="data"
        :pagination="false"
        :loading="loading"
        row-key="id"
      >
      </a-table>
    </div>
    <template slot="footer">
      <a-button key="back" type="primary" @click="close">取消</a-button>
    </template>
  </a-modal>
</template>
<script>
import { outPutPdf } from "@/utils/util";
import { getStorageOrderTopDetail, getStorageOrderBottomListNoPage } from "@/api/stock";
export default {
  name: "StockStorageOrderViewModal",
  components: {},
  data() {
    return {
      visible: false,
      form: null,
      title: "出庫確認",
      loading: false,
      viewInfo: {},
      columns: [
        {
          title: "序號",
          key: "index",
          customRender: (text, render, index) => {
            return index + 1
          },
          align: "center"
        },
        {
          title: "產(chǎn)品編號",
          key: "productNumber",
          dataIndex: "productNumber"
        },
        {
          title: "類別",
          key: "type",
          dataIndex: "type"
        },
        {
          title: "產(chǎn)品名稱",
          key: "productName",
          dataIndex: "productName"
        },
        {
          title: "規(guī)格型號",
          dataIndex: "specifications",
          dataIndex: "specifications"
        },
        {
          title: "計量單位",
          key: "unit",
          dataIndex: "unit"
        },
        {
          title: "批次",
          key: "batch",
          dataIndex: "batch"
        },
        {
          title: "數(shù)量",
          key: "number",
          dataIndex: "number"
        },
        {
          title: "單價",
          key: "price",
          dataIndex: "price"
        },
        {
          title: "金額",
          key: "total",
          dataIndex: "total"
        },
        {
          title: "已入庫",
          key: "inbound",
          dataIndex: "inbound"
        },
        {
          title: "未入庫",
          key: "notInbound",
          dataIndex: "notInbound"
        }
      ],
      data: [],
      pdfing: false, // 打印中
    };
  },
  methods: {
    // 顯示彈框
    show(id) {
      this.visible = true;
      // 獲取上方數(shù)據(jù)
      getStorageOrderTopDetail({ id }).then(res => {
        if (res.code === 0) {
          this.viewInfo = res.data;
        }
      });
      // 獲取下方表格數(shù)據(jù)
      this.getTableData(id);
    },
    /**
     * 關閉彈框
     */
    close() {
      this.visible = false;
      this.$emit("cancel");
    },
    // 獲取表格數(shù)據(jù)
    getTableData(warehouseRegisterId) {
       const params = {
        warehouseRegisterId
      };
      getStorageOrderBottomListNoPage(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.data = res.data;
        } else {
          this.$common.showErrorMessage(res.msg || "請求出現(xiàn)錯誤,請稍后再試");
        }
      });
    },
    // 打印
    printChart() {
      this.pdfing = true;
      this.$nextTick(() => {
        outPutPdf('printDiv', '入庫單', false, true, () => {
          this.pdfing = false;
        });
      });
    }
  }
};
</script>
<style scoped>
.maintain-view-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  &.pdfing {
    justify-content: center;
  }
  .maintain-view-title-label {
    font-weight: bold;
    font-size: 1.5em;
  }
}
.container-title-block {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.viewForm {
  /deep/.ant-form-item {
    margin-bottom: 0;
  }
}
</style>

“react打印樣式丟失如何解決”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI