Skip to content

Commit

Permalink
Simple mvc sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Rickedb committed May 13, 2024
1 parent 9e2f0a5 commit 3d0958d
Show file tree
Hide file tree
Showing 84 changed files with 74,995 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ name: master

on:
push:
paths:
- 'src/*'
- '.github/*'
branches:
- master

Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,42 @@ However there are some abstractions created for Razor and Blazor server componen

> If you run in both OS like Windows for development and publish on Linux, you should consider downloading both.
After that you'll need to install the binaries or have them at your folder.

#### Dockerfile

```dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy AS base
WORKDIR /app
RUN apt-get update && \
apt-get install -y wget wkhtmltopdf

USER app
EXPOSE 8080
EXPOSE 8081
```

> It is possible to download the `.deb` and install it, if necessary
#### Windows

Add the files to be copied to your publish folder by adding on your `.csproj`:

```xml
<ItemGroup>
<None Update="<path>\wkhtmltopdf.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="<path>\wkhtmltox.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
```

### Usage examples

For more examples, please check the [samples folder](https://github.com/Rickedb/wkhtmltowrapper/tree/master/samples).

#### Basic usage
```csharp
var wrapper = new WkHtmlToPdfWrapper(); //When not providing the root path of the executable, it considers the same path of your assembly
Expand Down
30 changes: 30 additions & 0 deletions samples/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
44 changes: 44 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using WkHtmlTo.Wrapper.AspNetCore.Mvc;
using WkHtmlTo.Wrapper.Samples.Mvc.Models;

namespace WkHtmlTo.Wrapper.Samples.Mvc.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}

public IActionResult WeatherForecasts()
{
return View(WeatherForecast.Forecasts);
}

public IActionResult DownloadWeatherForecasts()
{
var result = new PdfFileStreamResult("WeatherForecasts", WeatherForecast.Forecasts, ViewData);
return result;
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
28 changes: 28 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy AS base
WORKDIR /app
RUN apt-get update && \
apt-get install -y wget wkhtmltopdf

USER app
EXPOSE 8080
EXPOSE 8081

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["WkHtmlTo.Wrapper.Samples.Mvc/WkHtmlTo.Wrapper.Samples.Mvc.csproj", "WkHtmlTo.Wrapper.Samples.Mvc/"]
RUN dotnet restore "./WkHtmlTo.Wrapper.Samples.Mvc/WkHtmlTo.Wrapper.Samples.Mvc.csproj"
COPY . .
WORKDIR "/src/WkHtmlTo.Wrapper.Samples.Mvc"
RUN dotnet build "./WkHtmlTo.Wrapper.Samples.Mvc.csproj" -c $BUILD_CONFIGURATION -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./WkHtmlTo.Wrapper.Samples.Mvc.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WkHtmlTo.Wrapper.Samples.Mvc.dll"]
9 changes: 9 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace WkHtmlTo.Wrapper.Samples.Mvc.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
32 changes: 32 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Models/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace WkHtmlTo.Wrapper.Samples.Mvc.Models
{
public class WeatherForecast
{
private static Lazy<IEnumerable<WeatherForecast>> _forecasts = new Lazy<IEnumerable<WeatherForecast>>(GetRandomForecast);
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }

public static IEnumerable<WeatherForecast> Forecasts => _forecasts.Value;

private static IEnumerable<WeatherForecast> GetRandomForecast()
{
var startDate = DateTime.Now;
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
}
}
29 changes: 29 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
var path = OperatingSystem.IsWindows() ? "./wkhtmltox" : string.Empty;
builder.Services.AddWkHtmlToWrapper(path);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5091"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7107;http://localhost:5091"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true,
"remoteDebugEnabled": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:13150",
"sslPort": 44386
}
}
}
8 changes: 8 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@{
ViewData["Title"] = "Home Page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@model IEnumerable<WeatherForecast>
@{
}
<h2>Forecasts</h2>
<div class="no-print d-flex">
<a asp-area="" asp-controller="Home" asp-action="DownloadWeatherForecasts" target="_blank" class="btn btn-primary float-end">Print</a>
</div>
<table class="table table-bordered mt-3">
<thead>
<tr>
<th>Date</th>
<th>Temperature (°C/°F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach(var forecast in Model)
{
<tr>
<td>@forecast.Date</td>
<td>@($"{forecast.TemperatureC}°/{forecast.TemperatureF")</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
25 changes: 25 additions & 0 deletions samples/WkHtmlTo.Wrapper.Samples.Mvc/Views/Shared/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Loading

0 comments on commit 3d0958d

Please sign in to comment.