使用Itext把html转换成pdf文件

itext是一个开源的pdf相关的库,水平有限,没有深入研究,有对pdf进行处理的朋友,在网上搜索一下吧。

 

最近有一个需求,需要把html转换成pdf,html主要是都是文字信息。表现不复杂,没有表格,图片。网上搜了一下,我这个情况,操作还是比较简单的。

 

下面是我的一短简单代码,已成功测试,可以把html转换成pdf文件 注意:我的html没有图片和表格,如果你有这些内容,需要你自己研究一下。还有一点,我的html是英文的,所以不考虑编码问题,如果是中文的话,应该,还要加载相应的字体的文件。


下面直接贴代码吧:


If Not IO.File.Exists(inputfile) Then
Throw New IO.FileNotFoundException("输入文件 " & inputfile & " 不存在。")
End If

Dim r As New IO.StreamReader(inputfile)

Try
Dim st As New iTextSharp.text.html.simpleparser.StyleSheet
st.LoadTagStyle(
"body", "leading", "16,0")

Dim doc As New iTextSharp.text.Document

iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
New IO.FileStream(outputfile, IO.FileMode.Create))

doc.Open()

Dim ary As ArrayList = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(r, st)

'Console.WriteLine(ary.Count)
For i As Int32 = 0 To ary.Count - 1
doc.Add(
CType(ary(i), iTextSharp.text.IElement))
Console.WriteLine(i)
Next


doc.Close()
Catch ex As Exception
Throw New System.Exception("HTML 转 PDF 发生错误。" & ex.Message, ex)
Finally
r.Close()
End Try

 


posted on 2010-12-09 22:29  zqonline  阅读(3322)  评论(2编辑  收藏  举报

导航