【问题标题】:How can I create a pdf for download in blazor wasm如何在 blazor wasm 中创建 pdf 以供下载
【发布时间】:2021-12-21 10:37:39
【问题描述】:

在 blazor wasm 中,我想创建一个 pdf 并使其可下载。我测试了pdfflow,但只能让它在控制台应用程序中运行。有几种商业解决方案(devexpress、syncfusion),但它们确实很昂贵。 接下来,我浏览了博客文章Generate PDF files using an html template and Playwright,这对我来说似乎很有希望。不幸的是,它不包含完整的示例,我无法让它运行。这是我尝试过的: 我将 template.html 添加到 wwwroot 文件夹。

template.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="invoice.css">
</head>
<body style="padding: 3rem">
    <h1>Invoice</h1>
    Awesome company<br />
</body>
</html>

我添加了一个调用CreatePdf() 的按钮。我从上面的链接中复制了代码,并根据我的需要进行了修改(例如,没有提供方法 LoadOrder(orderId))。

Index.razor

@page "/"
@using Scriban
@using System.IO
@using Microsoft.Playwright
@inject HttpClient Http

<button class="btn btn-primary" @onclick="CreatePdf">pdf</button>

@code{ 
private async Task CreatePdf()
{
    //var templateContent = File.ReadAllText("template.html");
    var templateContent = await Http.GetStringAsync("template.html");
    var template = Template.Parse(templateContent);

    //var templateData = new { Invoice = LoadOrder(orderId) };
    //var pageContent = template.Render(templateData);
    var pageContent = "testString";

    //var dataUrl = "data:text/html;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(pageContent));
    var dataUrl = "data:text/html;base64," + pageContent;

我添加了以下两行,因为没有声明“浏览器”(Source from playwright)。

// Here, the app crashes.
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Webkit.LaunchAsync();

await using var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await page.GotoAsync(dataUrl, new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle });

var output = await page.PdfAsync(new PagePdfOptions
{
    Format = "A4",
    Landscape = false,
});

await File.WriteAllBytesAsync("output.pdf", output);
} }

问题

  1. 如何让上面的代码运行?
  2. 或者有没有我忽略的免费工具可以轻松创建 pdf?

非常感谢!

【问题讨论】:

    标签: pdf-generation blazor-webassembly


    【解决方案1】:

    您不能从浏览器 (js / wasm) 使用 Playwright。因此,您必须使用另一种解决方案。例如,您可以使用jsPDF。这个库在将 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/dompurify@2.3.3/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>");
        }
    }
    

    【讨论】:

    • 完美。非常感谢!
    猜你喜欢
    • 2020-07-18
    • 2021-08-02
    • 1970-01-01
    • 2021-01-12
    • 2022-10-06
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    相关资源
    最近更新 更多