404 html c# pdf itextsharp
我想通过将HTML内容传递给函数来生成PDF.我已经为此使用了iTextSharp,但是当它遇到表格并且布局变得混乱时它表现不佳.
有没有更好的办法?
Mar*_*rko 186
试试wkhtmtopdf.这是迄今为止我发现的最好的工具.
对于.NET,您可以使用此小型库轻松调用wkhtmtopdf命令行实用程序.
Ane*_*lou 185
编辑: 使用PdfSharp的PDF的新建议HTML渲染器
(在尝试wkhtmltopdf并建议避免它之后)
HtmlRenderer.PdfSharp是一个100%完全C#托管代码,易于使用,线程安全,最重要的是免费 (新BSD许可证)解决方案.
用法
使用示例方法.
public static Byte[] PdfSharpConvert(String html)
{
Byte[] res = null;
using (MemoryStream ms = new MemoryStream())
{
var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
pdf.Save(ms);
res = ms.ToArray();
}
return res;
}
Run Code Online (Sandbox Code Playgroud)一个很好的替代是一个免费版本的iTextSharp的
在版本4.1.6之前,iTextSharp根据LGPL许可证获得许可,版本直到4.16(或者也可能有叉子)作为包提供,可以自由使用.当然有人可以使用续5+ 付费版本.
我试图在我的项目中集成wkhtmltopdf解决方案,并遇到了一些障碍.
我个人会避免在托管企业应用程序上使用基于wkhtmltopdf的解决方案,原因如下.
--- PRE编辑部分---
对于想要在更简单的应用程序/环境中从html生成pdf的任何人,我将旧帖子作为建议.
https://www.nuget.org/packages/TuesPechkin/
或者特别是对于MVC Web应用程序 (但我认为您可以在任何.net应用程序中使用它)
https://www.nuget.org/packages/Rotativa/
他们都利用 wkhtmtopdf二进制文件将html转换为pdf.它使用webkit引擎来呈现页面,因此它也可以解析css样式表.
它们提供易于使用的与C#的无缝集成.
Rotativa还可以从任何Razor View 直接生成PDF .
此外,对于真实的Web应用程序,他们还管理线程安全等...
小智 29
大多数HTML到PDF转换器依赖于IE来进行HTML解析和渲染.当用户更新他们的IE时,这可能会中断.这是一个不依赖IE的.
代码是这样的:
EO.Pdf.HtmlToPdf.ConvertHtml(htmlText, pdfFileName);
Run Code Online (Sandbox Code Playgroud)
与许多其他转换器一样,您可以传递文本,文件名或Url.结果可以保存到文件或流中.
Mar*_*kus 28
我最近执行了关于HTML到PDF转换的PoC,并希望分享我的结果.
我最喜欢的是OpenHtmlToPdf
该工具的优点:
其他测试工具:
Kim*_*jan 24
我非常推荐NReco.它有免费和付费版本,非常值得.它在后台使用wkhtmtopdf,但你只需要一个程序集.太棒了.
使用示例:
通过NuGet安装.
var htmlContent = String.Format("<body>Hello world: {0}</body>", DateTime.Now);
var pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);
Run Code Online (Sandbox Code Playgroud)
免责声明:我不是开发人员,只是该项目的粉丝:)
fin*_*s10 24
对于所有在此处及以上寻找可行解决方案的人来说,.net 5您可以。
这是我的工作解决方案。
wkhtmltopdf:wkhtmltopdf最新版本。public static string HtmlToPdf(string outputFilenamePrefix, string[] urls,
string[] options = null,
string pdfHtmlToPdfExePath = @"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")
{
string urlsSeparatedBySpaces = string.Empty;
try
{
//Determine inputs
if ((urls == null) || (urls.Length == 0))
throw new Exception("No input URLs provided for HtmlToPdf");
else
urlsSeparatedBySpaces = String.Join(" ", urls); //Concatenate URLs
string outputFilename = outputFilenamePrefix + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff") + ".PDF"; // assemble destination PDF file name
var p = new System.Diagnostics.Process()
{
StartInfo =
{
FileName = pdfHtmlToPdfExePath,
Arguments = ((options == null) ? "" : string.Join(" ", options)) + " " + urlsSeparatedBySpaces + " " + outputFilename,
UseShellExecute = false, // needs to be false in order to redirect output
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true, // redirect all 3, as it should be all 3 or none
WorkingDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
}
};
p.Start();
// read the output here...
var output = p.StandardOutput.ReadToEnd();
var errorOutput = p.StandardError.ReadToEnd();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
// if 0 or 2, it worked so return path of pdf
if ((returnCode == 0) || (returnCode == 2))
return outputFilename;
else
throw new Exception(errorOutput);
}
catch (Exception exc)
{
throw new Exception("Problem generating PDF from HTML, URLs: " + urlsSeparatedBySpaces + ", outputFilename: " + outputFilenamePrefix, exc);
}
}
Run Code Online (Sandbox Code Playgroud)
HtmlToPdf("test", new string[] { "https://www.google.com" }, new string[] { "-s A5" });HTML字符串转换为PDF,请调整上述方法并将toArguments替换为Process StartInfo$@"/C echo | set /p=""{htmlText}"" | ""{pdfHtmlToPdfExePath}"" {((options == null) ? "" : string.Join(" ", options))} - ""C:\Users\xxxx\Desktop\{outputFilename}""";这种方法的缺点:
wkhtmltopdf不支持最新版本HTML5和CSS3. 因此,如果您尝试导出任何 html,那么CSS GRID输出将不会符合预期。chrome headless:var p = new System.Diagnostics.Process()
{
StartInfo =
{
FileName = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
Arguments = @"/C --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf-no-header --print-to-pdf=""C:/Users/Abdul Rahman/Desktop/test.pdf"" ""C:/Users/Abdul Rahman/Desktop/grid.html""",
}
};
p.Start();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
Run Code Online (Sandbox Code Playgroud)
html这会将文件转换为pdf文件。url为pdf然后使用以下Argument内容Process StartInfo@"/C --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf-no-header --print-to-pdf=""C:/Users/Abdul Rahman/Desktop/test.pdf"" ""https://www.google.com""",
这种方法的缺点:
HTML5功能CSS3。输出将与您在浏览器中查看的内容相同,但是当通过 IIS 运行时,您需要AppliactionPool在 Identity 下运行应用程序LocalSystem,或者您需要提供read/write访问IISUSRS.Selenium WebDriver:Selenium.WebDriver和Selenium.WebDriver.ChromeDriver.public async Task<byte[]> ConvertHtmlToPdf(string html)
{
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), "ApplicationName");
Directory.CreateDirectory(directory);
var filePath = Path.Combine(directory, $"{Guid.NewGuid()}.html");
await File.WriteAllTextAsync(filePath, html);
var driverOptions = new ChromeOptions();
// In headless mode, PDF writing is enabled by default (tested with driver major version 85)
driverOptions.AddArgument("headless");
using var driver = new ChromeDriver(driverOptions);
driver.Navigate().GoToUrl(filePath);
// Output a PDF of the first page in A4 size at 90% scale
var printOptions = new Dictionary<string, object>
{
{ "paperWidth", 210 / 25.4 },
{ "paperHeight", 297 / 25.4 },
{ "scale", 0.9 },
{ "pageRanges", "1" }
};
var printOutput = driver.ExecuteChromeCommandWithResult("Page.printToPDF", printOptions) as Dictionary<string, object>;
var pdf = Convert.FromBase64String(printOutput["data"] as string);
File.Delete(filePath);
return pdf;
}
Run Code Online (Sandbox Code Playgroud)
这种方法的优点:
HTML5功能CSS3。输出将与您在浏览器中查看的内容相同。这种方法的缺点:
Selenium.WebDriver.ChromeDriver需要更新Nuget包。否则,这将由于版本不匹配而引发运行时错误。如果我们在 docker 中运行应用程序,上述缺点就可以克服。我们需要做的就是在构建应用程序映像时安装 chromeDockerfile
使用这种方法,请确保添加<PublishChromeDriver>true</PublishChromeDriver>如下.csproj所示的文件:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<PublishChromeDriver>true</PublishChromeDriver>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
chrome driver这将在发布项目时发布。
这是我的工作项目存储库的链接 - HtmlToPdf
window.print()inJavaScript从浏览器生成 PDF如果用户通过浏览器使用您的应用程序,那么您可以依赖JavaScript并使用window.print()必要的内容print media css从浏览器生成 PDF。例如,从库存应用程序中的浏览器生成发票。
这种方法的优点:
这种方法的缺点:
SPA。Blazoriframe我花了几乎 2 天的时间研究可用选项并最终实施了Selenium基于解决方案并且它正在工作,之后我得出了上述答案。希望这对您有帮助并节省您的时间。
Ste*_*art 13
Winnovative提供支持HTML输入的.Net PDF库.他们提供无限制的免费试用.根据您希望部署项目的方式,这可能就足够了.
Leo*_* AB 10
您可以在无头模式下使用 Google Chrome 打印到 pdf 功能。我发现这是最简单但最强大的方法。
var url = "/sf/ask/39525531/";
var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
var output = Path.Combine(Environment.CurrentDirectory, "printout.pdf");
using (var p = new Process())
{
p.StartInfo.FileName = chromePath;
p.StartInfo.Arguments = $"--headless --disable-gpu --print-to-pdf={output} {url}";
p.Start();
p.WaitForExit();
}
Run Code Online (Sandbox Code Playgroud)
小智 8
基本PDF可用于将HTML转换为PDF:C#sample.链接到此处的示例是基于ASP.NET的,但可以从Windows窗体,WPF,ASP.NET Webforms和ASP.NET MVC使用该库.该库提供了使用不同HTML呈现引擎的选项:Internet Explorer(默认)和WebKit(最佳输出).
如果您符合条件,则可通过社区许可计划免费获得整套控件(商业应用程序).社区许可证是完整的产品,没有任何限制或水印.
注意:我为Syncfusion工作.
大多数项目很可能会包装 C/C++ 引擎,而不是从头开始实现 C# 解决方案。试试哥登堡计划。
测试一下
docker run --rm -p 3000:3000 thecodingmachine/gotenberg:6
Run Code Online (Sandbox Code Playgroud)
卷曲样品
curl --request POST \
--url http://localhost:3000/convert/url \
--header 'Content-Type: multipart/form-data' \
--form remoteURL=https://brave.com \
--form marginTop=0 \
--form marginBottom=0 \
--form marginLeft=0 \
--form marginRight=0 \
-o result.pdf
Run Code Online (Sandbox Code Playgroud)
C# 示例.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using static System.Console;
namespace Gotenberg
{
class Program
{
public static async Task Main(string[] args)
{
try
{
var client = new HttpClient();
var formContent = new MultipartFormDataContent
{
{new StringContent("https://brave.com/"), "remoteURL"},
{new StringContent("0"), "marginTop" }
};
var result = await client.PostAsync(new Uri("http://localhost:3000/convert/url"), formContent);
await File.WriteAllBytesAsync("brave.com.pdf", await result.Content.ReadAsByteArrayAsync());
}
catch (Exception ex)
{
WriteLine(ex);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译
csc sample.cs -langversion:latest -reference:System.Net.Http.dll && mono ./sample.exe
Run Code Online (Sandbox Code Playgroud)
有关HTML-to-PDF要求的好消息.正如这个答案所示,W3C标准css-break-3将解决这个问题 ......这是一个候选推荐标准,计划在经过测试后于2017年或2018年转为最终推荐标准.
由于没有那么标准,因此有一些解决方案,带有C#插件,如print-css.rocks所示.
这是一个免费的库,工作起来非常容易:OpenHtmlToPdf
string timeStampForPdfName = DateTime.Now.ToString("yyMMddHHmmssff");
string serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/FolderName");
string pdfSavePath = Path.Combine(@serverPath, "FileName" + timeStampForPdfName + ".FileExtension");
//OpenHtmlToPdf Library used for Performing PDF Conversion
var pdf = Pdf.From(HTML_String).Content();
//FOr writing to file from a ByteArray
File.WriteAllBytes(pdfSavePath, pdf.ToArray()); // Requires System.Linq
Run Code Online (Sandbox Code Playgroud)
上次更新时间:2019年9月
这是我汇总的.NET中HTML到PDF转换的选项列表(有些是免费的,有些是付费的)
HtmlRenderer.PdfSharp
木偶夏普
环氧乙烷
WnvHtmlToPdf_x64
铁Pdf
尖顶PDF
Aspose.Html
EvoPDF
ExpertPdfHtmlToPdf
邮编
PDFtron
WkHtmlToXSharp
选择PDF
如果以上选项均无济于事,您可以随时搜索NuGet软件包 https://www.nuget.org/packages?q=html+pdf
| 归档时间: |
|
| 查看次数: |
542363 次 |
| 最近记录: |