2017-09-29 8 views
0

Actuellement, j'ai une application MVC Core v2.0.0 qui utilise le cadre .NET 4.7. À l'intérieur de cela, j'utilise iTextSharp pour essayer de convertir HTML en PDF. Si j'ajoute une image au HTML, je reçois l'exception suivante "La page 1 a été demandée mais le document n'a que 0 pages".images en Render iTextSharp HTML5 au format PDF

Je l'ai essayé d'utiliser une URL complète et un contenu codé en base64.

<img src=\"http://localhost:4808/images/sig1.png\"> 

<img src=\"data:application/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADsSURBVEhLtc2NbcMgAERhz9JtImXK1gtkq46RU58K9CX&#x2B;KWDpswLhdLd83dZi&#x2B;fyerx24ZEMD4cQgtcOhEfnUjj&#x2B;hEfyoHTU0opzUjvLar72oHW2gh&#x2B;5qhzL/4/v0Dd9/qB3KnOX7L7VDmVN8b6gdyuDjcZf6Wk/vqB08qXHLwUCoHWrZcTwQaoeKthwPkFM7SsuOvQFF1Q5lXm0OKAe1QxlZ6mm3ulA7lGnVgfPUDmWKnoFQO5RB50CoHcpE/0CoHcoMDYTa0QZGB0LtKK8TBkLt4GnOQKgd&#x2B;X/aQKgdMwdC7TF5IC4fiDpwW590JX1NuZQyGwAAAABJRU5ErkJggg==\" alt=\"test.png\"> 

Voici la méthode d'assistance qui ne le transforme

public static Stream GeneratePDF(string html, string css = null) 
{ 
    MemoryStream ms = new MemoryStream(); 

    //HttpRenerer.PdfSharp implemenation 
    //PdfSharp.Pdf.PdfDocument pdf = 
    // TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.Letter, 40); 
    //pdf.Save(ms, false); 

    try 
    { 
     //iTextSharp implementation 
     //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF 
     using (Document doc = new Document(PageSize.LETTER)) 
     { 
      //Create a writer that's bound to our PDF abstraction and our stream 
      using (PdfWriter writer = PdfWriter.GetInstance(doc, ms)) 
      { 
       writer.CloseStream = false; 

       if (string.IsNullOrEmpty(css)) 
       { 
        //XMLWorker also reads from a TextReader and not directly from a string 
        using (StringReader srHtml = new StringReader(html)) 
        { 
         doc.Open(); 
         iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml); 
         doc.Close(); 
        } 
       } 
       else 
       { 
        using (MemoryStream msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(css))) 
        using (MemoryStream msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html))) 
        { 
         doc.Open(); 
         iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss); 
         doc.Close(); 
        } 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     ms.Dispose(); 
     throw ex; 
    } 

    //I think this is needed to use the stream to generate a file 
    ms.Position = 0; 
    return ms; 
} 

Ici, je vous appelle ma méthode d'aide pour générer un document PDF statique.

public async Task<IActionResult> TestGenerateStaticPdf() 
{ 
    //Our sample HTML and CSS 
    example_html = "<!doctype html><head></head><body><h1>Test Report</h1><p>Printed: 2017-09-29</p><table><tbody><tr><th>User Details</th><th>Date</th><th>Image</th></tr><tr><td>John Doe</td><td>2017-09-29</td><td><img src=\"http://localhost:4808/images/sig1.png\"></td></tr></tbody></table></body>"; 
    example_css = "h1 {color:red;} img {max-height:180px;width:100%;page-break-inside:avoid;} table {border-collapse:collapse;width:100%;} table, th, td {border:1px solid black;padding:5px;page-break-inside:avoid;}"; 

    System.IO.Stream stream = ControllerHelper.GeneratePDF(example_html, example_css); 

    return File(stream, "application/pdf", "Static Pdf.pdf"); 
} 

Répondre

0

Il s'avère que iTextSharp n'honore pas le doctype et force à la place XHTML. Selon XHTML, la balise d'image doit être fermée. Si vous utilisez il semble générer sans exception. Cependant, je n'ai pas réussi à obtenir le contenu codé en base64 à afficher. Il n'y a pas d'erreur dans ce cas mais l'image n'apparaît pas.

+0

Lire [l'introduction du tutoriel pdfHTML] (https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml). Vous utilisez une ancienne technologie pour convertir HTML en PDF. iText 7 + le pdfHTML add-on supporte les tags qui ne sont pas fermés, et il prend également en charge les images base64 out-of-the-box. Voir l'entrée FAQ [Est-ce que pdfHTML peut convertir des images Base64 en PDF?] (Https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-7-frequently-asked-questions-about -pdfhtml/can-pdfhtml-render-base64-images-pdf) Mise à niveau, et vos problèmes sont résolus. –

+0

J'ai ajouté cela par nuget n'est pas une méthode de distribution prise en charge? J'aurais pensé qu'il utiliserait le dernier. – Swazimodo