出于某种原因,我似乎无法在我的 htmlElements 上应用样式。我创建了一个样式包用于测试目的,但该样式并未应用于每个 div 元素。有人能发现我做错了什么吗?
try
{
// set the file name
string file = "C:/MyPdf.pdf";
// create a pdf document
Document document = new Document();
// set the page size, set the orientation
document.SetPageSize(PageSize.A4);
// create a writer instance
PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));
// open the document
document.Open();
// THIS STYLE IS SET FOR TESTING PURPOSES
StyleSheet styles = new StyleSheet();
styles.LoadTagStyle(HtmlTags.DIV, HtmlTags.BGCOLOR, "#ff0000");
// html pagina inlezen
string htmlText = File.ReadAllText("C:\\afl.html");
// html pagina parsen in een arraylist van IElements
List<IElement> htmlElements = HTMLWorker.ParseToList(new StringReader(htmlText), styles);
// add the IElements to the document
for (int i = 0; i < htmlElements.Count; i++)
{
// cast the element
IElement htmlElement = ((IElement)htmlElements[i]);
document.Add(htmlElement);
}
// close the document
document.Close();
// open the pdf document
//Process.Start(file);
}
catch (Exception ex)
{
var derp = ex.Message;
}
最佳答案
不再积极维护 HTMLWorker,而是鼓励您使用 XMLWorker。
也就是说,您会发现大多数标签都不支持背景颜色(可能基于表格的标签除外)。其背后的原因是 PDF 规范本身不支持背景颜色。要实现此 iText 需要使用复杂的注释或在文本后面绘制形状。
参见this link for the current XMLWorker documentation ,单击左侧导航栏中的 CSS 支持以查看支持的各种属性。
您的代码本身是正确且有效的,它只是一个不受支持的属性,不会引发任何错误。
关于c# - 将 html 转换为 pdf 时,iTextSharp 中的 HtmlTags 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438856/