使用ITextsharp将Html导出为PDF

时间:2013-08-22 10:53:47

标签: c# asp.net .net itext html-to-pdf

我试过下面的代码,我也遇到了错误。我正在使用最新的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);

我收到了这个错误:

  

字典中没有给定的密钥。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:-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;
     }
 }