预览
- const PDFPreview = (url) => {
- window.open(url,''_blank''); // 新窗口打开生成的图像
- }
下载
- const PDFDown = async (url) => {
- const response = await axios.get(url, { responseType: ''blob'' });
- const pdfUrl = window.URL.createObjectURL(new Blob([response.data]));
- const link = document.createElement(''a'');
- link.href = pdfUrl;
- link.setAttribute(''download'', ''专题图.pdf''); // 设置下载后保存的文件名
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
生成
需求:截取某个div中的内容生成pdf文件,可自定义pdf大小,支持下载与预览
在div中添加 ref="thematicMap" ,定义 const thematicMap = ref(null)
在pdf.js中
- import html2canvas from "html2canvas";
- import jsPDF from "jspdf";
-
- export const downloadPDF = (page,type,value) => {
- return new Promise((resolve, reject) => {
- html2canvas(page, {
- useCORS: true,
- scale: 4,
- }).then(function (canvas) {
- let pdfBlob = canvas2PDF(canvas, type, value);
- resolve(pdfBlob);
- }).catch(function (error) {
- reject(error);
- });
- });
- };
-
- const canvas2PDF = (canvas,type,value) => {
- let contentWidth = canvas.width;
- let contentHeight = canvas.height;
- let imgWidth;
- let imgHeight;
- let direction;
- let paper;
- let title;
- //type 1a4横向 2a4纵向 3a3横向 4a3纵向
- //a4纸的尺寸210x297 a3 297x420
- if(type.paper===''自定义''){
- let height = contentHeight/297
- let width = contentWidth/420
- if(width<height){
- imgHeight = 297;
- imgWidth = 297/contentHeight * contentWidth;
- }else {
- imgWidth = 420;
- imgHeight = 420/contentWidth * contentHeight;
- }
- direction = "l"
- paper = ''a3''
- title = ''A3横向''
- }else if(type.paper===''A4横向''){
- imgHeight = 210;
- imgWidth = 297;
- direction = "l"
- paper = ''a4''
- title = ''A4横向''
- }else if(type.paper===''A4纵向''){
- imgWidth = 210;
- imgHeight = 297;
- direction = "p"
- paper = ''a4''
- title = ''A4纵向''
- }else if(type.paper===''A3横向''){
- imgHeight = 297;
- imgWidth = 420;
- direction = "l"
- paper = ''a3''
- title = ''A3横向''
- }else if(type.paper===''A3纵向''){
- imgWidth = 297;
- imgHeight = 420;
- direction = "p"
- paper = ''a3''
- title = ''A3纵向''
- }
- // 第一个参数: l:横向 p:纵向
- // 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
- let pdf = new jsPDF(direction, "mm",paper);
- pdf.addImage(
- canvas.toDataURL("image/jpeg", 1.0),
- "JPEG",
- 0,
- 0,
- imgWidth,
- imgHeight
- );
- if(value===''0''){
- //添加内容到 doc
- const blob = pdf.output(''blob'')
- //创建用于预览的 URL
- const url = URL.createObjectURL(blob)
- //显示 PDF 预览,例如在一个新窗口中
- window.open(url,''_blank''); // 新窗口打开生成的图像
- }else if(value===''1''){
- pdf.save("专题制图导出"+title+".pdf");
- }
- else if(value===''2''){
- // 将 pdf 数据转换为 Blob 对象
- const blob = pdf.output(''blob'')
- let pdfFile = new File([blob], "专题制图导出"+title+".pdf", { type: ''application/pdf'' });
- return pdfFile
- }
- };
在vue组件中引用根据传入的dom生成pdf,根据传入的type决定是预览、下载还是返回pdf文件
预览
downloadPDF(thematicMap.value,ployForm.value,type)
获取pdf文件并上传
- downloadPDF(thematicMap.value,ployForm.value,type).then((a)=>{
- pdfFile = a
- //执行上传方法
- })