0
我试图在使用c#的.net应用程序中使用itextSharp将HTML内容转换为PDF。尽管如此,我可以在'<'符号之后获取我的内容。对于转换我使用下面一行:使用itextSharp将HTML转换为PDF时发生的问题<symbol
HTMLWorker.ParseToList(新StringReader(htmlContent,NULL);
这是需要添加referece'itextsharp.dll作参考
以下是代码片段代码段
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
{
}
}
}
}
}
}
你能发布代码片段吗? – Amy 2014-12-19 04:34:27
将HTML内容直接解析为PDF可能会导致意外行为,某些标记不受支持,并导致不适当的结果或损坏的文件。为什么有一个额外的<尝试后? – Codeek 2014-12-19 04:57:31
我不明白你为什么使用IElement来插入普通字符串,为什么如果你没有把它添加到pdfDoc中,你为什么创建了段落'para'?你在pdf中获得的数据量是多少,什么是截断的? – Codeek 2014-12-19 05:03:01