我尝试在ASP.NET C#中生成iTextSharp PDF文件,并将html表放入pdf文件中。 问题是该方法仅在html表有几列时才有效。只要我的表有更多列,我就不会将所有信息都输入到pdf文件中 - 它们很简单。
有没有办法自动调整表的大小,以便将表的所有信息都放到pdf文件中?我已经使用pdf页面在landscapge模式下工作了。
以下是我生成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);
String表返回正确的html字符串(标题+ html表)。
如果没有任何解决方案,是否有针对此问题的解决方法?
答案 0 :(得分:0)
我是这样做的,对于任何可能仍在努力的人来说。使用其他人的建议来编辑实际的html,我将CSS width属性添加到table。这确保它适合。您可能不得不摆弄添加font-size或其他CSS属性以使其看起来很好。只需在width属性之后添加它们。
string addCssStyling(string srhtml, string fontsize)
{
var styled = $"<style>table{{width: 100%; font-size: {fontsize};}}</style>" + srhtml;
return styled;
}