简体   繁体   中英

itextsharp “the document has no pages” error when i have anchor tag

I am converting some html to pdf. It is working fine but when i have anchor tag in my html i get error the document has no pages

My code is

 byte[] data;
 using (var sr = new StringReader(sw.ToString()))
 {
    var st = new StyleSheet();

    GetStyleSheetForUnicodeCharacters(st);
    using (var ms = new MemoryStream())
    {
       using (var pdfDoc = new Document())
       {                            
           using (var w = PdfWriter.GetInstance(pdfDoc, ms))
           {
              pdfDoc.Open();
              var parsedHtmlElements = HTMLWorker.ParseToList(sr, st);
              foreach (var htmlElement in parsedHtmlElements)
              {
                 pdfDoc.Add(htmlElement as IElement);
              }
              pdfDoc.Close();
              data = ms.ToArray();
           }
       }
    }
 }

The problem may be invalid html. One way to check is to run your html source through a validator such W3C Markup Validation Service .

have you already tried to add a Page with:

pdfDoc.NewPage();

I think your Code should look like this:

byte[] data;
using (var sr = new StringReader(sw.ToString()))
{
    var st = new StyleSheet();

    GetStyleSheetForUnicodeCharacters(st);
    using (var ms = new MemoryStream())
    {
        using (var pdfDoc = new Document())
        {                            
            using (var w = PdfWriter.GetInstance(pdfDoc, ms))
            {
               pdfDoc.Open();
               pdfDoc.NewPage(); // add Page here
               var parsedHtmlElements = HTMLWorker.ParseToList(sr, st);
               foreach (var htmlElement in parsedHtmlElements)
               {
                  pdfDoc.Add(htmlElement as IElement);
               }
               pdfDoc.Close();
               data = ms.ToArray();
            }
        }
    }
}

You can also add a blank Page by using:

    pdfDoc.newPage();
    w.setPageEmpty(false);

MfG chris

Need to check that any html tags are mismatched. Example /td>, this types of mistake raised above error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM