由于您没有提到转换后的页面是在 Vue 或 Blade 中,所以我将两种方式进行解释。
这是Library,您只需要设计一个 Blade 视图,然后做这样的事情
Route::get('/doc', function () {
//
$data = Marketers::all();
// LoadView with $data
$pdf = PDF::loadView('pdf',$data)->setPaper('A4');
// LoadView with Compact
$pdf = PDF::loadView('pdf',compact('data'))->setPaper('A4');
// Then Download it
return $pdf->download('pdf.pdf');
});
现在在 Vue 中你需要jsPDF和htmlToCanvas或htmlToIMage
我使用HTMLtoImage波斯语是因为我有一些波斯语的字符问题,所以我会根据HtmlToImage图书馆帮助你。
<template>
// Part you want to Convert to pdf or ...
<div ref="contentz" id="jsPdf" >
// Contents
<div/>
</template>
downloadFull(t) {
let self = this
switch (t) {
case 1:
const doc = new jsPDF("l", "mm", "a4");
htmlToImage.toCanvas(document.getElementById('jsPdf'))
.then(function (canvas) {
var img = canvas.toDataURL("image/jpeg");
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
doc.addImage(img, 'JPEG', 0, 0, width, 0);
doc.save('app.pdf');
})
.catch(function (error) {
self.$notifications.failedNotificationOnGetData(self)
});
break;
case 2:
htmlToImage.toJpeg(document.getElementById('jsPdf'), { quality: 1 })
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'kalabala.jpeg';
link.href = dataUrl;
link.click();
})
.catch(function (error) {
self.$notifications.failedNotificationOnGetData(self)
});
}
break;
default:
break;
}
}
所以这是我的函数,downloadFull(t)它将是文件类型,您可能不需要它,或者您可以使用简单的 if/else 来改进它,无需切换,首先您将导入如下库:
import jsPDF from 'jspdf';
import htmlToImage from 'html-to-image';
然后为 设置页面尺寸jsPDF,然后简单地使用HtmlToImage来获取画布,然后使用变量设置宽度、高度和图像画布,然后简单地将图像添加到doc并保存。我的功能是相同的,但在第一个开关情况下我会得到PDF,在第二个我会得到JPEG。
如果您尝试使用第一种方式但在 Vue 页面中获取下载链接,您必须像我在上面解释的那样执行控制器,那么VUE当您进行 API 调用时,您应该使用 BLOB 下载文件。这是示例:
getPDF(type) {
axios({
url : '/api/api_name/exportPDF',
method: 'POST',
responseType: 'blob'
})
.then(res => {
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'pdf.pdf');
document.body.appendChild(link);
link.click();
})
},
祝你好运。