iText7 将 HTML 转换为 PDF “System.NullReferenceException". [英] iText7 convert HTML to PDF "System.NullReferenceException."
问题描述
OLD TITLE:iTextSharp 将 HTML 转换为 PDF文档没有页面."
我正在使用 iTextSharp 和 xmlworker 在 ASP.NET Core 2.1 中将 html 从视图转换为 PDF
我尝试了许多在网上找到的代码片段,但都生成了一个异常:文档没有页面."
这是我当前的代码:
public static byte[] ToPdf(string html){字节[] 输出;使用 (var document = new Document()){使用 (var workStream = new MemoryStream()){PdfWriter writer = PdfWriter.GetInstance(document, workStream);writer.CloseStream = false;文档.Open();使用 (var reader = new StringReader(html)){XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);文档.关闭();输出 = workStream.ToArray();}}}返回输出;}
<块引用>
更新 1
感谢@Bruno Lowagie 的建议,我升级到 iText7 和 pdfHTML ,但我找不到太多关于它的教程.
我试过这个代码:
public static byte[] ToPdf(string html){html = "<html><head><title>非常基础的标题</title></head><body>非常基础的内容</body></html>";字节[] 输出;使用 (var workStream = new MemoryStream())使用 (var pdfWriter = new PdfWriter(workStream)){使用 (var document = HtmlConverter.ConvertToDocument(html, pdfWriter)){//将文档传递给委托函数以执行某些内容、边距或页面大小操作//pdfModifier(文档);}//返回包含PDF的写入MemoryStream.返回 workStream.ToArray();}}
但我得到 System.NullReferenceException:当我调用 HtmlConverter.ConvertToDocument(html, pdfWriter)
我错过了什么吗?
<块引用>更新 2
我尝试使用源代码进行调试.
这是堆栈跟踪
System.NullReferenceExceptionHResult=0x80004003Message=未将对象引用设置为对象的实例.来源=itext.io堆栈跟踪:在 iText.IO.Font.FontCache..cctor() 在 S:Progetti*****itext7-dotnet-developitextitext.ioitextiofontFontCache.cs:line 76
这是产生异常的代码:
static FontCache() {尝试 {加载注册表();foreach(registryNames.Get(FONTS_PROP) 中的字符串字体){allCidFonts.Put(font, ReadFontProperties(font));}}捕获(异常){}
registryNames count = 0 并且 .Get(FONTS_PROP) 抛出异常
<块引用>更新 3
该问题与某种缓存有关.我真的不明白是什么,但是正如您在代码中看到的那样,当他尝试从缓存加载字体时生成了异常.在对一个新项目尝试了相同的代码后,我意识到它奏效了.
所以我清理了解决方案,删除了 bin、obj、.vs,杀死了 IIS Express,删除并重新安装了所有 nuget 包,然后再次运行,神奇地工作了.
然后我只需要对代码进行修复:我使用 HtmlConverter.ConvertToPdf
生成完整的 pdf,而不是仅生成 15 字节文档的 HtmlConverter.ConvertToDocument
.
完整代码如下:
public static byte[] ToPdf(string html){使用 (var workStream = new MemoryStream()){使用 (var pdfWriter = new PdfWriter(workStream)){HtmlConverter.ConvertToPdf(html, pdfWriter);返回 workStream.ToArray();}}}
我遇到了完全相同的问题,在一直深入到 iText7 的 FontCache 对象并尝试创建我的 OWN FontProgram 以从原始 TTF 文件(也因相同的空引用错误而失败),我终于解决"了我的问题.
显然 iText 有一些内部错误/异常,它们只是某种跳过";和推过去",因为我偶然意识到我有启用我的代码".在 Visual Studios 中被禁用,所以我的系统试图调试 iText7 的代码以及我的.在我的 Visual Studio 设置(工具 > 选项 > 调试 > 常规 > 启用仅我的代码复选框)中重新启用它的那一刻,问题就神奇地消失了.
所以我花了四个小时试图解决他们代码中的一个问题,但他们显然找到了一些解决方法,即使在空引用失败的情况下也能通过该方法.
我的转换为 PDF 功能现在工作正常.
OLD TITLE: iTextSharp convert HTML to PDF "The document has no pages."
I am using iTextSharp and xmlworker to convert html from a view to PDF in ASP.NET Core 2.1
I tried many code snippets I found online but all generate an exception: "The document has no pages."
Here is my current code:
public static byte[] ToPdf(string html)
{
byte[] output;
using (var document = new Document())
{
using (var workStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, workStream);
writer.CloseStream = false;
document.Open();
using (var reader = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
document.Close();
output = workStream.ToArray();
}
}
}
return output;
}
UPDATE 1
thanks to @Bruno Lowagie advice I upgraded to iText7 and pdfHTML , but I can't find much tutorials about it.
I tried this code:
public static byte[] ToPdf(string html)
{
html = "<html><head><title>Extremely Basic Title</title></head><body>Extremely Basic Content</body></html>";
byte[] output;
using (var workStream = new MemoryStream())
using (var pdfWriter = new PdfWriter(workStream))
{
using (var document = HtmlConverter.ConvertToDocument(html, pdfWriter))
{
//Passes the document to a delegated function to perform some content, margin or page size manipulation
//pdfModifier(document);
}
//Returns the written-to MemoryStream containing the PDF.
return workStream.ToArray();
}
}
but I get System.NullReferenceException: when I call HtmlConverter.ConvertToDocument(html, pdfWriter)
Am I missing something?
UPDATE 2
I tried to debug using source code.
This is the stack trace
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=itext.io
StackTrace:
at iText.IO.Font.FontCache..cctor() in S:Progetti*****itext7-dotnet-developitextitext.ioitextiofontFontCache.cs:line 76
This is the code that generates the exception:
static FontCache() {
try {
LoadRegistry();
foreach (String font in registryNames.Get(FONTS_PROP)) {
allCidFonts.Put(font, ReadFontProperties(font));
}
}
catch (Exception) {
}
registryNames count = 0 and .Get(FONTS_PROP) throws the exception
UPDATE 3
The problem was related due some sort of cache. I can't really understand what, but as you can see in the code the exceptions was generate when he tried to load fonts from cache. I realized that after having tried the same code to a new project and it worked.
so I cleaned the solution, deleted bin, obj, .vs, killed IIS Express, removed and reinstalled all nuget packages then run again, magically it worked.
then I had to made only a fix to the code:
instead of HtmlConverter.ConvertToDocument
that generates only 15 bytes document i used HtmlConverter.ConvertToPdf
to generate a full pdf.
Here is the complete code:
public static byte[] ToPdf(string html)
{
using (var workStream = new MemoryStream())
{
using (var pdfWriter = new PdfWriter(workStream))
{
HtmlConverter.ConvertToPdf(html, pdfWriter);
return workStream.ToArray();
}
}
}
I had this EXACT same problem, and after digging down all the way to iText7's FontCache object and getting an error when trying to create my OWN FontProgram to use from a raw TTF file (which also failed with the same null reference error), I finally "solved" my problem.
Apparently iText has some internal errors/exceptions that they are just sort of "skipping" and "pushing past", because I realized by accident that I had "Enable Just My Code" in Visual Studios disabled, and so my system was trying to debug iText7's code as well as mine. The moment that I re-enabled it in my Visual Studio settings (Tools > Options > Debugging > General > Enable Just My Code checkbox), the problem magically went away.
So I spent four hours trying to troubleshoot a problem that was in THEIR code, but that they apparently found some way to work around and push through the method anyways even on a null reference failure.
My convert to PDF function is now working just fine.
这篇关于iText7 将 HTML 转换为 PDF “System.NullReferenceException".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!