我只是想使用XMLWorker將圖像添加到我的PDF文檔中。但由於某種原因,它想要一個密切的img標籤。但即使我把它放在它仍然失敗。XMLWorker:找到無效的嵌套標記div,預計結束標記img
C#代碼
Byte[] bytes;
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4.Rotate()))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
//Our HTML and CSS
string exampleHtml = @"<div style='position: relative; width: 100%'>" +
"<img src='/Content/images/certificate.jpg'><img>" +
"<div style='position: absolute; top: 100px; left: 100px; width: 800px; height: 550px; text-align: center;'>" +
"<h1>" +
"<img src='/Content/images/CertTitle.png' alt='CERTIFICATE PDF' style='width: 800px;'/>" +
"</h1>" +
"<p>" +
"The School certifies that<br/>" +
"<h2>FIRSTNAME LAST NAME TITLE</h2>" +
"has participated in the class titled<br />" +
"<h2>COURSCODE - COURSENAME</h2>" +
"This activity was designated for # Credit(s)™" +
"</p>" +
"<div style='float: left; position: absolute; bottom: 50px;'>" +
"<i>Date issued: DATE<br/></i><img src='Content/images/ceo-signature.jpg' style='border-bottom: solid #000 1px;'>" +
"</div>" +
"</div>" +
"</div>";
using (var srHtml = new StringReader(exampleHtml))
{
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml); //right here is where it crashes ({"Invalid nested tag div found, expected closing tag img."} {"The document has no pages."}
}
doc.Close();
}
}
bytes = ms.ToArray();
}
var testFile = HttpContext.Server.MapPath("~/Content/documents/UserCertificates/test.pdf"); ;
System.IO.File.WriteAllBytes(testFile, bytes);
Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
return File(testFile, "application/pdf");
我從來沒有使用結束的img標籤,所以我很好奇,如果我在這裏做什麼了嗎?
XMLWorker適用於XML。雖然HTML支持未封閉的標籤(如'img'標籤),但這不是有效的XML。您必須確保使用方法來確保您的「HTML」有效。這將是沒有什麼不同,你的「br」標籤,雖然它可能在HTML中作爲
,它會打破作爲無效的XML。 –