0

I am trying to create some PDF generator service. For that I would like to use Playwright. I create some test to see is it working, but I got the following error:

Executable doesn't exist at C:\Users\wasys\AppData\Local\ms-playwright\chromium_headless_shell-1148\chrome-win\headless_shell.exe

This would be my service:

public class PdfgeneratorService(IServiceProvider serviceProvider, ILoggerFactory loggerFactory) : IPdfgeneratorService
{
    public async Task GeneratePdf<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TComponent>
                        (string fileName, Dictionary<string, object?> htmlData) where TComponent : IComponent
    {
        await using var htmlRenderer = new HtmlRenderer(serviceProvider, loggerFactory);

        var html = await htmlRenderer.Dispatcher.InvokeAsync(async () =>
        {
            var parameters = ParameterView.FromDictionary(htmlData);
            var output = await htmlRenderer.RenderComponentAsync(typeof(TComponent), parameters);
            return output.ToHtmlString();
        });

        using var playwright = await Playwright.CreateAsync();
        //ERROR IS APPEARING IN THIS LINE
        var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
        {
            Headless = true
        });

        var page = await browser.NewPageAsync();
        await page.SetContentAsync(html);

        await page.PdfAsync(new PagePdfOptions
        {
            Format = "A4",
            Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), $"{fileName.Replace(".pdf","")}.pdf")
        });

        await page.CloseAsync();
    }
}

In the test library I created a test and used a code provided by Nick Chapsas in his tutorial.

public class PdfgeneratorServiceTests
{
    private PdfgeneratorServiceTestBuilder builder;

    public PdfgeneratorServiceTests()
    {
        this.builder = new PdfgeneratorServiceTestBuilder();
    }

    [Fact]
    public async Task GeneratePdf_Success()
    {
        var invoice = InvoiceGenerator.Generate();

        var htmlDictionary = new Dictionary<string, object?>
        {
                { "Invoice", invoice }
        };

        var exception = await Record.ExceptionAsync(async () =>
            await builder.PdfgeneratorService.GeneratePdf<InvoiceView>("Test", htmlDictionary)
        );

        Assert.Null(exception);
    }
}

I also tried to add a PostBuild script in my PdfGenerator library.

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="powershell.exe -Command $(TargetDir)playwright.ps1 install chrome;" />
</Target>

When I tried to build this library, I got an error:

Exception calling "ReadAllBytes" with "1" argument(s): "Could not find file
'D:\Temp\Solution.PdfGenerator\bin\Debug\net9.0\Microsoft.Playwright.dll'."
At D:\Temp\Solution.PdfGenerator\bin\Debug\net9.0\playwright.ps1:6 char:1
+ [Reflection.Assembly]::Load([System.IO.File]::ReadAllBytes($playwrigh ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundException
Unable to find type [Microsoft.Playwright.Program].
At D:\Temp\Solution.PdfGenerator\bin\Debug\net9.0\playwright.ps1:7 char:6
+ exit [Microsoft.Playwright.Program]::Main($args)
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Microsoft.Playwright.Program:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

In the bin/debug/net9.0 folder I have a playwright.ps1 file and a .playwright folder (if this helps).

2
  • 1
    Playwright is NOT a PDF generator. It's a tool used to control browsers for web site testing. You need to install the browsers that will be used for unit testing with playwright install etc on the web server, not the development machine. Needless to say this is a very convoluted way of generating PDFs and guaranteed to cause problems Commented Dec 16, 2024 at 12:06
  • 1
    As for the post-build error, the working directory of Exec is the project folder, ie Solution.PdfGenerator not bin\Debug\.... Use the WorkingDirectory parameter to change the working directory Commented Dec 16, 2024 at 12:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.