>我正在将我的HTML表格转换为PDF:
using (MemoryStream stream = new System.IO.MemoryStream())
{
StringReader sr = new StringReader(GridHtml);
Document pdfDoc = new Document(PageSize.A0, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
return File(stream.ToArray(), "application/pdf", "Grid.pdf");
}
这工作正常,但转换后我有一些空白(nowrap)。
我的 HTML 表<td>
怎么能没有换行?
而且我的表格很长,有很多列。当页面水平很长时,扩展页面或具有长表宽度的最佳做法是什么?
这是GridHtml:
https://jsfiddle.net/2nyjhpaz/
据我了解,您使用iText5,无论如何识别white-space: nowrap
都可能存在麻烦,因此可以在从页面元素获取表格后设置表格首选项,遍历代码中的所有单元格:
// Setting a css file
ICSSResolver cssResolver = new StyleAttrCSSResolver();
ICssFile cssFile = XMLWorkerHelper.GetCSS(cssStream);
cssResolver.AddCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
// Transmitting the html file with the table
p.Parse(htmlStream);
// Obtaining the table
var table = elements[0];
var pdfTable = table as PdfPTable;
foreach (var c in pdfTable.Rows.SelectMany(r => r.GetCells()))
{
c.NoWrap = true;
}
这是官方文档的链接(尽管只有用 JAVA 编写的示例),我将其应用于我的示例。 该方法的问题在于,您可能负责处理这样的单元格宽度(如何定义单元格的宽度? ):
pdfTable.SetTotalWidth(new float[] { 500, 500, 500, 500, 500 });
pdfTable.LockedWidth = true;
否则,这些单元格可能会相互重叠。
要根据表格宽度和高度定义页面大小,您可以按以下方式执行此操作(如何根据内容定义页面大小?
var pdfDoc = new Document(new Rectangle(pdfTable.TotalWidth, pdfTable.TotalHeight), 10f, 10f, 10f, 0f);
使用 HTML<td>
nowrap 属性
<td nowrap>No wrapped</td>
的 nowrap 属性在 HTML5 中不受支持。请改用 CSS。
CSS 语法:<td style="white-space: nowrap">
测试示例在这里 https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_td_nowrap。
扩展页面的最佳方法是什么?
您可以使用Rotate()
在此处浏览页面:
iTextSharp.text.Document doc;
// ...initialize 'doc'...
// Set the page size
doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
或者使用RectangleReadOnly
设置高度和宽度的大小:
Document doc = new Document(new RectangleReadOnly(595,842,90), 88f, 88f, 10f, 10f);