您无法从浏览器(js / wasm)使用 Playwright。所以,你必须使用另一种解决方案。例如,您可以使用jsPDF https://artskydj.github.io/jsPDF/docs/jsPDF.html。这个库在将 html 转换为 pdf 时并不完美,但也许它适合您的使用。
添加一些脚本引用index.html
使用 jsPDF(如果您愿意,也可以使用 npm 安装它们)
<script src="_framework/blazor.webassembly.js"></script>
<!-- jsPDF references -->
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection/dist/purify.min.js"></script>
创建文件wwwroot/HtmlToPdf.js
包含以下内容:
export function generateAndDownloadPdf(htmlOrElement, filename) {
const doc = new jspdf.jsPDF({
orientation: 'p',
unit: 'pt',
format: 'a4'
});
return new Promise((resolve, reject) => {
doc.html(htmlOrElement, {
callback: doc => {
doc.save(filename);
resolve();
}
});
});
}
export function generatePdf(htmlOrElement) {
const doc = new jspdf.jsPDF();
return new Promise((resolve, reject) => {
doc.html(htmlOrElement, {
callback: doc => {
const output = doc.output("arraybuffer");
resolve(new Uint8Array(output));
}
});
});
}
然后,您可以使用 Razor 组件中的脚本:
@inject IJSRuntime JSRuntime
<button type="button" @onclick="DownloadPdf">Generate</button>
@code {
async Task DownloadPdf()
{
await using var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./HtmlToPdf.js");
// Generate and download the PDF
await module.InvokeVoidAsync("generateAndDownloadPdf", "<h1>sample</h1>", "sample.pdf");
// Generate the PDF and get its content as byte[] (need .NET 6 to support Uint8Array)
var bytes = await module.InvokeAsync<byte[]>("generatePdf", "<h1>sample</h1>");
}
}