2

我已经尝试了下面的代码,我也面临一个错误。我正在使用最新的 DLL。

String strSelectUserListBuilder = @"<html><body>
                                <h1>My First Heading</h1>
                                <p>My first paragraph.</p>
                            </body>
                        </html>";

String htmlText = strSelectUserListBuilder.ToString();

List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);

我收到了这个错误:

字典中不存在给定的键。

4

2 回答 2

6

尝试这个:

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();
于 2013-08-22T11:04:07.430 回答
-1

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

String strSelectUserListBuilder = @"<html><body>
                                <h1>My First Heading</h1>
                                <p>My first paragraph.</p>
                            </body>
                        </html>";

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;
     }
 }
于 2013-08-22T11:03:58.807 回答