代码之家  ›  专栏  ›  技术社区  ›  Dashrath

在样式中添加高度/宽度时,图像不会显示在itextsharp生成的html到pdf文档中

  •  0
  • Dashrath  · 技术社区  · 7 年前

    我正在研究动态HTML到PDF文档,并使用ckeditor编写HTML,然后使用itextsharp 5.5.10从中生成可下载的PDF。下面是我正在使用的代码

    string htmlText = "some basic HTML I wrote in ckeditor 4.0 and save in my DB to retrieve later"
    
    
    StringReader sr = new StringReader(htmlText);
    Document pdfDoc = new Document(PageSize.A4, 0, 0, 0, 18f);
    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    
    
    // instantiate the custom PdfPageEventHelper
    MyPageEventHandler e = new MyPageEventHandler()
         {
        ImageHeader = imageHeader
    };
    writer.PageEvent = e;
    
    pdfDoc.Open();
    XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
    pdfDoc.Close();
    
    // Auto Download option
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Proposal-" + pid + ".pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
    

    现在一切都很好,这多亏了这个伟大的库itextsharp,但有时它不会向PDF文件中添加很少的图像。

    在调试期间,我发现了该变量 htmlText 与我使用ekeditor保存的输入HTML相同,它包含所有 img 标签也有,但仍有一些图像没有显示在PDF中。

    下面是我的HTML中的几个标记

    <img alt="" src="http://www.mydomain/fullpath/13101571jjc-banner.png" />
    <img alt="" src="http://www.mydomain/fullpath/0c1bc6fbchart-1.png" style="width:400px" />
    <img alt="" src="http://www.mydomain/fullpath/f7802520graph1.png" style="height:288px; width:643px" />
    <img alt="" src="http://www.mydomain/fullpath/4cd70c03sample_s-l_DISTRIBUTION.jpg" style="height:756px; width:1056px" />
    

    第四张图像未显示 在我的PDF中**

    我知道这可能与 Height Width 属性打开 img公司 标签,但我无法解决它。

    注意:当我删除其中一个时,图像会正确显示 身高 宽度 或来自的两个属性 img公司 标签但使用我的代码的实际用户不会每次在HTML中添加新图像时都这样做,所以我在这里寻找合适的解决方案。

    提前感谢您的建议和解决方案。

    1 回复  |  直到 7 年前
        1
  •  2
  •   mkl    7 年前

    一方面 style 问题图像的属性如下所示:

    style="height:756px; width:1056px"
    

    另一方面,您使用A4大小的文档

    Document pdfDoc = new Document(PageSize.A4, 0, 0, 0, 18f);
    

    A4纸的宽度约为8.27英寸,每英寸96px约为794px。

    因此,对于1056px宽的图像来说,A4页面的宽度根本不够!

    因此,为了适应图像,您可以

    • 将文档大小更改为更宽的大小,或
    • 在将HTML输入iTextSharp之前,应用预处理步骤,检查并修复不适当的属性值,或者
    • 更改HTML生成过程,以不生成这样不合适的属性值。

    在你询问的另一条评论中

    要正确打印图像,图像的最大宽度和最大高度应该是多少?

    考虑到已明确将左、右和上边距设置为0,将下边距设置为18个用户单位(默认情况下,用户单位为1/72英寸),最大图像宽度可能约为794px,最大图像高度约为(1122-18*96/72)px=1098px。一定要再减去几个像素。

    当然,这取决于你的HTML没有在图像周围添加额外的边距或单元格边框或任何东西。。。