txt to pdf

 

代码
<% @ Page Language = " C# "   %>
<% @ Import Namespace = " iTextSharp.text "   %>
<% @ Import Namespace = " iTextSharp.text.pdf "   %>
<% @ Import Namespace = " System.IO "   %>
< script  runat ="server" >
    protected 
void  btnConvert_Click(object sender, EventArgs e)
    {
// REF: http://www.codeproject.com/KB/graphics/iTextSharpTutorial.aspx
        Document doc  =   new  Document(PageSize.A4.Rotate());
        
        using (MemoryStream ms 
=   new  MemoryStream())
        {
 
            
try
            {
                PdfWriter.GetInstance(doc, ms);
                doc.Open();
                string fontPath 
=  
                    Environment.GetFolderPath(
                    Environment.SpecialFolder.System) 
+
                    @
" \..\Fonts\kaiu.ttf " ;
                BaseFont bfChinese 
=  BaseFont.CreateFont(
                    fontPath,
                    BaseFont.IDENTITY_H, 
// 橫式中文
                    BaseFont.NOT_EMBEDDED
                );
                Font fontChinese 
=   new  Font(bfChinese, 8f, Font.NORMAL);
                
                StringReader sr 
=   new  StringReader(txtInput.Text);
                string line 
=   null ;
                
while  ((line  =  sr.ReadLine())  !=   null )
                {
                    string[] p 
=  line.Split( ' \f ' );
                    foreach (string s 
in  p)
                    {
                        doc.Add(
new  Paragraph(s, fontChinese));
                        
if  (p.Length  >   1 // 表示有换页
                            doc.NewPage();
                    }
                }
            }
            
catch  (DocumentException de)
            {
                Response.Write(de.Message);
                Response.End();
            }
            
catch  (IOException ioe)
            {
                Response.Write(ioe.Message);
                Response.End();
            }
            doc.Close();
            
// Output PDF
            Response.Clear();
            Response.ContentType 
=   " application/octet-stream " ;
            Response.AddHeader(
" content-disposition "
                
" attachment;filename=output.pdf " );
            Response.BinaryWrite(ms.ToArray());
            Response.End();
        }
                    
    }
</ script >
 
< html  xmlns ="http://www.w3.org/1999/xhtml" >
< head  id ="Head1"  runat ="server" >
    
< title > Text to PDF demo </ title >
</ head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div >
    
< asp:TextBox  ID ="txtInput"  runat ="server"  Height ="600px"  TextMode ="MultiLine"  
            Width
="800px" ></ asp:TextBox >
    
< br  />< asp:Button  ID ="btnConvert"  runat ="server"  onclick ="btnConvert_Click"  
            Text
="Convert to PDF"   />
    
</ div >
    
</ form >
</ body >
</ html >



 

 

你可能感兴趣的:(pdf)