itextsharp error: “The document has no pages.”

2019-09-01 11:21发布

问题:

I set as references three dlls:

  • itextsharp.dll: the core library
  • itextsharp.xtra.dll: extra functionality (PDF 2!)
  • itextsharp.pdfa.dll: PDF/A-related functionality This project is hosted on http://sourceforge.net/projects/itextsharp/ You can find the latest release here: http://sourceforge.net/projects/itextsharp/files/itextsharp/

I get an error when executing this code:

On pdfDoc.Close(), "The document has no pages."

Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf


    gv.DataBind()
    gv.AllowPaging = "False"
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=Export.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Dim frm As New HtmlForm()
    gv.Parent.Controls.Add(frm)
    frm.Attributes("runat") = "server"
    frm.Controls.Add(gv)
    frm.RenderControl(hw)
    Dim sr As New StringReader(sw.ToString())
    Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
    Dim htmlparser As New HTMLWorker(pdfDoc)
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()
    htmlparser.Parse(sr)
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.[End]()

回答1:

The class HTMLWorker is deprecated and should no longer be used. HTML to PDF functionality has been replaced by technology called XML Worker. I see that you include itextsharp.xtra and itextsharp.pdfa which are 2 DLLs you don't need. I don't see you including the xmlworker DLL.

As for the exception: when you get the message "The document has no pages", you are trying to create a document without any content (and that doesn't make sense). How is this possible? Well, it all depends on the content of sr. That content is either empty or it contains HTML that can't be interpreted by HTMLWorker.

Extra remark: next to itextpdf.xtra, you wrote (PDF 2!). While the xtra package contains functonality that didn't exist in PDF 1.7, it's not the PDF 2 package. The PDF 2 specification is to be expected at the earliest by the end of 2015 (a more realistic estimation is 2016). At iText, we've already implemented PDF 2.0 functionality based on the draft of the spec, but that functionality is (1) not limited to what is in the xtra package, and (2) not part of a specification that has been publicly released by ISO yet.