如何向文档中添加HTML内容
本文关键字:添加 HTML 内容 文档 | 更新日期: 2023-09-27 18:13:38
我正在尝试将html转换为pdf。我有一个html代码。例:
var example_html = @"<p>This
<em>is</em>
<span class=""
headline""
style=""text-decoration: underline;"">some</span>
<strong>sample
<em>text</em>
</strong>
<span style=""color: red;"">!!!</span>
</p>";
我已经添加了下面的代码来生成这个html内容到pdf,但是它抛出了一个错误说"the document has no pages"
Response.Clear();
Response.ContentType = "application/pdf";
using (Document doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
//doc.Add(new Paragraph(example_html));
using (TextReader reader = File.OpenText(Server.MapPath("~/GST/HTMLtoPDF.aspx")))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, reader);
}
doc.Close();
}
Response.End();
在文档中我需要传递或添加我的html内容对吗??但我不知道如何添加我的html内容,以便它可以解析成pdf。请帮助。谢谢你。
错误提示您没有向文档添加页面。下面的代码为我工作,它返回一个PDF标题MyDoc.pdf.
在您的问题中,您提到您想将example_html转换为PDF,但代码示例正在读取名为HTMLtoPDF.aspx的文件。确保该文件具有该HTML。我试着直接从文件和变量中读取,它在两种情况下都有效。
要添加更多的页面,您可以调用NewPage方法和HTML到该页,如下所示:
public ActionResult Index()
{
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/PDF";
HttpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + "MyDoc.pdf");
var page1 = @"<p>PAGE 1 This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
var page2 = @"<p>PAGE 2 This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
var page3 = @"<p>PAGE 3 This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
MemoryStream outputStream = new MemoryStream();
using (Document doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, new StringReader(page1));
// To add more pages you can call NewPage and add other HTML snippets
doc.NewPage();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, new StringReader(page2));
doc.NewPage();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, new StringReader(page3));
}
return View();
}
这个示例创建了一个3页的PDF,每个页面上都有不同的HTML
你可以试试这个
//HTMLString = Pass your Html , fileLocation = File Store Location
public void converttopdf(string HTMLString, string fileLocation)
{
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(fileLocation, FileMode.Create));
document.Open();
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HTMLString), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
document.Close();
}
with http://sourceforge.net/projects/itextsharp/files/itextsharp/iTextSharp-5.4.1/