반응 인쇄 스타일이 손실된 경우 수행할 작업

藏色散人
풀어 주다: 2022-12-21 15:45:48
원래의
2224명이 탐색했습니다.

반응에서 인쇄 스타일 손실에 대한 해결 방법: 1. "npm install --save html2canvas npm install jspdf --save" 명령을 통해 jspdf를 설치합니다. 2. jspdf를 사용하여 인쇄해야 하는 div를 pdf로 변환합니다. 재인쇄에 반응하세요. 그게 다입니다.

반응 인쇄 스타일이 손실된 경우 수행할 작업

이 튜토리얼의 운영 환경: Windows 10 시스템, React18 버전, Dell G3 컴퓨터.

리액트 인쇄 스타일이 사라졌다면 어떻게 해야 하나요?

vue print print div 스타일이 손실되었습니다(반응용 범용)

온라인 print.js 플러그인을 사용하여 인쇄하고 스타일이 손실된 것을 확인하세요.

해결 방법> html을 pdf로 변환한 다음 pdf를 인쇄하세요

jspdf를 사용하여 인쇄해야 하는 div를 pdf로 변환하세요(pdf.js가 div를 캔버스로 변환하므로 변환된 PDF 스타일은 손실되지 않습니다)

설치 jspdf

npm install --save html2canvas
로그인 후 복사
npm install jspdf --save
로그인 후 복사

코드를 직접 복사

utli.js하고, outPutPdf 메소드에 주의하여 매개변수를 입력하세요

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 对象用来表示通用的、固定长度的原始二进制数据缓冲区
  // let arrayBuffer = new ArrayBuffer(byteString.length) // 创建缓冲数组
  // let uintArr = new Uint8Array(arrayBuffer) // 创建视图
  const uintArr = new Uint8Array(byteString.length); // 创建视图
  for (let i = 0; i < byteString.length; i += 1) {
    uintArr[i] = byteString.charCodeAt(i);
  }
  // 生成blob
  const blob = new Blob([uintArr], {
    type: mimeString
  })
  // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
  return blob;
};
/**
 * 输出pdf
 * @param {*} idName  html元素
 * @param {*} pdfName  输出pdf文件名
 * @param {*} isDownload  是否直接下载
 * @param {*} isPrint 是否直接打印
 * @param {*} callback  执行后的回调  
 */
 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(&#39;2d&#39;);
  context.scale(2, 2);
  context.translate(-offsetLeft - abs, -offsetTop);
  // 这里默认横向没有滚动条的情况,因为offset.left(),有无滚动条的时候存在差值,因此translate的时候,要把这个差值去掉
  html2canvas(element, {
    useCORS: true, // 允许加载跨域的图片
    allowTaint: true,
    scale: 2 // 提升画面质量,但是会增加文件大小
  }).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(&#39;image/jpeg&#39;, 1.0);
    const pdf = new jsPDF(&#39;&#39;, &#39;pt&#39;, &#39;a4&#39;);
    // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面的高度(841.89)
    // 当内容未超过pdf一页显示的范围,无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(pageDate, &#39;JPEG&#39;, 0, position, imgWidth, imgHeight);
    } else { // 分页
      while (leftHeight > 0) {
        pdf.addImage(pageDate, &#39;JPEG&#39;, 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(&#39;datauristring&#39;)));
            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(&#39;YYYY-MM-DD HH:mm:ss&#39;) }}</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="经办人">
              <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="发票号">
              <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="创建时间">
              <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: "产品编号",
          key: "productNumber",
          dataIndex: "productNumber"
        },
        {
          title: "类别",
          key: "type",
          dataIndex: "type"
        },
        {
          title: "产品名称",
          key: "productName",
          dataIndex: "productName"
        },
        {
          title: "规格型号",
          dataIndex: "specifications",
          dataIndex: "specifications"
        },
        {
          title: "计量单位",
          key: "unit",
          dataIndex: "unit"
        },
        {
          title: "批次",
          key: "batch",
          dataIndex: "batch"
        },
        {
          title: "数量",
          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;
      // 获取上方数据
      getStorageOrderTopDetail({ id }).then(res => {
        if (res.code === 0) {
          this.viewInfo = res.data;
        }
      });
      // 获取下方表格数据
      this.getTableData(id);
    },
    /**
     * 关闭弹框
     */
    close() {
      this.visible = false;
      this.$emit("cancel");
    },
    // 获取表格数据
    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 || "请求出现错误,请稍后再试");
        }
      });
    },
    // 打印
    printChart() {
      this.pdfing = true;
      this.$nextTick(() => {
        outPutPdf(&#39;printDiv&#39;, &#39;入库单&#39;, 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 동영상 튜토리얼"

위 내용은 반응 인쇄 스타일이 손실된 경우 수행할 작업의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!