<%@ 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();
//中文字型問題REF
//http://renjin.blogspot.com/2009/01/using-chinese-fonts-in-itextsharp.html
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 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>