【问题标题】:Downloaded PDF Width Issue下载的 PDF 宽度问题
【发布时间】:2013-10-03 12:16:11
【问题描述】:

我正在使用下面显示的一段代码,通过 iTextSharp 库将我的网页导出为 pdf。网页分为两列,一列宽度为 90%,另一列宽度为 10%。但是,当下载为 PDF 时,两列分配相同的宽度。在下载的 PDF 中,每列占 50% 的宽度。

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=ResumeTemplate.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
wrapper.RenderControl(hw);

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

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
StringReader sr = new StringReader(sw.ToString());

HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

下面是我的 HTML 代码:

<table border="0" width="100%" id="maintable" runat="server" >
    <tr>
        <td>
            <div id="content_left" runat="server"  style="margin-right:10px; float:left;vertical-align:top;width:90%" >
                </td>
                <td>
                    <div id="content_right" runat="server" style="vertical-align:top;width:10%">
                    </div>
                    </div>
                </td>
            </tr>
        </table>

div content_leftcontent_right 在页面中以指定的宽度精确显示。当它以 Word 格式下载时,它会在网页中以精确的 css 显示。但是,当下载为 PDF 格式时,content_leftcontent_right 的宽度与页面大小相等(分配给 content_leftcontent_right 的宽度为 50%)。

【问题讨论】:

  • 您的 HTML sn-p 无效,我已对其进行了格式化,以便您可以看到第一个 &lt;div&gt; 未正确关闭。是故意的吗?这可能是您的问题的原因吗?
  • 不,这不是问题的原因,即使 div 格式正确,下载的 pdf 的 content_left 和 content_right 的宽度也会相同

标签: c# .net pdf itextsharp


【解决方案1】:

在您的代码中,div 分别是其父元素大小 (td) 的 90% 和 10%。由于表格最初设计用于显示表格而不是定义布局,因此单元格大小平衡。 td 不是 50% - 50% 或 90% - 10%。但根据内容调整大小。

在下面的 sn-p 中,我定义了 td 的大小。前后见小提琴:http://jsfiddle.net/allcaps/tEGB8/1/

<table border="1" width="100%">
    <tr>
        <td width="90%">
            <div id="content_left" style="background-color:red;">Foo</div>
        </td>
        <td width="10%">
            <div id="content_right" style="background-color:blue;">Foo</div>
        </td>
    </tr>
</table>

更新

iTextSharp 忽略表格列/单元格的宽度属性。您必须设置此线程中建议的尺寸: How to set the cell width in itextsharp pdf creation

Dim intTblWidth() As Integer = {12, 10, 26, 10}

【讨论】:

  • 是的。你是对的,上表将像下面小提琴中的那样显示。jsfiddle.net/allcaps/tEGB8/1 但是,当以 pdf 格式下载相同的内容时(代码在我的旧帖子中给出),表内的 td 将共享相等的宽度
  • 明确一点:您是否尝试将小提琴代码转换为 pdf?我不开发 .Net/iTextSharp 所以无法测试它。我知道您的 html 不会以您想要的方式呈现为 pdf。这就是我为您提供新 html 的原因。
  • 是的。我转换了小提琴代码并下载了与pdf相同的文件,问题仍然存在
  • 我觉得奇怪的是 html2pdf 工具 (iTextSharp) 不支持 html。你试过这个吗:stackoverflow.com/questions/9208482/…
  • 谢谢。该链接解决了我的宽度问题。但是,当我尝试将用户控件呈现为 pdfpcell 时,我遇到了问题。因为在我的页面中,所有控件都是动态创建的,最后将其添加到 div 中,现在我希望将该 div 添加到 PdfpCell 中,但我无法做到。
猜你喜欢
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多