繁体   English   中英

使用ITextsharp将HTML导出为PDF

[英]Export Html to PDF using ITextsharp

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

我收到此错误:

给定的键在词典中不存在。

尝试这个:

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 = @"<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;
     }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM