Skip to content
This repository has been archived by the owner on Dec 14, 2022. It is now read-only.

Develop #58

Open
wants to merge 34 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
4a56411
Added a smoke test.
gurustron Sep 8, 2020
c7cf359
Small clean up and a smoke test.
gurustron Sep 8, 2020
a67bf52
some more clean up
gurustron Sep 8, 2020
c4fa6b7
ConvertOptions tests.
gurustron Sep 8, 2020
f71ffd5
rename test classes
gurustron Sep 8, 2020
3e068d7
end of files.
gurustron Sep 8, 2020
fa1198a
fix some inspections.
gurustron Sep 8, 2020
80ec396
fix some inspections.
gurustron Sep 8, 2020
3efa5ae
fix some inspections.
gurustron Sep 8, 2020
a567f37
rename variable
gurustron Sep 8, 2020
18f76fd
Add tested property.
gurustron Sep 8, 2020
7854649
refactor test.
gurustron Sep 8, 2020
887979f
add support for absolute paths.
gurustron Sep 9, 2020
89a31b4
WIP
gurustron Sep 9, 2020
f352554
New DI.
gurustron Sep 9, 2020
3ba88d5
end of files.
gurustron Sep 9, 2020
e6c34b8
Path providers.
gurustron Sep 9, 2020
a9bc218
Path providers.
gurustron Sep 9, 2020
793e5c5
end of files.
gurustron Sep 9, 2020
d59d852
Merge pull request #31 from gurustron/feature/clean-up
fpanaccia Sep 10, 2020
2214201
Merge branch 'master' into develop
fpanaccia Sep 10, 2020
1b6b2ce
Merge remote-tracking branch 'upstream/master' into feature/allow-abs…
gurustron Sep 10, 2020
d426a33
Merge remote-tracking branch 'upstream/develop' into feature/allow-ab…
gurustron Sep 11, 2020
91407f6
Xml comments.
gurustron Sep 11, 2020
b959402
Add exception
gurustron Sep 11, 2020
eb51e36
small comment change.
gurustron Sep 11, 2020
30127a7
end of files.
gurustron Sep 11, 2020
dd6ee51
rename.
gurustron Sep 11, 2020
e51c9f3
rename.
gurustron Sep 11, 2020
23586f4
Improve test
gurustron Sep 11, 2020
fd717e0
Introduced IWkhtmlDriver.
gurustron Sep 11, 2020
4024f60
rename to ExactPathProvider
gurustron Sep 12, 2020
2691478
Merge pull request #32 from gurustron/feature/allow-absolute-path
fpanaccia Sep 13, 2020
4b03c51
Enable local file access for wkhtmltopdf 0.12.6
slawomirbrys Jun 25, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions Wkhtmltopdf.NetCore.Test/Options/ConvertOptionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using Wkhtmltopdf.NetCore.Interfaces;
using Wkhtmltopdf.NetCore.Options;

namespace Wkhtmltopdf.NetCore.Test.Options
{
public class ConvertOptionsTests
{
[Test]
public void ConvertsEmpty()
{
IConvertOptions options = new ConvertOptions();
Assert.AreEqual(string.Empty, options.GetConvertOptions());
}

[Test]
public void ConvertsAll()
{
var switches = new List<string>();
var counter = 0;
IConvertOptions options = new ConvertOptions
{
Copies = AddWithFormat(++counter, "--copies {0}"),
EnableForms = AddWithValue(true, "--enable-forms"),
FooterHtml = AddWithFormat(nameof(ConvertOptions.FooterHtml), "--footer-html {0}"),
FooterSpacing = AddWithFormat(++counter, "--footer-spacing {0}"),
HeaderHtml = AddWithFormat(nameof(ConvertOptions.HeaderHtml), "--header-html {0}"),
HeaderSpacing = AddWithFormat(++counter, "--header-spacing {0}"),
PageHeight = AddWithFormat(++counter + 0.5, "--page-height {0}"),
PageMargins = AddWithValues(new Margins(1, 2, 3, 4),
new[] {"-B 3", "-L 4", "-R 2", "-T 1"}),
PageOrientation = AddWithFormat(Orientation.Landscape, "-O {0}"),
PageSize = AddWithFormat(Size.Legal, "-s {0}"),
PageWidth = AddWithFormat(++counter + 0.5, "--page-width {0}"),
IsGrayScale = AddWithValue(true, "-g"),
IsLowQuality = AddWithValue(true, "-l"),
Replacements = AddWithValues(new Dictionary<string, string>
{
{"one", "1"},
{"two", "2"}
},
new[] {"--replace \"one\" \"1\"", "--replace \"two\" \"2\""})
};

var result = options.GetConvertOptions();

var allSwitches = typeof(ConvertOptions).GetProperties()
.Select(p => p.GetCustomAttribute<OptionFlag>())
.Where(a => a != null)
.Select(a => a.Name);
foreach (var @switch in allSwitches)
{
StringAssert.Contains(@switch, result, $"Switch \"{@switch}\" was not set up.");
}

var sb = new StringBuilder(result);
foreach (var @switch in switches)
{
StringAssert.Contains(@switch, result, $"Should contain \"{@switch}\".");
sb.Replace(@switch, string.Empty);
}
Assert.IsEmpty(sb.ToString().Trim());

// Local functions

T AddWithValue<T>(T value, string switchToAdd)
{
switches.Add(switchToAdd);
return value;
}

T AddWithValues<T>(T value, IEnumerable<string> switchesToAdd)
{
switches.AddRange(switchesToAdd);
return value;
}

T AddWithFormat<T>(T value, string formatToAdd)
{
switches.Add(string.Format(formatToAdd, value));
return value;
}
}

[Test]
public void ConvertsChild()
{
IConvertOptions options = new CustomConvertOptions
{
Test1 = nameof(CustomConvertOptions.Test1),
Test2 = true,
Ignored1 = "Ignored",
Ignored2 = "Ignored",
Ignored3 = "Ignored"
};

var result = options.GetConvertOptions();

Assert.AreEqual($"-t1 {nameof(CustomConvertOptions.Test1)} -t2", result);
}

[SuppressMessage("ReSharper", "NotAccessedField.Local")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
private class CustomConvertOptions : ConvertOptions
{
[OptionFlag("-t1")] public string Test1 { get; set; }
[OptionFlag("-t2")] public bool Test2 { get; set; }
[OptionFlag("-ignr")] public string Ignored1;
public string Ignored2 { get; set; }
public string Ignored3;
}
}
}
26 changes: 26 additions & 0 deletions Wkhtmltopdf.NetCore.Test/Options/MarginsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using NUnit.Framework;
using Wkhtmltopdf.NetCore.Options;

namespace Wkhtmltopdf.NetCore.Test.Options
{
public class MarginsTests
{
[TestCase("-B 1 -L 2 -R 3 -T 4", 1,2,3,4)]
[TestCase("-B 1 -L 2 -R 3", 1,2,3,null)]
[TestCase("-B 1 -L 2", 1,2,null,null)]
[TestCase("-B 1", 1,null,null,null)]
[TestCase("", null,null,null,null)]
public void Converts(string expected, int? bottom, int? left, int? right, int? top)
{
var margins = new Margins
{
Bottom = bottom,
Left = left,
Right = right,
Top = top,
};

Assert.AreEqual(expected, margins.ToString());
}
}
}
95 changes: 95 additions & 0 deletions Wkhtmltopdf.NetCore.Test/SmokeTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NUnit.Framework;

namespace Wkhtmltopdf.NetCore.Test
{
/// <summary>
/// Some smoke tests including legacy API.
/// </summary>
public class SmokeTest
{
[SetUp]
public void SetRotativaPath()
{
#pragma warning disable 612
WkhtmltopdfConfiguration.RotativaPath = AppDomain.CurrentDomain.BaseDirectory + "Rotativa";
#pragma warning restore 612
}

[TearDown]
public void ClearRotativaPath()
{
#pragma warning disable 612
WkhtmltopdfConfiguration.RotativaPath = null;
#pragma warning restore 612
}

[Test]
public void CanConvert()
{
var generatePdf = new GeneratePdf(null);
generatePdf.GetPDF("<p><h1>Hello World</h1>This is html rendered text</p>");
}

[Test]
public void CanConvertWithLegacyProvider()
{
var generatePdf = new GeneratePdf(null, new WkhtmlDriver(new LegacyPathProvider()));
generatePdf.GetPDF("<p><h1>Hello World</h1>This is html rendered text</p>");
}

[Test]
public void CanConvertWithAbsoluteProvider()
{
var path = new LegacyPathProvider().GetPath();
var generatePdf = new GeneratePdf(null, new WkhtmlDriver(new ExactPathProvider(path)));
generatePdf.GetPDF("<p><h1>Hello World</h1>This is html rendered text</p>");
}

[Test]
public void LegacyResolutionWorks()
{
ClearRotativaPath();
using var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
#pragma warning disable 612
webBuilder.ConfigureServices(services => services.AddWkhtmltopdf());
#pragma warning restore 612
})
.Build();

using var serviceScope = host.Services.CreateScope();
var generatePdf = serviceScope.ServiceProvider.GetService<IGeneratePdf>();
generatePdf.GetPDF("<p><h1>Hello World</h1>This is html rendered text</p>");
}

[Test]
public void ResolutionWorks()
{
ClearRotativaPath();
using var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder => { })
.ConfigureServices(services => services
.AddMvc()
.AddWkhtmltopdf<LegacyPathProvider>())
.Build();

using var serviceScope = host.Services.CreateScope();
var generatePdf = serviceScope.ServiceProvider.GetService<IGeneratePdf>();
generatePdf.GetPDF("<p><h1>Hello World</h1>This is html rendered text</p>");
}

[Test]
public void ThrowsForMissingExecutable()
{
var path = "not_valid_path";
var generatePdf = new GeneratePdf(null, new WkhtmlDriver(new ExactPathProvider(path)));

var ex = Assert.Throws<WkhtmlDriverException>(() => generatePdf.GetPDF(""));
StringAssert.Contains(path, ex.Message);
}
}
}
36 changes: 36 additions & 0 deletions Wkhtmltopdf.NetCore.Test/Wkhtmltopdf.NetCore.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Wkhtmltopdf.NetCore\Wkhtmltopdf.NetCore.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Rotativa\Mac\" />
<Folder Include="Rotativa\Linux\" />
<Folder Include="Rotativa\Windows\" />
</ItemGroup>

<ItemGroup>
<None Include="..\Wkhtmltopdf.NetCore\Rotativa\Linux\wkhtmltopdf" Link="Rotativa\Linux\wkhtmltopdf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="..\Wkhtmltopdf.NetCore\Rotativa\Windows\wkhtmltopdf.exe" Link="Rotativa\Windows\wkhtmltopdf.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="..\Wkhtmltopdf.NetCore\Rotativa\Mac\wkhtmltopdf" Link="Rotativa\Mac\wkhtmltopdf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions Wkhtmltopdf.NetCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 15.0.28010.2041
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Wkhtmltopdf.NetCore", "Wkhtmltopdf.NetCore\Wkhtmltopdf.NetCore.csproj", "{AD64E16D-A86E-47AD-8DEF-0B1346A5E30D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wkhtmltopdf.NetCore.Test", "Wkhtmltopdf.NetCore.Test\Wkhtmltopdf.NetCore.Test.csproj", "{DAB48830-F9C3-4257-A9BB-5797196CB654}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +17,10 @@ Global
{AD64E16D-A86E-47AD-8DEF-0B1346A5E30D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AD64E16D-A86E-47AD-8DEF-0B1346A5E30D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AD64E16D-A86E-47AD-8DEF-0B1346A5E30D}.Release|Any CPU.Build.0 = Release|Any CPU
{DAB48830-F9C3-4257-A9BB-5797196CB654}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DAB48830-F9C3-4257-A9BB-5797196CB654}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DAB48830-F9C3-4257-A9BB-5797196CB654}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DAB48830-F9C3-4257-A9BB-5797196CB654}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
22 changes: 22 additions & 0 deletions Wkhtmltopdf.NetCore/Configuration/ExactPathProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Wkhtmltopdf.NetCore
{
/// <summary>
/// Provides exact specified path to wkthmltopdf/wkthmltoimage.
/// </summary>
public class ExactPathProvider : IWkhtmltopdfPathProvider
{
private readonly string _path;

/// <summary>
/// Constructs new instance of <see cref="ExactPathProvider" />. Uses provided path as is.
/// </summary>
/// <param name="path">Path to wkthmltopdf/wkthmltoimage.</param>
public ExactPathProvider(string path = "wkhtmltopdf")
{
_path = path;
}

/* <inheritDoc /> */
public string GetPath() => _path;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Wkhtmltopdf.NetCore
{
public interface IWkhtmltopdfPathProvider
{
/// <summary>
/// Gets path to executable.
/// </summary>
/// <returns>Path to executable.</returns>
string GetPath();
}
}
51 changes: 51 additions & 0 deletions Wkhtmltopdf.NetCore/Configuration/LegacyPathProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Wkhtmltopdf.NetCore
{
/// <summary>
/// Emulates legacy registration behavior.
/// </summary>
public class LegacyPathProvider : IWkhtmltopdfPathProvider
{
private readonly string _rotativaLocation;

/// <summary>
/// Constructs path from <see cref="AppDomain.CurrentDomain" />'s base directory, <see cref="wkhtmltopdfRelativePath" />,
/// <para />
/// OS dependent folder and executable name.
/// </summary>
/// <param name="wkhtmltopdfRelativePath"></param>
public LegacyPathProvider(string wkhtmltopdfRelativePath = "Rotativa")
{
var wkhtmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, wkhtmltopdfRelativePath);

if (!Directory.Exists(wkhtmlPath))
{
throw new Exception("Folder containing wkhtmltopdf not found, searched for " + wkhtmlPath);
}

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_rotativaLocation = Path.Combine(wkhtmlPath, "Windows", "wkhtmltopdf.exe");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
_rotativaLocation = Path.Combine(wkhtmlPath, "Mac", "wkhtmltopdf");
}
else
{
_rotativaLocation = Path.Combine(wkhtmlPath, "Linux", "wkhtmltopdf");
}

if (!File.Exists(_rotativaLocation))
{
throw new Exception("wkhtmltopdf not found, searched for " + _rotativaLocation);
}
}

/* <inheritDoc /> */
public string GetPath() => _rotativaLocation;
}
}
Loading