Generate PDF from HTML

Generate PDF from HTML

 

 

http://sourceforge.net/projects/pdfizer

First, set a reference in your project to the 3 DLL's that Pdfizer uses. Here are the 3 dll names to set a reference to:

ICSharpCode.SharpZipLib.dll (This component is used to parse the HTML)

itextsharp.dll (This component is used by Pdfizer to create the PDF document)

Pdfizer.dll (This is the main component with the HtmlToPdf object that executes the conversion operations).

Now we can add some code to use this component. Here is the code to generate a PDF from some HTML specified:

// set a path to where you want to write the PDF to.
string sPathToWritePdfTo = @"C:/new_pdf_name.pdf";
 
// build some HTML text to write as a PDF.  You could also 
// read this HTML from a file or other means.
// NOTE: This component doesn't understand CSS or other 
// newer style HTML so you will need to use depricated 
// HTML formatting such as the <font> tag to make it look correct.
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
sbHtml.Append("<html>");
sbHtml.Append("<body>");
sbHtml.Append("<font size='14'>My Document Title Line</font>");
sbHtml.Append("<br />");
sbHtml.Append("This is my document text");
sbHtml.Append("</body>");
sbHtml.Append("</html>");
 
// create file stream to PDF file to write to
using (System.IO.Stream stream = new System.IO.FileStream

(sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))
{
    // create new instance of Pdfizer
    Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();
    // open stream to write Pdf to to
    htmlToPdf.Open(stream);
    // write the HTML to the component
    htmlToPdf.Run(sbHtml.ToString());
    // close the write operation and complete the PDF file
    htmlToPdf.Close();
}

This component also supports PDF Chapters. You could add a single line of code right before the Run() method to make the HTML specified a single chapter like this:

// open stream to write Pdf to to
htmlToPdf.Open(stream);
 
// add a chapter for this HTML
htmlToPdf.AddChapter("My Chapter Title 1");
 
// write the HTML to the component
htmlToPdf.Run(sbHtml.ToString());

Repeat the AddChapter() and Run() methods for each chapter you want to add and then Close() to commit it to the PDF.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值