【发布时间】:2014-12-19 04:30:22
【问题描述】:
我正在尝试使用 c# 在 .net 应用程序中使用 itextSharp 将 HTML 内容转换为 PDF。这样做时,我的内容在“
HTMLWorker.ParseToList(new StringReader(htmlContent, null);
这是需要添加引用'itextsharp.dll'引用的代码sn-p
以下是代码片段
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf.draw;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CreatePDF();
}
static void CreatePDF()
{
string fileName = string.Empty;
DateTime fileCreationDatetime = DateTime.Now;
fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_New" + fileCreationDatetime.ToString(@"HHmmss"));
string pdfPath = "D:\\" + fileName;
using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
{
//step 1
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
{
try
{
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
//pdfWriter.PageEvent = new ConsoleApplication1.ITextEvents();
//open the stream
pdfDoc.Open();
{
Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 16));
para.Alignment = Element.ALIGN_CENTER;
pdfDoc.NewPage();
string str = "<b>Try<</b>";
StringReader TheStream = new StringReader(str.ToString());
List<IElement> htmlElementsh = HTMLWorker.ParseToList(TheStream, null);
IElement htmlElementh = (IElement)htmlElementsh[0];
pdfDoc.Add((Paragraph)htmlElementh);
}
pdfDoc.Close();
}
catch (Exception ex)
{
//handle exception
}
finally
{
}
}
}
}
}
}
【问题讨论】:
-
能贴出代码sn-p吗?
-
将 HTML 内容直接解析为 PDF 可能会导致意外行为、不支持某些标签并导致结果不正确或文件损坏。为什么在 Try 之后会有一个额外的
-
我不明白您为什么要使用 IElement 插入普通字符串,如果您不将其添加到 pdfDoc 中,为什么还要创建一个段落“para”?您在 pdf 中获得了多少数据以及被截断的数据?
-
把你的 html 内容放到面板 HtmlTextWriter hw = new HtmlTextWriter(sw); panel.RenderControl(hw);
-
@Codeek :我正在使用 IElement 因为它对我的应用程序的要求,我试图生成的 pdf 是包含各种 HTML 表格的 3-4 页的 pdf,你可以忽略前 2 行。这些是实际代码。 '
标签: c# html asp.net-mvc pdf