我想通过将HTML内容传递给函数来生成PDF。我已经为此使用了iTextSharp,但它在遇到表和布局时表现不佳。
有没有更好的办法?
我想通过将HTML内容传递给函数来生成PDF。我已经为此使用了iTextSharp,但它在遇到表和布局时表现不佳。
有没有更好的办法?
当前回答
对于所有在。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);
}
}
并调用上述方法HtmlToPdf("test", new string[] {"https://www.google.com"}, new string[] {"-s A5"}); 如果你需要将HTML字符串转换为PDF,调整上述方法,并将参数替换为进程StartInfo为$@"/C echo | set /p=""{htmlText}"" | ""{pdfHtmlToPdfExePath}""{((选项== null) ?"":字符串。加入(“”,选项))}-”“C: \用户桌面\ xxxx \ \ {outputFilename}”“”;
这种方法的缺点:
wkhtmltopdf的最新版本不支持最新的HTML5和CSS3。因此,如果您尝试将任何html导出为CSS GRID,那么输出将不会像预期的那样。 您需要处理并发性问题。
使用铬无头:
从这里下载并安装最新的chrome浏览器。 使用下面的代码。
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();
这将把html文件转换为pdf文件。 如果你需要将一些url转换为pdf,那么使用下面的参数来处理StartInfo
@"/C——headless——disable-gpu——run-all- composter - stagebefore -draw——print-to-pdf-no-header——print-to-pdf=""C:/Users/Abdul Rahman/Desktop/test.pdf"" ""https://www.google.com"",
这种方法的缺点:
这与最新的HTML5和CSS3特性一样。输出将与您在浏览器中查看的相同,但当通过IIS运行时,您需要在LocalSystem Identity下运行应用程序的AppliactionPool,或者您需要提供对IISUSRS的读写访问。
使用Selenium WebDriver:
安装Nuget包硒。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;
}
该方法的优点:
这只需要一个Nuget安装和工作与最新的HTML5和CSS3功能预期。输出将与您在浏览器中查看的相同。
这种方法的缺点:
这种方法需要在应用程序运行的服务器上安装最新的chrome浏览器。 如果服务器中的chrome浏览器版本更新,则需要更新Selenium.WebDriver.ChromeDriver Nuget包。否则,由于版本不匹配,将抛出运行时错误。
使用这种方法,请确保在.csproj文件中添加<PublishChromeDriver>true</PublishChromeDriver>,如下所示:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<PublishChromeDriver>true</PublishChromeDriver>
</PropertyGroup>
这将在发布项目时发布chrome驱动程序。
这是我的工作项目repo - HtmlToPdf的链接
使用JavaScript中的window.print()从浏览器生成PDF
如果用户从浏览器使用你的应用程序,那么你可以依靠JavaScript和使用window.print()和必要的打印媒体css从浏览器生成PDF。例如,生成发票从浏览器在一个库存应用程序。
该方法的优点:
不依赖于任何工具。 在浏览器中直接从HTML, CSS和JS生成PDF。 快 支持所有最新的CSS属性。
这种方法的缺点:
在像Blazor这样的SPA中,我们需要使用iframe来打印页面的部分。
在几乎花了2天的时间与可用的选项之后,我得到了上面的答案,最终实现了基于Selenium的解决方案,它正在工作。希望这能帮到你,节省你的时间。
其他回答
这取决于您的其他需求。
一个非常简单但不容易部署的解决方案是使用WebBrowser控件加载Html,然后使用Print方法打印到本地安装的PDF打印机。有一些免费的PDF打印机,WebBrowser控件是. net框架的一部分。
编辑: 如果你的Html是XHtml,你可以使用PDFizer来完成这项工作。
我之前也在找这个。我遇到了HTMLDOC http://www.easysw.com/htmldoc/,这是一个免费的开源命令行应用程序,它以HTML文件为参数,并从中输出PDF。这在我的副业项目中非常有效,但这完全取决于你真正需要什么。
制作它的公司出售编译后的二进制文件,但您可以免费从源代码下载和编译并使用它。我设法编译了一个最近的版本(1.9版本),我打算在几天内发布它的二进制安装程序,所以如果你感兴趣,我可以在发布它时立即提供它的链接。
编辑(2/25/2014):看起来文档和网站转移到http://www.msweet.org/projects.php?Z1
作为HiQPdf软件的代表,我认为最好的解决方案是HiQPdf HTML到PDF转换器。net。它包含了市场上最先进的HTML5, CSS3, SVG和JavaScript渲染引擎。还有一个免费版本的HTML到PDF库,您可以使用它来免费生成最多3个PDF页面。从HTML页面生成以字节[]为单位的PDF的最小c#代码是:
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set PDF page size, orientation and margins
htmlToPdfConverter.Document.PageSize = PdfPageSize.A4;
htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
htmlToPdfConverter.Document.Margins = new PdfMargins(0);
// convert HTML to PDF
byte[] pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
你可以找到更详细的例子。NET和MVC在HiQPdf HTML到PDF转换器的例子库。
与Winnovative HTML到PDF转换器,您可以转换HTML字符串在单行
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);
基URL用于解析HTML字符串中相对URL引用的图像。另外,你也可以在HTML中使用完整的url,或者使用src="data:image/png"作为图像标签嵌入图像。
在回答'fubaar'用户对Winnovative转换器的评论时,有必要进行更正。转换器不使用IE作为渲染引擎。它实际上不依赖于任何安装的软件,并且渲染与WebKit引擎兼容。
2018年的更新,让我们使用标准的HTML+CSS=PDF方程式!
对于html到pdf的需求,有一个好消息。正如这个答案所示,W3C标准css-break-3将解决这个问题……这是一份候选人推荐书,计划在2017年或2018年经过测试后成为正式推荐书。
由于不太标准,有一些解决方案,使用c#插件,如print-css.rocks所示。