gpt4 book ai didi

c# - MVCRazorToPdf (iTextSharp) 使用自定义字体

转载 作者:行者123 更新时间:2023-11-30 15:23:42 25 4
gpt4 key购买 nike

我正在尝试使用 nuget 包 MVCRazorToPdf 将自定义字体添加到我的 pdf 输出中,但我在执行此操作时遇到了问题,因为 iTextSharp 的文档不是很好,而且似乎都已过时。

我创建 pdf 的当前代码是:

return new PdfActionResult(
"test.cshtml",
new TestModel(),
(writer, document) =>
{
FontFactory.Register(HostingEnvironment.MapPath("~/content/fonts/vegur-regular-webfont.ttf"), "VegurRegular");
});

writer 是一个 PdfWriterdocument 是一个 Document

所有使用 FontFactory 的示例都表明您需要使用 XmlWorker 但我无权访问它,所以我想知道是否有使用 writerdocument 更改文档字体的方法?

我看到有 document.HtmlStyleClass 属性,但找不到任何关于如何在任何地方使用它的信息。

如有任何帮助,我们将不胜感激

最佳答案

MVCRazorToPdf是 iTextSharp 的 XMLWorker 的一个非常非常简单的包装器,并使用更简单的 XMLWorkerHelper 和所有默认值来完成它的工作。如果您查看 source你会看到这个:

                document.Open();


using (var reader = new StringReader(RenderRazorView(context, viewName)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);

document.Close();
output = workStream.ToArray();
}

如果您执意要使用 NuGet 版本,那么您将受困于此实现,并且您将无法注册自定义字体。

但是,有一个 open issue关于这个includes a fix所以如果你愿意 compile from source您可以应用该更改,您应该已经准备就绪。

如果您想更进一步,我建议您阅读 this great post这表明使用 iTextSharp 解析 HTML 也是多么简单 Bruno's post here显示如何注册字体。

编辑

根据包含修复链接的帖子(以防万一链接将来断开),将上面的 using 语句更改为:

        using (var reader = new MemoryStream(Encoding.UTF8.GetBytes(RenderRazorView(context, viewName))))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader, null, FontFactory.FontImp as IFontProvider);

document.Close();
output = workStream.ToArray();
}

然后在上述问题中注册的字体工厂将在使用 style="font-family:VegurRegular;"

时起作用

关于c# - MVCRazorToPdf (iTextSharp) 使用自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34200416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com