【问题标题】:Resize table with too many columns in iTextSharp PDF调整 iTextSharp PDF 中列过多的表格大小
【发布时间】:2016-01-05 11:09:41
【问题描述】:

我尝试在 ASP.NET C# 中生成一个 iTextSharp PDF 文件并将一个 html 表放入 pdf 文件中。 问题是该方法仅在 html 表有几列时才有效。一旦我的表格有更多列,我就不会将所有信息都放入 pdf 文件中——它们很容易被删除。

有没有办法自动调整表格的大小,以便将表格的所有信息放入 pdf 文件中?我已经在使用 pdf 页面以景观模式工作。

这是我生成 PDF 文件的代码:

//Create a byte array that will eventually hold our final PDF
        Byte[] bytes;

        //Boilerplate iTextSharp setup here
        //Create a stream that we can write to, in this case a MemoryStream
        using (MemoryStream ms = new MemoryStream())
        {

            //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
            using (Document doc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f))
            {

                //Create a writer that's bound to our PDF abstraction and our stream
                using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
                {

                    //Open the document for writing
                    doc.Open();

                    StringBuilder sb = (StringBuilder)genObjects[1];
                    String tableName = sb.ToString();
                    Table myGenTable = (Table)genObjects[0];
                    String table = genObjects[2].ToString();

                    using (StringReader srHtml = new StringReader(table))
                    {

                        //Parse the HTML
                        iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                    }

                    doc.Close();
                }
            }

            //After all of the PDF "stuff" above is done and closed but **before** we
            //close the MemoryStream, grab all of the active bytes from the stream
            bytes = ms.ToArray();
        }

        //Now we just need to do something with those bytes.
        Response.ContentType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + friendlyName+ ".pdf");
        Response.BinaryWrite(bytes);

字符串表返回正确的 html 字符串(标题 + html 表)。

如果没有任何解决方案,是否有解决此问题的方法?

【问题讨论】:

  • 您应该调整表格 html 中的列大小。将表格写入 pdf 后,您无法对表格进行任何操作,因为它只是一堆文本和行。
  • 那么我可以调整整个表格 html 的大小吗?列大小已经尽可能小了..
  • 然后使用更小的字体,或者使用更大的“纸张”尺寸,或者考虑重新构建数据。 Pdf 只不过是一个虚拟打印机,所以如果你不能将你的 html 表格放入可打印的页面,它也不会适合 pdf。

标签: c# html asp.net itextsharp


【解决方案1】:

这就是我的做法,适用于可能仍在苦苦挣扎的任何人。使用其他人的建议来编辑实际的 html,我将 CSS width 属性添加到表中。这样可以确保它适合。您可能不得不摆弄添加 font-size 或其他 CSS 属性以使其看起来不错。只需在 width 属性之后添加它们即可。

    string addCssStyling(string srhtml, string fontsize)
    {
        var styled = $"<style>table{{width: 100%; font-size: {fontsize};}}</style>" + srhtml; 
        return styled;
    }

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多