使用ITextsharp将Html导出为PDF

我试过下面的代码,我也遇到了错误。 我正在使用最新的DLL。

String strSelectUserListBuilder = @" 

My First Heading

My first paragraph.

"; String htmlText = strSelectUserListBuilder.ToString(); List htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);

我收到了这个错误:

给定的密​​钥不在字典中。

试试这个:

 Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create)); document.Open(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(htmlText)); document.Close(); 

让我们尝试下面的代码,它将帮助您将HTML转换为PDF文件。

 String strSelectUserListBuilder = @" 

My First Heading

My first paragraph.

"; String htmlText = strSelectUserListBuilder.ToString(); CreatePDFFromHTMLFile(htmlText , pdfFileName); public void CreatePDFFromHTMLFile(string HtmlStream, string FileName) { try { object TargetFile = FileName; string ModifiedFileName = string.Empty; string FinalFileName = string.Empty; /* To add a Password to PDF -test */ TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4); TestPDF.HtmlPdfPage first = builder.AddPage(); first.AppendHtml(HtmlStream); byte[] file = builder.RenderPdf(); File.WriteAllBytes(TargetFile.ToString(), file); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString()); ModifiedFileName = TargetFile.ToString(); ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1"); string password = "password"; iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, password, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);ss reader.Close(); if (File.Exists(TargetFile.ToString())) File.Delete(TargetFile.ToString()); FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1); File.Copy(ModifiedFileName, FinalFileName); if (File.Exists(ModifiedFileName)) File.Delete(ModifiedFileName); } catch (Exception ex) { throw ex; } }