簡體   English   中英

iText7 將 HTML 轉換為 PDF“System.NullReferenceException”。

[英]iText7 convert HTML to PDF "System.NullReferenceException."

舊標題:iTextSharp 將 HTML 轉換為 PDF“文檔沒有頁面。”

我正在使用 iTextSharp 和 xmlworker 將 html 從視圖轉換為 ASP.NET Core 2.1 中的 PDF

我嘗試了很多在網上找到的代碼片段,但都產生了異常:

該文檔沒有頁面。

這是我當前的代碼:

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;
}

更新 1

感謝@Bruno Lowagie 的建議,我升級到 iText7 和 pdfHTML,但我找不到太多關於它的教程。

我試過這段代碼:

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();
      }
}

但我明白了

系統.NullReferenceException

當我調用HtmlConverter.ConvertToDocument(html, pdfWriter)

我錯過了什么嗎?


更新 2

我嘗試使用源代碼進行調試。

這是堆棧跟蹤

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-develop\itext\itext.io\itext\io\font\FontCache.cs:line 76

這是生成異常的代碼:

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

更新 3

該問題與某種緩存有關。 我不太明白是什么,但是正如您在代碼中看到的那樣,當它試圖從緩存中加載 fonts 時會生成異常。
我意識到,在一個新的項目上嘗試了相同的代碼之后。

所以我清理了解決方案,刪除了 bin、obj、.vs,殺死了 IIS Express,刪除並重新安裝了所有 nuget 包,然后再次運行,神奇地它起作用了。

然后我只需要對代碼進行一次修復:
我使用HtmlConverter.ConvertToPdf生成完整的HtmlConverter.ConvertToDocument ,而不是僅生成 15 字節文檔的 HtmlConverter.ConvertToDocument。

這是完整的代碼:

public static byte[] ToPdf(string html)
{
    using (var workStream = new MemoryStream())
    {
        using (var pdfWriter = new PdfWriter(workStream))
        {                    
            HtmlConverter.ConvertToPdf(html, pdfWriter);
            return workStream.ToArray();
        }
    }
}

我有這個完全相同的問題,並且在一直挖掘到 iText7 的 FontCache 對象並在嘗試從原始 TTF 文件創建我的 OWN FontProgram 以使用時遇到錯誤(它也因相同的空引用錯誤而失敗),我終於“解決”了我的問題。

顯然,iText 有一些內部錯誤/異常,它們只是一種“跳過”和“推過去”,因為我偶然意識到我在 Visual Studios 中禁用了“僅啟用我的代碼”,所以我的系統正在嘗試調試iText7 的代碼和我的一樣。 在我的 Visual Studio 設置(工具 > 選項 > 調試 > 常規 > 僅啟用我的代碼復選框)中重新啟用它的那一刻,問題就神奇地消失了。

Visual Studio 中的設置

所以我花了四個小時試圖解決他們代碼中的一個問題,但他們顯然找到了一些解決方法,即使在空引用失敗的情況下也可以通過該方法。

我的轉換為 PDF 功能現在工作得很好。

我也遇到了這個錯誤,但注意到它只是在第一次嘗試加載 SvgConverter 時。 所以我把這個添加到我的班級頂部,它似乎已經 修復 了隱藏的錯誤。

using iText.Kernel.Pdf;
using iText.IO.Font;
public class PdfBuilder {

    static PdfBuilder() {
        try {
            FontCache.GetRegistryNames();
        }
        catch(Exception) {
            // ignored... this forces the FontCache to initialize
        }
    }
    ...
}

我正在使用 itext 7 在控制台應用程序中一切正常。 當我在 Web/Function App 項目中使用相同的代碼時,我開始遇到以下錯誤。

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=itext.html2pdf
  StackTrace:
   at iText.Html2pdf.Attach.Impl.Tags.BrTagWorker..ctor(IElementNode element, ProcessorContext context)
   at iText.Html2pdf.Attach.Impl.DefaultTagWorkerMapping.<>c.<.cctor>b__1_10(IElementNode lhs, ProcessorContext rhs)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.Visit(INode node)
   at iText.Html2pdf.Attach.Impl.DefaultHtmlProcessor.ProcessDocument(INode root, PdfDocument pdfDocument)
   at iText.Html2pdf.HtmlConverter.ConvertToPdf(String html, PdfDocument pdfDocument, ConverterProperties converterProperties)
   at iTextSample.ConsoleApp.HtmlToPdfBuilder.RenderPdf() in C:\code\iTextSample.ConsoleApp\HtmlToPdfBuilder.cs:line 227

經過一番排查,發現是<br />標簽出了問題。 我刪除了所有<br />標簽,它工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM